<?php
// File: competition_register.php
// 🛠 Enable debugging while testing
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session only if not already active
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'db.php';
require_once 'email_helper.php';

if (!isset($_GET['id'])) {
    header("Location: /competition.php");
    exit();
}

// Fetch competition details, including entry_fee
$competition_id = intval($_GET['id']);
// ⭐️ FIX: Added entry_fee to the query
$stmt = $conn->prepare("SELECT * FROM competitions WHERE id = ?");
$stmt->bind_param("i", $competition_id);
$stmt->execute();
$comp = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$comp) {
    echo "<div class='text-center py-20 text-red-600'>Competition not found.</div>";
    exit();
}

$entry_fee = (float)$comp['entry_fee']; // Ensure it's a float

// ✅ Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $message = trim($_POST['message']);
    
    // Store entry data in session
    $_SESSION['competition_entry'] = [
        'competition_id' => $competition_id,
        'name' => $name,
        'email' => $email,
        'phone' => $phone,
        'message' => $message,
        'entry_fee' => $entry_fee // Store fee for handler
    ];

    if ($entry_fee > 0) {
        // --- PAID COMPETITION FLOW ---
        // Redirect directly to the payment handler
        header("Location: competition_payment_handler.php");
        exit();
    } else {
        // --- FREE COMPETITION FLOW (OTP) ---
        $otp = random_int(100000, 999999);
        $_SESSION['competition_entry']['otp'] = $otp;
        $_SESSION['competition_entry']['otp_expiry'] = time() + 300; // 5 minutes

        $subject = "Your UCF Competition OTP";
        $body = "
            <p>Dear <strong>$name</strong>,</p>
            <p>Your OTP for the competition <strong>{$comp['title']}</strong> is:</p>
            <h2 style='color:#5A8B48;font-size:24px;'>$otp</h2>
            <p>This code will expire in 5 minutes.</p>
            <p>Regards,<br>United Cultural Forum</p>
        ";

        if (sendEmail($email, $subject, $body)) {
            session_write_close();
            header("Location: /competition_verify_otp.php");
            exit();
        } else {
            $error_msg = "Email sending failed. Please try again.";
        }
    }
}

// 🧩 Only include header *after* all header() redirects are done
include 'header.php';
?>

<div class="bg-gray-50 py-12 md:py-20">
  <div class="max-w-3xl mx-auto bg-white p-8 rounded-xl shadow-lg">
    <h2 class="text-3xl font-extrabold text-ucf-charcoal text-center mb-2">
      Participate in "<?php echo htmlspecialchars($comp['title']); ?>"
    </h2>
    
    <!-- Show Entry Fee -->
    <p class="text-center text-gray-600 mb-6 font-medium">
        Entry Fee: 
        <?php if ($entry_fee > 0): ?>
            <span class="text-ucf-green font-bold">₹<?php echo number_format($entry_fee, 2); ?></span>
        <?php else: ?>
            <span class="text-green-600 font-bold">FREE</span>
        <?php endif; ?>
    </p>

    <?php if (isset($error_msg)): ?>
        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded">
            <?php echo $error_msg; ?>
        </div>
    <?php endif; ?>

    <form method="POST" class="space-y-6">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label class="block text-sm font-medium text-gray-700">Full Name *</label>
          <input type="text" name="name" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-ucf-green focus:border-ucf-green">
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700">Email Address *</label>
          <input type="email" name="email" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-ucf-green focus:border-ucf-green">
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700">Phone *</label>
          <input type="tel" name="phone" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-ucf-green focus:border-ucf-green">
        </div>
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700">Message (Optional)</label>
        <textarea name="message" rows="4" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-ucf-green focus:border-ucf-green"></textarea>
      </div>

      <div class="pt-6">
        <button type="submit" class="w-full bg-ucf-green hover:bg-ucf-green-dark text-white font-semibold py-3 rounded-md transition duration-150 ease-in-out">
          <?php echo ($entry_fee > 0) ? 'Proceed to Pay ₹' . number_format($entry_fee, 2) : 'Send OTP'; ?>
        </button>
      </div>
    </form>
  </div>
</div>

<?php include 'footer.php'; ?>