<?php
// Simple JSON API: GET /api/scanqrcode.php?id=123
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../main/helper/connect.php';

function json_out($arr, $code = 200) {
    http_response_code($code);
    echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    json_out(['success' => false, 'error' => 'invalid_id'], 400);
}

try {
    // Fetch user
    $stmt = $con->prepare('SELECT id, name, company_name, phone FROM users WHERE id = ? LIMIT 1');
    $stmt->execute([$id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        json_out(['success' => false, 'error' => 'user_not_found'], 404);
    }

    // Fetch latest QR for this user
    $stmt2 = $con->prepare('SELECT * FROM qrcodes WHERE user_id = ? ORDER BY created_at DESC LIMIT 1');
    $stmt2->execute([$id]);
    $qr = $stmt2->fetch(PDO::FETCH_ASSOC);
    if (!$qr) {
        json_out(['success' => false, 'error' => 'qr_not_found'], 404);
    }

    $already = (int)$qr['scanned'] === 1;
    if (!$already) {
        // Mark as scanned now
        $upd = $con->prepare('UPDATE qrcodes SET scanned = 1, scanned_at = NOW() WHERE id = ?');
        $upd->execute([$qr['id']]);
        // Re-read scanned_at
        $stmt3 = $con->prepare('SELECT scanned, scanned_at FROM qrcodes WHERE id = ?');
        $stmt3->execute([$qr['id']]);
        $qr2 = $stmt3->fetch(PDO::FETCH_ASSOC);
        $qr['scanned'] = $qr2 ? $qr2['scanned'] : 1;
        $qr['scanned_at'] = $qr2 ? $qr2['scanned_at'] : null;
    }

    json_out([
        'success' => true,
        'scanned_before' => $already,
        'user' => $user,
    ]);
} catch (Exception $e) {
    error_log('scanqrcode error: ' . $e->getMessage());
    json_out(['success' => false, 'error' => 'server_error'], 500);
}
