<?php
require_once 'connect.php';
require_once 'functions.php';
require_once __DIR__ . '/phpqrcode/qrlib.php';

/**
 * Generate data-embedded QR (CSV payload only)
 * Payload format (single line):
 *   id,name,company,phone
 * @param int $user_id
 * @param string $name
 * @param string $company_name
 * @param string $phone
 * @return array|false
 */
function generateDataQRCode($user_id, $name, $company_name, $phone) {
    global $con;
    try {
        // Ensure directory exists (renamed to unified uploads/qrcodes/)
        $qr_dir = __DIR__ . '/../../uploads/qrcodes/';
        if (!is_dir($qr_dir)) {
            if (!mkdir($qr_dir, 0755, true)) {
                throw new Exception('Failed to create Data QR directory: ' . $qr_dir);
            }
        }
        if (!is_writable($qr_dir)) {
            throw new Exception('Data QR directory is not writable: ' . $qr_dir);
        }

        // CSV payload (values only)
        $csv_line = implode(',', [
            (string)(int)$user_id,
            trim($name),
            trim($company_name),
            trim($phone)
        ]);
        $payload = $csv_line;

        // File paths
        $qr_filename = $user_id . '_data.png';
        $qr_full_path = $qr_dir . $qr_filename;
        $qr_web_path = 'uploads/qrcodes/' . $qr_filename;

        if (file_exists($qr_full_path)) {
            unlink($qr_full_path);
        }

        // Generate QR PNG
        ob_start();
        QRcode::png($payload, $qr_full_path, QR_ECLEVEL_L, 6, 2);
        ob_end_clean();

        if (!file_exists($qr_full_path) || filesize($qr_full_path) < 100) {
            throw new Exception('Data QR PNG was not created or is empty: ' . $qr_full_path);
        }

        // Save DB record (table renamed to qrcodes)
        $stmt = $con->prepare("INSERT INTO qrcodes (user_id, path, payload) VALUES (?, ?, ?)");
        $stmt->execute([$user_id, $qr_filename, $payload]);

        return [
            'path' => $qr_full_path,
            'web_path' => $qr_web_path,
            'payload' => $payload,
            'filename' => $qr_filename
        ];
    } catch (Exception $e) {
        error_log("Data QR generation error: " . $e->getMessage());
        echo '<div style="color:red;font-weight:bold;">Data QR Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
        return false;
    }
}

/**
 * Get latest Data QR for a user
 * @param int $user_id
 * @return array|false
 */
function getDataQRCode($user_id) {
    global $con;
    try {
        $stmt = $con->prepare("SELECT * FROM qrcodes WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$user_id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        error_log("Get Data QR error: " . $e->getMessage());
        return false;
    }
}
?>