<?php
if (session_status() === PHP_SESSION_NONE) session_start();
include('../config/db.php');
include('../includes/auth.php');
require_once '../includes/csrf.php';
require_once '../includes/rate_limit.php';
require_once '../includes/voucher_helpers.php';
csrf_generate();

$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
rate_limit('redeem', $ip, 60, 60);

$isJson = !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
          && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
$isPost = $_SERVER['REQUEST_METHOD'] === 'POST';
$mode   = $_POST['mode'] ?? '';
$isRedeemPost = $isPost && $mode !== 'preview';
$code   = trim(($isPost ? $_POST['code'] : $_GET['code']) ?? '');
$claimId = (int)(($isPost ? $_POST['claim_id'] : $_GET['claim_id']) ?? 0);

$status  = 'error';
$heading = 'Invalid Voucher';
$sub     = 'This voucher code does not exist.';
$v       = null;
$claim   = null;

if ($code !== '') {
    $s = $conn->prepare('SELECT * FROM vouchers WHERE code = ? LIMIT 1');
    $s->bind_param('s', $code);
    $s->execute();
    $v = $s->get_result()->fetch_assoc();
    $s->close();
}

if ($isPost) {
    csrf_verify();
}

if ($v) {
    if ($claimId > 0) {
        $cs = $conn->prepare('SELECT * FROM voucher_claims WHERE id = ? AND voucher_id = ? LIMIT 1');
        $cs->bind_param('ii', $claimId, $v['id']);
    } else {
        $cs = $conn->prepare("SELECT * FROM voucher_claims WHERE voucher_id = ? AND status = 'claimed' ORDER BY id ASC LIMIT 1");
        $cs->bind_param('i', $v['id']);
    }
    $cs->execute();
    $claim = $cs->get_result()->fetch_assoc();
    $cs->close();

    $window = voucher_window_status($v);
    if ($window === 'expired') {
        $heading = 'Voucher Expired';
        $sub     = 'This voucher expired on ' . htmlspecialchars($v['end_date']) . '.';
    } elseif ($window === 'not_started') {
        $heading = 'Not Yet Valid';
        $sub     = 'This voucher is valid from ' . htmlspecialchars($v['start_date']) . '.';
    } elseif (!$claim) {
        $heading = 'No Pending Claim';
        $sub     = 'This voucher has no pending claim to redeem.';
    } elseif ($claim['status'] === 'redeemed') {
        $heading = 'Already Redeemed';
        $sub     = 'This claim has already been used.';
    } elseif (!$isRedeemPost) {
        $status  = 'ready';
        $heading = 'Ready to Redeem';
        $sub     = htmlspecialchars($v['event_name']);
    } else {
        $conn->begin_transaction();
        try {
            $s1 = $conn->prepare("UPDATE voucher_claims SET status = 'redeemed', redeemed_at = NOW() WHERE id = ? AND voucher_id = ? AND status = 'claimed'");
            $s1->bind_param('ii', $claim['id'], $v['id']);
            $s1->execute();

            if ($s1->affected_rows === 0) {
                throw new RuntimeException('Already redeemed');
            }

            $s2 = $conn->prepare("UPDATE vouchers SET is_redeemed = 1 WHERE id = ? AND NOT EXISTS (SELECT 1 FROM voucher_claims WHERE voucher_id = ? AND status = 'claimed')");
            $s2->bind_param('ii', $v['id'], $v['id']);
            $s2->execute();

            $conn->commit();
            $status  = 'success';
            $heading = 'Redeemed Successfully';
            $sub     = htmlspecialchars($v['event_name']);
        } catch (Exception $e) {
            $conn->rollback();
            $heading = 'Already Redeemed';
            $sub     = 'This voucher claim was just used.';
        }
    }
}

if ($isJson) {
    header('Content-Type: application/json');
    echo json_encode([
        'status'   => $status,
        'heading'  => $heading,
        'sub'      => $sub,
        'code'     => $code,
        'claim_id' => $claim['id'] ?? $claimId,
        'event'    => $v['event_name'] ?? '',
        'type'     => $v['type'] ?? '',
    ]);
    exit;
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars($heading) ?> - Perna Events</title>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<style>
body{font-family:'Plus Jakarta Sans',sans-serif;background:#0d0f14;color:#dde1ee;min-height:100vh;display:grid;place-items:center;padding:24px}
.card{background:#13161e;border:1px solid #232839;border-radius:16px;padding:40px 32px;text-align:center;max-width:360px;width:100%}
.icon{font-size:56px;margin-bottom:16px}
.icon.ok{color:#2dbd87}.icon.ready{color:#e8a020}.icon.err{color:#e05252}
h2{font-size:22px;font-weight:700;margin-bottom:8px}
p{font-size:14px;color:#6b7394}
.code{font-family:monospace;font-size:12px;background:#1a1e28;padding:6px 12px;border-radius:6px;color:#e8a020;margin-top:14px;display:inline-block}
.back{display:inline-flex;align-items:center;justify-content:center;gap:6px;margin-top:14px;background:#e8a020;color:#000;border:none;padding:10px 20px;border-radius:8px;font-size:13px;font-weight:700;text-decoration:none;cursor:pointer;width:100%;font-family:inherit}
.back.secondary{background:#1a1e28;color:#dde1ee}
</style>
</head>
<body>
<div class="card">
  <div class="icon <?= $status==='success'?'ok':($status==='ready'?'ready':'err') ?>">
    <i class="bi bi-<?= $status==='success'?'check-circle-fill':($status==='ready'?'qr-code-scan':'x-circle-fill') ?>"></i>
  </div>
  <h2><?= htmlspecialchars($heading) ?></h2>
  <p><?= htmlspecialchars($sub) ?></p>
  <?php if ($v): ?>
  <div class="code"><?= htmlspecialchars($v['code']) ?></div>
  <?php endif; ?>
  <?php if ($v && $status === 'ready'): ?>
  <form method="POST" style="margin:0">
    <?php csrf_field(); ?>
    <input type="hidden" name="mode" value="redeem">
    <input type="hidden" name="code" value="<?= htmlspecialchars($code, ENT_QUOTES) ?>">
    <input type="hidden" name="claim_id" value="<?= (int)($claim['id'] ?? 0) ?>">
    <button class="back" type="submit"><i class="bi bi-check2-circle"></i>Confirm Redeem</button>
  </form>
  <?php endif; ?>
  <a href="scan.php" class="back secondary"><i class="bi bi-qr-code-scan"></i>Back to Scanner</a>
</div>
</body></html>
