<?php
// File: competition_verify_otp.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session safely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'db.php';

if (!isset($_SESSION['competition_entry'])) {
    echo "<div style='text-align:center; padding:50px; color:red;'>
            Session expired. Please <a href='/competition.php' style='color:#5A8B48;'>register again</a>.
          </div>";
    exit();
}

$entry = $_SESSION['competition_entry'];
$error = "";

// --- Form submitted ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entered_otp = trim($_POST['otp']);
    $stored_otp = $entry['otp'];
    $otp_expiry = $entry['otp_expiry'];

    // Check expiry
    if (time() > $otp_expiry) {
        $error = "Your OTP has expired. Please register again.";
        unset($_SESSION['competition_entry']);
    }
    // Check match
    elseif ($entered_otp !== (string)$stored_otp) {
        $error = "Invalid OTP. Please try again.";
    }
    else {
        // ✅ OTP Verified — Insert into DB
        try {
            $stmt = $conn->prepare("
                INSERT INTO competition_entries
                    (competition_id, name, email, phone, message, otp_verified, payment_status)
                VALUES (?, ?, ?, ?, ?, 1, 'Pending')
            ");
            $stmt->bind_param(
                "issss",
                $entry['competition_id'],
                $entry['name'],
                $entry['email'],
                $entry['phone'],
                $entry['message']
            );
            $stmt->execute();
            $stmt->close();

            // Clean session + redirect
            unset($_SESSION['competition_entry']);
            session_write_close();
            header("Location: /competition_success.php");
            exit();

        } catch (Exception $e) {
            $error = "Database error: " . htmlspecialchars($e->getMessage());
        }
    }
}
?>

<?php include 'header.php'; ?>

<div class="bg-gray-50 py-20">
  <div class="max-w-md mx-auto bg-white p-8 rounded-xl shadow-lg text-center">
    <h2 class="text-2xl font-bold mb-4 text-ucf-charcoal">Verify Your OTP</h2>

    <?php if (!empty($error)): ?>
      <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-3 mb-4 rounded">
        <?= htmlspecialchars($error) ?>
      </div>
    <?php else: ?>
      <p class="text-gray-600 mb-4">Enter the 6-digit code sent to your email.</p>
    <?php endif; ?>

    <?php if (empty($error) || str_contains($error, 'Invalid')): ?>
      <form method="POST" class="space-y-6">
        <input type="text"
               name="otp"
               maxlength="6"
               required
               placeholder="Enter OTP"
               class="border-gray-300 rounded-md text-center w-full py-3 text-xl tracking-widest shadow-sm focus:ring-ucf-green focus:border-ucf-green">
        <button type="submit"
                class="w-full bg-ucf-green hover:bg-ucf-green-dark text-white font-semibold py-3 rounded-md">
          Verify OTP
        </button>
      </form>

      <p class="text-sm text-gray-500 mt-4">
        Didn’t get the code?
        <a href="/competition_register.php?id=<?= $entry['competition_id'] ?>" class="text-ucf-green font-semibold hover:text-ucf-green-dark">Resend OTP</a>
      </p>
    <?php else: ?>
      <a href="/competition_register.php?id=<?= $entry['competition_id'] ?>" class="inline-block mt-6 bg-ucf-green text-white px-6 py-2 rounded-md hover:bg-ucf-green-dark">
        Try Again
      </a>
    <?php endif; ?>
  </div>
</div>

<?php include 'footer.php'; ?>
