<?php
// school_admission/public/branch_add_applicant.php

// --- DEBUGGING LINES START ---
// These lines will force PHP errors to display in the browser.
// REMOVE or comment them out once your application is stable and deployed to production.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// --- DEBUGGING LINES END ---


if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth_check.php';

requireRole(['branch_admin']); // Only Branch Admin can access this page

$message = '';

// Get branch_id for the current branch admin
$current_branch_id = $_SESSION['branch_id'];

// Fetch available courses for the dropdown
$courses = [];
$course_result = $conn->query("SELECT course_id, course_name FROM courses ORDER BY course_name ASC");
if ($course_result) {
    while ($row = $course_result->fetch_assoc()) {
        $courses[] = $row;
    }
    $course_result->free();
} else {
    $message .= "<div class='message error'>Error fetching courses: " . $conn->error . "</div>";
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and validate basic applicant data
    $first_name = sanitize_input($_POST['first_name']);
    $last_name = sanitize_input($_POST['last_name']);
    $other_names = sanitize_input($_POST['other_names']);
    $date_of_birth = sanitize_input($_POST['date_of_birth']);
    $marital_status = sanitize_input($_POST['marital_status']);
    $gender = sanitize_input($_POST['gender']);
    $tribe = sanitize_input($_POST['tribe']);
    $address = sanitize_input($_POST['address']);
    $phone_number = sanitize_input($_POST['phone_number']);
    $email = sanitize_input($_POST['email']);
    $course_id = (int)$_POST['course_id'];
    $level = sanitize_input($_POST['level']);

    // Parent/Guardian data
    $parent_guardian_name = sanitize_input($_POST['parent_guardian_name']);
    $parent_guardian_contact = sanitize_input($_POST['parent_guardian_contact']);
    $parent_guardian_relationship = sanitize_input($_POST['parent_guardian_relationship']);
    $parent_guardian_address = sanitize_input($_POST['parent_guardian_address']);


    // Basic validation
    if (empty($first_name) || empty($last_name) || empty($date_of_birth) || empty($marital_status) || empty($gender) || empty($tribe) || empty($address) || empty($phone_number) || empty($email) || empty($course_id) || empty($level) || empty($parent_guardian_name) || empty($parent_guardian_contact) || empty($parent_guardian_relationship) || empty($parent_guardian_address)) {
        $message = "<div class='message error'>Please fill in all required personal, course, and parent/guardian details.</div>";
    } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "<div class='message error'>Please enter a valid email address.</div>";
    } else {
        // Generate unique application number
        $application_no = generateApplicationNumber($current_branch_id);
        $application_date = date('Y-m-d');

        // Start transaction
        $conn->begin_transaction();
        try {
            // 1. Insert into applicants table
            $stmt_applicant = $conn->prepare("INSERT INTO applicants (first_name, last_name, other_names, date_of_birth, marital_status, gender, tribe, address, phone_number, email, application_no, course_id, level, application_date, branch_id, parent_guardian_name, parent_guardian_contact, parent_guardian_relationship, parent_guardian_address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            // --- DIAGNOSTIC: COUNTING PARAMETERS FOR DEBUGGING ---
            // Corrected type string for 19 variables: ssssssssssisssissss
            $bind_types_applicant = "ssssssssssisssissss"; // 19 characters (10 's', 1 'i', 3 's', 1 'i', 4 's')
            $bind_variables_applicant = [
                $first_name, $last_name, $other_names, $date_of_birth, $marital_status, $gender, $tribe, $address,
                $phone_number, $email, $application_no, $course_id, $level, $application_date, $current_branch_id,
                $parent_guardian_name, $parent_guardian_contact, $parent_guardian_relationship, $parent_guardian_address
            ];

            if (strlen($bind_types_applicant) !== count($bind_variables_applicant)) {
                // This exception will be caught by the outer catch block
                throw new Exception("CRITICAL BIND_PARAM MISMATCH (APPLICANT INSERT): Type string length (" . strlen($bind_types_applicant) . ") does not match variable count (" . count($bind_variables_applicant) . "). Please report this to support. Line " . (__LINE__ + 1));
            }
            // --- END DIAGNOSTIC ---

            $stmt_applicant->bind_param($bind_types_applicant,
                $first_name, $last_name, $other_names, $date_of_birth, $marital_status, $gender, $tribe, $address,
                $phone_number, $email, $application_no, $course_id, $level, $application_date, $current_branch_id,
                $parent_guardian_name, $parent_guardian_contact, $parent_guardian_relationship, $parent_guardian_address
            );
            
            if (!$stmt_applicant->execute()) {
                throw new Exception("Error adding applicant: " . $stmt_applicant->error);
            }
            $applicant_id = $stmt_applicant->insert_id;
            $stmt_applicant->close();

            // 2. Handle Academic Records
            if (isset($_POST['academic_records']) && is_array($_POST['academic_records'])) {
                foreach ($_POST['academic_records'] as $index => $record) {
                    $exam_type = sanitize_input($record['exam_type']);
                    $exam_year = (int)sanitize_input($record['exam_year']);
                    $subject = sanitize_input($record['subject']);
                    $grade = sanitize_input($record['grade']);

                    if (empty($exam_type) || empty($exam_year) || empty($subject) || empty($grade)) {
                        continue;
                    }

                    $attachment_path = null;
                    if (isset($_FILES['academic_records']['name'][$index]['attachment']) && $_FILES['academic_records']['error'][$index]['attachment'] == UPLOAD_ERR_OK) {
                        $file_tmp_name = $_FILES['academic_records']['tmp_name'][$index]['attachment'];
                        $file_name = $_FILES['academic_records']['name'][$index]['attachment'];
                        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                        $allowed_ext = ['pdf', 'jpg', 'jpeg', 'png'];

                        if (in_array($file_ext, $allowed_ext)) {
                            $new_file_name = uniqid('acad_') . '.' . $file_ext;
                            $upload_dir = __DIR__ . '/uploads/academic_records/';
                            if (!is_dir($upload_dir)) { 
                                if (!mkdir($upload_dir, 0777, true)) {
                                    throw new Exception("Failed to create academic records upload directory at " . $upload_dir . ". Check permissions.");
                                }
                            }
                            $destination = $upload_dir . $new_file_name;

                            if (move_uploaded_file($file_tmp_name, $destination)) {
                                $attachment_path = '/school_admission/public/uploads/academic_records/' . $new_file_name;
                            } else {
                                throw new Exception("Failed to upload academic record file for subject: " . $subject . ". Possible directory permissions issue.");
                            }
                        } else {
                            throw new Exception("Invalid file type for academic record: " . $file_name . ". Only PDF, JPG, JPEG, PNG are allowed.");
                        }
                    }

                    $stmt_academic = $conn->prepare("INSERT INTO academic_records (applicant_id, exam_type, exam_year, subject, grade, attachment_path) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt_academic->bind_param("isssss", $applicant_id, $exam_type, $exam_year, $subject, $grade, $attachment_path);
                    if (!$stmt_academic->execute()) {
                        throw new Exception("Error adding academic record: " . $stmt_academic->error);
                    }
                    $stmt_academic->close();
                }
            }

            // 3. Handle General Document Uploads
            $document_types = [
                'primary_school_cert' => 'Primary School Certificate',
                'secondary_school_cert' => 'Secondary School Certificate',
                'lga_letter' => 'L.G.A Letter',
                'passport_photo' => 'Passport Photo'
            ];

            foreach ($document_types as $input_name => $doc_type_name) {
                if (isset($_FILES[$input_name]) && $_FILES[$input_name]['error'] == UPLOAD_ERR_OK) {
                    $file_tmp_name = $_FILES[$input_name]['tmp_name'];
                    $file_name = $_FILES[$input_name]['name'];
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    $allowed_ext = ['pdf', 'jpg', 'jpeg', 'png'];
                    
                    if ($input_name == 'passport_photo') {
                        $allowed_ext = ['jpg', 'jpeg', 'png'];
                    }

                    if (in_array($file_ext, $allowed_ext)) {
                        $new_file_name = uniqid($input_name . '_') . '.' . $file_ext;
                        $upload_dir = __DIR__ . '/uploads/general_documents/';
                        if (!is_dir($upload_dir)) { 
                            if (!mkdir($upload_dir, 0777, true)) {
                                throw new Exception("Failed to create general documents upload directory at " . $upload_dir . ". Check permissions.");
                            }
                        }
                        $destination = $upload_dir . $new_file_name;

                        if (move_uploaded_file($file_tmp_name, $destination)) {
                            $file_path = '/school_admission/public/uploads/general_documents/' . $new_file_name;
                            $stmt_doc = $conn->prepare("INSERT INTO uploaded_documents (applicant_id, document_type, file_path) VALUES (?, ?, ?)");
                            $stmt_doc->bind_param("iss", $applicant_id, $doc_type_name, $file_path);
                            if (!$stmt_doc->execute()) {
                                throw new Exception("Error uploading document: " . $stmt_doc->error);
                            }
                            $stmt_doc->close();
                        } else {
                            throw new Exception("Failed to upload " . $doc_type_name . ". Possible directory permissions issue.");
                        }
                    } else {
                        throw new Exception("Invalid file type for " . $doc_type_name . ": " . $file_name . ". Only " . implode(', ', $allowed_ext) . " are allowed.");
                    }
                } elseif (in_array($input_name, ['primary_school_cert', 'secondary_school_cert', 'lga_letter', 'passport_photo'])) {
                     if (empty($_FILES[$input_name]['name'])) {
                        throw new Exception($doc_type_name . " is required but was not uploaded.");
                     }
                }
            }

            $conn->commit();
            $_SESSION['message'] = "<div class='message success'>Applicant <strong>" . htmlspecialchars($first_name . ' ' . $last_name) . "</strong> added successfully with Application No: <strong>" . htmlspecialchars($application_no) . "</strong>!</div>";
            redirect('branch_view_applicants.php');

        } catch (Exception $e) {
            $conn->rollback();
            $message = "<div class='message error'>Application failed: " . $e->getMessage() . "</div>";
            error_log("Applicant add failed: " . $e->getMessage() . " for branch " . $current_branch_id); // Log the error
        }
    }
}

include __DIR__ . '/../includes/header.php';
?>

<h2 class="mt-30">Add New Applicant</h2>

<?php if (!empty($message)): ?>
    <?php echo $message; ?>
<?php endif; ?>

<form action="branch_add_applicant.php" method="POST" enctype="multipart/form-data">
    <h3>Personal Details</h3>
    <div class="form-group">
        <label for="first_name">First Name:</label>
        <input type="text" id="first_name" name="first_name" required value="<?php echo isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="last_name">Last Name:</label>
        <input type="text" id="last_name" name="last_name" required value="<?php echo isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="other_names">Other Names (Optional):</label>
        <input type="text" id="other_names" name="other_names" value="<?php echo isset($_POST['other_names']) ? htmlspecialchars($_POST['other_names']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="date_of_birth">Date of Birth:</label>
        <input type="date" id="date_of_birth" name="date_of_birth" required value="<?php echo isset($_POST['date_of_birth']) ? htmlspecialchars($_POST['date_of_birth']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="marital_status">Marital Status:</label>
        <select id="marital_status" name="marital_status" required>
            <option value="">Select Status</option>
            <option value="Single" <?php echo (isset($_POST['marital_status']) && $_POST['marital_status'] == 'Single') ? 'selected' : ''; ?>>Single</option>
            <option value="Married" <?php echo (isset($_POST['marital_status']) && $_POST['marital_status'] == 'Married') ? 'selected' : ''; ?>>Married</option>
            <option value="Divorced" <?php echo (isset($_POST['marital_status']) && $_POST['marital_status'] == 'Divorced') ? 'selected' : ''; ?>>Divorced</option>
            <option value="Widowed" <?php echo (isset($_POST['marital_status']) && $_POST['marital_status'] == 'Widowed') ? 'selected' : ''; ?>>Widowed</option>
        </select>
    </div>
    <div class="form-group">
        <label for="gender">Gender:</label>
        <select id="gender" name="gender" required>
            <option value="">Select Gender</option>
            <option value="Male" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'Male') ? 'selected' : ''; ?>>Male</option>
            <option value="Female" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'Female') ? 'selected' : ''; ?>>Female</option>
            <option value="Other" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'Other') ? 'selected' : ''; ?>>Other</option>
        </select>
    </div>
    <div class="form-group">
        <label for="tribe">Tribe:</label>
        <input type="text" id="tribe" name="tribe" required value="<?php echo isset($_POST['tribe']) ? htmlspecialchars($_POST['tribe']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="address">Address:</label>
        <textarea id="address" name="address" rows="3" required><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address']) : ''; ?></textarea>
    </div>
    <div class="form-group">
        <label for="phone_number">Phone Number:</label>
        <input type="text" id="phone_number" name="phone_number" required value="<?php echo isset($_POST['phone_number']) ? htmlspecialchars($_POST['phone_number']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
    </div>

    <h3 class="mt-30">Parent/Guardian Data</h3>
    <div class="form-group">
        <label for="parent_guardian_name">Name:</label>
        <input type="text" id="parent_guardian_name" name="parent_guardian_name" required value="<?php echo isset($_POST['parent_guardian_name']) ? htmlspecialchars($_POST['parent_guardian_name']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="parent_guardian_contact">Contact:</label>
        <input type="text" id="parent_guardian_contact" name="parent_guardian_contact" required value="<?php echo isset($_POST['parent_guardian_contact']) ? htmlspecialchars($_POST['parent_guardian_contact']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="parent_guardian_relationship">Relationship:</label>
        <input type="text" id="parent_guardian_relationship" name="parent_guardian_relationship" placeholder="e.g., Father, Mother, Guardian" required value="<?php echo isset($_POST['parent_guardian_relationship']) ? htmlspecialchars($_POST['parent_guardian_relationship']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="parent_guardian_address">Address:</label>
        <textarea id="parent_guardian_address" name="parent_guardian_address" rows="3" required><?php echo isset($_POST['parent_guardian_address']) ? htmlspecialchars($_POST['parent_guardian_address']) : ''; ?></textarea>
    </div>

    <h3 class="mt-30">Course Details</h3>
    <div class="form-group">
        <label for="course_id">Select Course:</label>
        <select id="course_id" name="course_id" required>
            <option value="">Choose a Course</option>
            <?php foreach ($courses as $course): ?>
                <option value="<?php echo htmlspecialchars($course['course_id']); ?>" <?php echo (isset($_POST['course_id']) && $_POST['course_id'] == $course['course_id']) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($course['course_name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="form-group">
        <label for="level">Level:</label>
        <input type="text" id="level" name="level" value="NID 1" readonly> <!-- As per sample form -->
    </div>

    <h3 class="mt-30">Academic Records (WAEC/NECO/Others)</h3>
    <div id="academicRecordsContainer">
        <!-- Initial academic record entry -->
        <div class="academic-record-item form-group" id="academic-record-1">
            <h4>Academic Record #1</h4>
            <label for="academic_records_1_exam_type">Exam Type:</label>
            <select id="academic_records_1_exam_type" name="academic_records[1][exam_type]" required>
                <option value="">Select Exam Type</option>
                <option value="WAEC" <?php echo (isset($_POST['academic_records'][1]['exam_type']) && $_POST['academic_records'][1]['exam_type'] == 'WAEC') ? 'selected' : ''; ?>>WAEC</option>
                <option value="NECO" <?php echo (isset($_POST['academic_records'][1]['exam_type']) && $_POST['academic_records'][1]['exam_type'] == 'NECO') ? 'selected' : ''; ?>>NECO</option>
                <option value="Others" <?php echo (isset($_POST['academic_records'][1]['exam_type']) && $_POST['academic_records'][1]['exam_type'] == 'Others') ? 'selected' : ''; ?>>Others</option>
            </select>

            <label for="academic_records_1_exam_year">Exam Year:</label>
            <input type="number" id="academic_records_1_exam_year" name="academic_records[1][exam_year]" placeholder="e.g., 2023" required value="<?php echo isset($_POST['academic_records'][1]['exam_year']) ? htmlspecialchars($_POST['academic_records'][1]['exam_year']) : ''; ?>">

            <label for="academic_records_1_subject">Subject:</label>
            <input type="text" id="academic_records_1_subject" name="academic_records[1][subject]" placeholder="e.g., Mathematics" required value="<?php echo isset($_POST['academic_records'][1]['subject']) ? htmlspecialchars($_POST['academic_records'][1]['subject']) : ''; ?>">

            <label for="academic_records_1_grade">Grade:</label>
            <input type="text" id="academic_records_1_grade" name="academic_records[1][grade]" placeholder="e.g., A1, B2, C6" required value="<?php echo isset($_POST['academic_records'][1]['grade']) ? htmlspecialchars($_POST['academic_records'][1]['grade']) : ''; ?>">

            <label for="academic_records_1_attachment">Result Slip (PDF/Image):</label>
            <input type="file" id="academic_records_1_attachment" name="academic_records[1][attachment]" accept=".pdf,.jpg,.jpeg,.png">
        </div>
    </div>
    <div class="form-group">
        <button type="button" id="addAcademicRecord" class="btn btn-info btn-sm"><i class="fas fa-plus"></i> Add Another Academic Record</button>
    </div>

    <h3 class="mt-30">Required Documents (Photocopies)</h3>
    <p class="message info">Please upload clear scanned copies of the following documents:</p>
    <div class="form-group">
        <label for="primary_school_cert">Primary School Certificate:</label>
        <input type="file" id="primary_school_cert" name="primary_school_cert" accept=".pdf,.jpg,.jpeg,.png" required>
    </div>
    <div class="form-group">
        <label for="secondary_school_cert">Secondary School Certificate (WAEC/NECO):</label>
        <input type="file" id="secondary_school_cert" name="secondary_school_cert" accept=".pdf,.jpg,.jpeg,.png" required>
    </div>
    <div class="form-group">
        <label for="lga_letter">L.G.A Letter (Local Government Area Identification):</label>
        <input type="file" id="lga_letter" name="lga_letter" accept=".pdf,.jpg,.jpeg,.png" required>
    </div>
    <div class="form-group">
        <label for="passport_photo">Passport Photograph:</label>
        <input type="file" id="passport_photo" name="passport_photo" accept=".jpg,.jpeg,.png" required>
    </div>

    <div class="form-group mt-30">
        <button type="submit" class="btn btn-primary"><i class="fas fa-user-plus"></i> Submit Application</button>
        <a href="dashboard.php" class="btn btn-secondary">Cancel</a>
    </div>
</form>

<?php
include __DIR__ . '/../includes/footer.php';
$conn->close();
?>