<?php
// ✅ Must be FIRST
require_once 'session_init.php';
require_once 'db.php';

$otp_error = "";
$expired = false;

// Debug: Check if session is missing
if (!isset($_SESSION['registration_data'])) {
    $otp_error = "Your session expired. Please register again.";
    $expired = true;
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entered_otp = trim($_POST['otp']);

    if (!isset($_SESSION['otp']) || time() > $_SESSION['otp_expiry']) {
        $otp_error = "Your OTP has expired. Please request a new code.";
        $expired = true;
        unset($_SESSION['otp'], $_SESSION['otp_expiry']);
    } elseif ($entered_otp != $_SESSION['otp']) {
        $otp_error = "Invalid OTP. Please try again.";
    } else {
        // OTP Verified ✅
        $data = $_SESSION['registration_data'];
        $role = $data['role'];

        try {
            if ($role === 'artist') {
                session_write_close();
                header("Location: subscription_payment.php");
                exit();
            } else {
                $password_hash = password_hash($data['password'], PASSWORD_DEFAULT);
                $stmt = $conn->prepare("INSERT INTO users (username, email, password_hash, role, is_verified) VALUES (?, ?, ?, ?, 1)");
                $stmt->bind_param("ssss", $data['username'], $data['email'], $password_hash, $data['role']);
                $stmt->execute();
                $stmt->close();

                unset($_SESSION['registration_data'], $_SESSION['otp'], $_SESSION['otp_expiry']);
                session_write_close();
                header("Location: login.php?status=reg_success");
                exit();
            }
        } catch (Exception $e) {
            error_log("OTP Verification Error: " . $e->getMessage());
            $otp_error = "A server error occurred. Please try again later.";
        }
    }
}
?>

<?php include 'header.php'; ?>

<div class="bg-gray-50 py-16">
  <div class="max-w-md mx-auto bg-white p-8 rounded-lg shadow">
    <h2 class="text-2xl font-bold text-center mb-4 text-ucf-charcoal">Verify Your Account</h2>

    <?php if ($otp_error): ?>
      <div class="<?php echo $expired ? 'bg-yellow-100 border-yellow-500 text-yellow-800' : 'bg-red-100 border-red-500 text-red-700'; ?> border-l-4 p-3 mb-4 rounded">
        <?php echo htmlspecialchars($otp_error); ?>
      </div>
    <?php else: ?>
      <p class="text-gray-600 text-center mb-2">Enter the 6-digit code sent to your email.</p>
      <p class="text-center text-sm text-gray-500 mb-6">
        Code expires in <span id="timer" class="font-semibold text-red-600">2:00</span>
      </p>
    <?php endif; ?>

    <?php if (!$expired): ?>
      <form method="POST" class="space-y-6">
        <div>
          <label for="otp" class="block text-sm font-medium text-gray-700">Enter OTP</label>
          <input type="text" name="otp" id="otp" maxlength="6" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm text-center text-xl tracking-widest">
        </div>

        <button type="submit" class="w-full bg-ucf-green hover:bg-ucf-green-dark text-white font-bold py-2 px-4 rounded transition">
          Verify
        </button>
      </form>
    <?php endif; ?>
  </div>
</div>
