<?php
require_once '../../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $celebrity_id = $_POST['celebrity_id'] ?? null;
    $full_name    = trim($_POST['full_name'] ?? '');
    $email        = trim($_POST['email'] ?? '');
    $phone        = trim($_POST['phone'] ?? '');
    $role         = trim($_POST['role'] ?? '');
    $bio          = trim($_POST['bio'] ?? '');
    $location     = trim($_POST['location'] ?? '');
    $condition    = trim($_POST['condition'] ?? '');
    $experience   = trim($_POST['experience'] ?? '');
    $why          = trim($_POST['why'] ?? '');
    $dob          = trim($_POST['dob'] ?? '');
    $approved     = 0;

    if (!$celebrity_id || !$full_name || !$email || !$phone || !$role) {
        die('Missing required fields.');
    }

 // BEFORE inserting, check if email exists anywhere
$stmt = $pdo->prepare("SELECT id FROM applications WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->fetch()) {
    die("<script>alert('An application with this email already exists. Please use a different email.'); window.history.back();</script>");
}


    // Handle ID upload
    $idcard = '';
    if (isset($_FILES['idcard']) && $_FILES['idcard']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = '../images/idcards/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $fileTmp  = $_FILES['idcard']['tmp_name'];
        $fileName = basename($_FILES['idcard']['name']);
        $fileExt  = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $allowed  = ['jpg', 'jpeg', 'png', 'pdf'];

        if (!in_array($fileExt, $allowed)) {
            die('Only JPG, PNG, and PDF files are allowed for ID upload.');
        }

        $uniqueName = 'id_' . uniqid() . '.' . $fileExt;
        $destPath = $uploadDir . $uniqueName;

        if (!move_uploaded_file($fileTmp, $destPath)) {
            die('Failed to upload ID card.');
        }

        $idcard = $uniqueName;
    } else {
        die('ID card file is required.');
    }

    // Get celebrity name
    $stmt = $pdo->prepare("SELECT name FROM celebrities WHERE id = ?");
    $stmt->execute([$celebrity_id]);
    $celeb = $stmt->fetch();
    if (!$celeb) die("Celebrity not found.");

    // Insert application
    $stmt = $pdo->prepare("INSERT INTO applications (
        celebrity_id, full_name, email, phone, role, bio, status, idcard, location, `condition`, experience, why, dob, approved
    ) VALUES (
        ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?
    )");

    $stmt->execute([
        $celebrity_id,
        $full_name,
        $email,
        $phone,
        $role,
        $bio,
        $idcard,
        $location,
        $condition,
        $experience,
        $why,
        $dob,
        $approved
    ]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Application Submitted</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <style>
    body, html {
      height: 100%;
      background-color: #f8fafc;
    }
    .modal-content {
      border-radius: 1rem;
      box-shadow: 0 0 20px rgb(0 0 0 / 0.15);
    }
    .spinner-container {
      height: 250px;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      gap: 15px;
    }
    .success-icon {
      font-size: 3.5rem;
      color: #198754; /* bootstrap success color */
    }
  </style>
</head>
<body>

<!-- Modal -->
<div class="modal fade show d-block" id="appModal" tabindex="-1" aria-labelledby="appModalLabel" aria-modal="true" role="dialog" style="background: rgba(0,0,0,0.35);">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">

      <!-- Spinner View -->
      <div id="spinnerView" class="spinner-container">
        <div class="spinner-border text-primary" style="width: 5rem; height: 5rem;" role="status">
          <span class="visually-hidden">Loading...</span>
        </div>
        <div class="fs-4 fw-semibold">Submitting your application...</div>
      </div>

      <!-- Success View (hidden initially) -->
      <div id="successView" class="text-center p-4" style="display:none;">
        <h5 class="modal-title mb-3" id="appModalLabel">Application Submitted</h5>
        <p class="fs-6">Thank you, <strong><?= htmlspecialchars($full_name) ?></strong>.</p>
        <p>Your application to join <strong><?= htmlspecialchars($celeb['name']) ?></strong>'s team has been received.</p>
        <p>We'll be in touch shortly via email.</p>
        <a href="../index.php" class="btn btn-success mt-3 px-5">Back to Home</a>
      </div>

    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  window.addEventListener('DOMContentLoaded', () => {
    // After 2 seconds, hide spinner and show success message
    setTimeout(() => {
      document.getElementById('spinnerView').style.display = 'none';
      document.getElementById('successView').style.display = 'block';
    }, 2000);
  });
</script>

</body>
</html>

<?php
} else {
    echo "Invalid request.";
}
?>
