<?php
// qr.php — generates QR PNG for a voucher the logged-in user owns

require_once '../includes/rate_limit.php';
require_once '../includes/voucher_helpers.php';
require_once '../config/db.php';

$ip   = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$code = trim($_GET['code'] ?? '');
$claimId = (int)($_GET['claim_id'] ?? 0);

// Rate limit: 60 QR requests per minute per IP
rate_limit('qr', $ip, 60, 60);

// FIX: uid MUST come from the verified session, not a spoofable GET param
$uid = 0;
if (isset($_SESSION['user'])) {
    // User-facing session
    $sess = $_SESSION['user'];
    if (!empty($sess['id'])) {
        $uid = (int)$sess['id'];
    } elseif (!empty($sess['phone'])) {
        // Session may only have phone — resolve to id
        $r = $conn->prepare('SELECT id FROM customers WHERE phone=? LIMIT 1');
        $r->bind_param('s', $sess['phone']);
        $r->execute();
        $row = $r->get_result()->fetch_assoc();
        $r->close();
        $uid = (int)($row['id'] ?? 0);
    }
} elseif (isset($_SESSION['admin'])) {
    // Admin previewing a QR — allow, bypass uid check below
    $uid = -1; // sentinel: admin bypass
}

if (empty($code)) {
    http_response_code(400);
    exit('Missing code');
}

$today = date('Y-m-d');

// Check voucher validity
$s = $conn->prepare('SELECT id, start_date, end_date, is_redeemed, is_public FROM vouchers WHERE code = ? LIMIT 1');
$s->bind_param('s', $code);
$s->execute();
$v = $s->get_result()->fetch_assoc();
$s->close();

if (!$v || voucher_window_status($v, $today) !== 'ok') {
    header('Content-Type: image/gif');
    echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
    exit;
}

// Access check — only for non-admin sessions
if ($uid !== -1) {
    if ($uid <= 0) {
        header('Content-Type: image/gif');
        echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
        exit;
    }

    // Voucher QR must be tied to one pending claim owned by this user.
    if ($claimId > 0) {
        $chk = $conn->prepare("SELECT id FROM voucher_claims WHERE id=? AND customer_id=? AND voucher_id=? AND status='claimed' LIMIT 1");
        $chk->bind_param('iii', $claimId, $uid, $v['id']);
    } else {
        $chk = $conn->prepare("SELECT id FROM voucher_claims WHERE customer_id=? AND voucher_id=? AND status='claimed' ORDER BY id ASC LIMIT 1");
        $chk->bind_param('ii', $uid, $v['id']);
    }
    $chk->execute();
    $claimRow = $chk->get_result()->fetch_assoc();
    $chk->close();
    if (!$claimRow) {
        header('Content-Type: image/gif');
        echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
        exit;
    }
    $claimId = (int)$claimRow['id'];
} elseif ($claimId <= 0) {
    $chk = $conn->prepare("SELECT id FROM voucher_claims WHERE voucher_id=? AND status='claimed' ORDER BY id ASC LIMIT 1");
    $chk->bind_param('i', $v['id']);
    $chk->execute();
    $claimRow = $chk->get_result()->fetch_assoc();
    $chk->close();
    $claimId = (int)($claimRow['id'] ?? 0);
}

// Build dynamic redeem URL
$proto    = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host     = $_SERVER['HTTP_HOST'];
$claimUrl = $proto . '://' . $host . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . '/redeem.php?code=' . urlencode($code);
if ($claimId > 0) {
    $claimUrl .= '&claim_id=' . urlencode((string)$claimId);
}

// Generate QR
require_once '../phpqrcode/qrlib.php';
header('Content-Type: image/png');
header('Cache-Control: private, max-age=300');
QRcode::png($claimUrl, false, 'M', 6, 2);
