<?php
// submit_admission.php (MySQLi - procedural, NO OOP)
require __DIR__ . '/db.php';

function clean($v) { return htmlspecialchars(trim($v ?? ''), ENT_QUOTES, 'UTF-8'); }

// === Read & sanitize inputs ===
$full_name        = clean($_POST['full_name'] ?? '');
$father_name      = clean($_POST['father_name'] ?? '');
$father_number    = clean($_POST['father_number'] ?? '');
$gender           = clean($_POST['gender'] ?? ''); // <-- NEW
$cnic             = clean($_POST['cnic'] ?? '');
$dob              = clean($_POST['dob'] ?? '');
$contact_number   = clean($_POST['contact_number'] ?? '');
$email            = clean($_POST['email'] ?? '');
$address          = clean($_POST['address'] ?? '');
$course           = clean($_POST['course'] ?? '');
$preferred_timing = clean($_POST['preferred_timing'] ?? '');
$preferred_start  = clean($_POST['preferred_start_date'] ?? '');

// === Basic validations ===
$errors = [];
if ($full_name === '')                               $errors[] = "Full Name is required.";
if ($father_name === '')                              $errors[] = "Father’s Name is required.";
if ($father_number === '' || !preg_match('/^0[0-9]{3}-?[0-9]{7}$/', $father_number)) $errors[] = "Father’s Number format is invalid.";
if ($gender === '' || !in_array($gender, ['Male','Female','Other'])) $errors[] = "Gender is required.";
if ($cnic === '' || !preg_match('/^[0-9]{5}-[0-9]{7}-[0-9]$/', $cnic)) $errors[] = "CNIC/B-Form format is invalid.";
if ($dob === '')                                      $errors[] = "Date of Birth is required.";
if ($contact_number === '' || !preg_match('/^0[0-9]{3}-?[0-9]{7}$/', $contact_number)) $errors[] = "Contact Number format is invalid.";
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid Email is required.";
if ($address === '')                                  $errors[] = "Address is required.";
if ($course === '')                                   $errors[] = "Course selection is required.";
if ($preferred_timing === '')                         $errors[] = "Preferred timing is required.";
if ($preferred_start === '')                          $errors[] = "Preferred start date is required.";

// === File upload (optional) ===
$uploaded_path = null;
if (isset($_FILES['cnic_file']) && $_FILES['cnic_file']['error'] !== UPLOAD_ERR_NO_FILE) {
  $f = $_FILES['cnic_file'];
  if ($f['error'] !== UPLOAD_ERR_OK) {
    $errors[] = "File upload failed. Error code: " . $f['error'];
  } else {
    $maxBytes = 2 * 1024 * 1024; // 2MB
    if ($f['size'] > $maxBytes) {
      $errors[] = "File too large (max 2MB).";
    } else {
      $allowed = [
        'image/png'        => 'png',
        'image/jpeg'       => 'jpg',
        'application/pdf'  => 'pdf'
      ];
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $mime  = finfo_file($finfo, $f['tmp_name']); finfo_close($finfo);
      if (!isset($allowed[$mime])) {
        $errors[] = "Invalid file type. Allowed: PNG, JPG, PDF.";
      } else {
        $dir = __DIR__ . '/uploads';
        if (!is_dir($dir)) mkdir($dir, 0775, true);
        $ext = $allowed[$mime];
        $safeBase = preg_replace('/[^a-zA-Z0-9-_]/', '_', substr($full_name,0,32));
        $filename = $safeBase . '_' . time() . '.' . $ext;
        $dest = $dir . '/' . $filename;
        if (!move_uploaded_file($f['tmp_name'], $dest)) {
          $errors[] = "Failed to save uploaded file.";
        } else {
          $uploaded_path = 'uploads/' . $filename; // relative path for DB
        }
      }
    }
  }
}

// === If errors, show and exit ===
if (!empty($errors)) {
  echo "<h3>Fix the following:</h3><ul>";
  foreach ($errors as $e) echo "<li>" . $e . "</li>";
  echo "</ul><p><a href='index.html'>&larr; Back</a></p>";
  exit;
}

// === Insert into DB (MySQLi prepared statement) ===
$sql = "INSERT INTO admission_requests
(full_name, father_name, father_number, gender, cnic, dob, contact_number, email, address,
 requested_course, preferred_timing, preferred_start_date, cnic_file_path, status, created_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,'PENDING', NOW())";

$stmt = mysqli_prepare($conn, $sql);
if (!$stmt) {
  die("Prepare failed: " . mysqli_error($conn));
}

// 13 string params:
if (!mysqli_stmt_bind_param(
  $stmt,
  "sssssssssssss",
  $full_name, $father_name, $father_number, $gender, $cnic, $dob,
  $contact_number, $email, $address, $course, $preferred_timing,
  $preferred_start, $uploaded_path
)) {
  die("Bind failed: " . mysqli_stmt_error($stmt));
}

if (!mysqli_stmt_execute($stmt)) {
  die("Execute failed: " . mysqli_stmt_error($stmt));
}
mysqli_stmt_close($stmt);

// === Done ===
echo "<h2>Application Received ✅</h2>
<p>Thanks, <strong>$full_name</strong>. Your request is now <b>PENDING</b> review.</p>
<ul>
  <li><b>Gender:</b> $gender</li>
  <li><b>Course:</b> $course</li>
  <li><b>Preferred Timing:</b> $preferred_timing</li>
  <li><b>Preferred Start:</b> $preferred_start</li>
</ul>
<p><a href='index.html'>&larr; Submit another</a></p>";
