<?php
$conn = new mysqli("localhost", "root", "", "hesed_admissions");
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);

// Sanitize inputs
function clean($data) {
    return htmlspecialchars(trim($data));
}

// Assign variables
$full_name = clean($_POST['full_name']);
$dob = $_POST['dob'];
$gender = clean($_POST['gender']);
$nationality = clean($_POST['nationality']);
$state = clean($_POST['state']);
$lga = clean($_POST['lga']);
$religion = clean($_POST['religion']);
$previous_school = clean($_POST['previous_school']);
$last_class = clean($_POST['last_class']);
$class_intended = clean($_POST['class_intended']);
$performance = clean($_POST['performance']);
$parent_name = clean($_POST['parent_name']);
$parent_phone = clean($_POST['parent_phone']);
$email = clean($_POST['email']);
$occupation = clean($_POST['occupation']);
$relationship = clean($_POST['relationship']);
$address = clean($_POST['address']);

// Check for duplicates
$check = $conn->prepare("SELECT * FROM applications WHERE email=? OR parent_phone=?");
$check->bind_param("ss", $email, $parent_phone);
$check->execute();
$result = $check->get_result();
if ($result->num_rows > 0) {
    die("<p style='color:red;'>Duplicate application detected. You have already submitted this form.</p>");
}

// File uploads
$upload_dir = "uploads/";
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

function uploadFile($file, $name) {
    global $upload_dir;
    $allowed = ['image/jpeg', 'image/png', 'application/pdf'];
    if ($file['error'] === 0 && in_array($file['type'], $allowed)) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = uniqid($name . "_", true) . "." . $ext;
        move_uploaded_file($file['tmp_name'], $upload_dir . $filename);
        return $upload_dir . $filename;
    } else {
        die("<p style='color:red;'>Error with $name upload. Please upload a valid JPG, PNG, or PDF file.</p>");
    }
}

// Upload each file (adjust input names exactly as in your form)
$passport = uploadFile($_FILES['passport'], 'passport');
$birth_cert = uploadFile($_FILES['birth_certificate'], 'birthcert');
$result_file = uploadFile($_FILES['academic_result'], 'result');
$receipt = uploadFile($_FILES['receipt'], 'receipt');

// Generate unique 4-digit form number
do {
    $form_number = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
    $exists = $conn->query("SELECT id FROM applications WHERE form_number='$form_number'");
} while ($exists->num_rows > 0);

// Insert into database
$stmt = $conn->prepare("INSERT INTO applications (
    full_name, dob, gender, nationality, state, lga, religion,
    previous_school, last_class, class_intended, performance,
    parent_name, parent_phone, email, occupation, relationship, address,
    passport_path, birth_cert_path, result_path, receipt_path, form_number
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

$stmt->bind_param("ssssssssssssssssssssss",
    $full_name, $dob, $gender, $nationality, $state, $lga, $religion,
    $previous_school, $last_class, $class_intended, $performance,
    $parent_name, $parent_phone, $email, $occupation, $relationship, $address,
    $passport, $birth_cert, $result_file, $receipt, $form_number
);

if ($stmt->execute()) {
    // Show preview + print button
    echo "
    <!DOCTYPE html>
    <html lang='en'>
    <head>
        <meta charset='UTF-8'>
        <title>Application Submitted - Preview</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                background: #f9f9f9;
                padding: 30px;
            }
            .container {
                background: #fff;
                max-width: 700px;
                margin: auto;
                padding: 20px 30px;
                border-radius: 8px;
                box-shadow: 0 0 15px rgba(0,0,0,0.1);
            }
            h2 {
                color: #28a745;
                text-align: center;
                margin-bottom: 30px;
            }
            table {
                width: 100%;
                border-collapse: collapse;
            }
            td, th {
                padding: 10px;
                border: 1px solid #ccc;
                vertical-align: top;
            }
            th {
                background: #f1f1f1;
                width: 35%;
                text-align: left;
            }
            .btn-print {
                margin-top: 20px;
                display: block;
                width: 150px;
                padding: 10px;
                text-align: center;
                background: #007bff;
                color: white;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                font-size: 16px;
            }
            .btn-print:hover {
                background: #0056b3;
            }
            img.passport {
                max-width: 150px;
                max-height: 150px;
                border: 1px solid #ccc;
            }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='card'>
            <h2>🎉 Application Submitted Successfully</h2>
            <p class='info'>
                Thank you, <span class='highlight'>$full_name</span>.<br>
                Your Reg. Number is: <span class='highlight'>$form_number</span><br>
                Your application for <span class='highlight'>$class_intended</span> has been received.<br>
                Use your Registration Number to check your admission status.
            </p>
        </div>
            
            <table>
                <tr><th>Full Name</th><td>" . htmlspecialchars($full_name) . "</td></tr>
                <tr><th>Date of Birth</th><td>" . htmlspecialchars($dob) . "</td></tr>
                <tr><th>Gender</th><td>" . htmlspecialchars($gender) . "</td></tr>
                <tr><th>Nationality</th><td>" . htmlspecialchars($nationality) . "</td></tr>
                <tr><th>State of Origin</th><td>" . htmlspecialchars($state) . "</td></tr>
                <tr><th>LGA</th><td>" . htmlspecialchars($lga) . "</td></tr>
                <tr><th>Religion</th><td>" . htmlspecialchars($religion) . "</td></tr>
                <tr><th>Previous School</th><td>" . htmlspecialchars($previous_school) . "</td></tr>
                <tr><th>Last Class Completed</th><td>" . htmlspecialchars($last_class) . "</td></tr>
                <tr><th>Class Intended</th><td>" . htmlspecialchars($class_intended) . "</td></tr>
                <tr><th>Academic Performance</th><td>" . htmlspecialchars($performance) . "</td></tr>
                <tr><th>Parent/Guardian Name</th><td>" . htmlspecialchars($parent_name) . "</td></tr>
                <tr><th>Parent Phone</th><td>" . htmlspecialchars($parent_phone) . "</td></tr>
                <tr><th>Email</th><td>" . htmlspecialchars($email) . "</td></tr>
                <tr><th>Occupation</th><td>" . htmlspecialchars($occupation) . "</td></tr>
                <tr><th>Relationship</th><td>" . htmlspecialchars($relationship) . "</td></tr>
                <tr><th>Address</th><td>" . nl2br(htmlspecialchars($address)) . "</td></tr>
                <tr><th>Passport Photograph</th><td><img src='" . htmlspecialchars($passport) . "' class='passport' alt='Passport'></td></tr>
                <tr><th>Birth Certificate</th><td><a href='" . htmlspecialchars($birth_cert) . "' target='_blank'>View Document</a></td></tr>
                <tr><th>Academic Result/Transfer Letter</th><td><a href='" . htmlspecialchars($result_file) . "' target='_blank'>View Document</a></td></tr>
                <tr><th>Payment Receipt</th><td><a href='" . htmlspecialchars($receipt) . "' target='_blank'>View Document</a></td></tr>
                <tr><th>Registration Number</th><td><strong>" . htmlspecialchars($form_number) . "</strong></td></tr>
            </table>
            <button class='btn-print' onclick='window.print()'>Print Application</button>
        </div>
    </body>
    </html>
    ";
} else {
    echo "<p style='color:red;'>❌ Error submitting application. Please try again.</p>";
}
?>
