<?php
// school_admission/public/branch_edit_applicant.php

// --- DEBUGGING LINES START ---
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 = '';
$applicant_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$current_branch_id = $_SESSION['branch_id'];
$applicant = null;
$academic_records = [];
$uploaded_documents = [];
$courses = [];

if ($applicant_id === 0) {
    $_SESSION['message'] = "<div class='message error'>Invalid applicant ID.</div>";
    redirect('branch_view_applicants.php');
}

// Fetch available courses for the dropdown
$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>";
}


// Fetch applicant's main details
$stmt_applicant = $conn->prepare("SELECT * FROM applicants WHERE applicant_id = ? AND branch_id = ?");
$stmt_applicant->bind_param("ii", $applicant_id, $current_branch_id);
$stmt_applicant->execute();
$result_applicant = $stmt_applicant->get_result();

if ($result_applicant->num_rows === 1) {
    $applicant = $result_applicant->fetch_assoc();
} else {
    $_SESSION['message'] = "<div class='message error'>Applicant not found or you don't have permission to view this applicant.</div>";
    redirect('branch_view_applicants.php');
}
$stmt_applicant->close();

// Fetch academic records
$stmt_acad = $conn->prepare("SELECT * FROM academic_records WHERE applicant_id = ? ORDER BY record_id ASC");
$stmt_acad->bind_param("i", $applicant_id);
$stmt_acad->execute();
$result_acad = $stmt_acad->get_result();
while ($row = $result_acad->fetch_assoc()) {
    $academic_records[] = $row;
}
$stmt_acad->close();

// Fetch uploaded documents
$stmt_docs = $conn->prepare("SELECT * FROM uploaded_documents WHERE applicant_id = ? ORDER BY uploaded_at ASC");
$stmt_docs->bind_param("i", $applicant_id);
$stmt_docs->execute();
$result_docs = $stmt_docs->get_result();
while ($row = $result_docs->fetch_assoc()) {
    $uploaded_documents[] = $row;
}
$stmt_docs->close();


// Handle form submission for updates
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Only allow editing if the application is still 'pending_review'
    if ($applicant['status'] !== 'pending_review') {
        $message = "<div class='message error'>Cannot edit a submitted application once it is no longer pending review.</div>";
    } else {
        // Sanitize and validate basic applicant data (UPDATED)
        $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 (UPDATED)
        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 {
            $conn->begin_transaction();
            try {
                // 1. Update applicants table
                $stmt_update_applicant = $conn->prepare("UPDATE applicants SET first_name=?, last_name=?, other_names=?, date_of_birth=?, marital_status=?, gender=?, tribe=?, address=?, phone_number=?, email=?, course_id=?, level=?, parent_guardian_name=?, parent_guardian_contact=?, parent_guardian_relationship=?, parent_guardian_address=? WHERE applicant_id=? AND branch_id=?");
                
                // --- DIAGNOSTIC: COUNTING PARAMETERS FOR DEBUGGING ---
                // Type string for 16 SET variables + 2 WHERE variables = 18 characters: ssssssssssisssssii
                $bind_types_applicant_update = "ssssssssssisssssii"; // 18 characters
                $bind_variables_applicant_update = [
                    $first_name, $last_name, $other_names, $date_of_birth, $marital_status, $gender, $tribe, $address,
                    $phone_number, $email, $course_id, $level,
                    $parent_guardian_name, $parent_guardian_contact, $parent_guardian_relationship, $parent_guardian_address,
                    $applicant_id, $current_branch_id
                ];

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

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

                // 2. Handle Academic Records Updates/Additions/Deletions
                // For simplicity, we'll delete all and re-insert for now, or you'd manage IDs
                $stmt_delete_acad = $conn->prepare("DELETE FROM academic_records WHERE applicant_id = ?");
                $stmt_delete_acad->bind_param("i", $applicant_id);
                $stmt_delete_acad->execute();
                $stmt_delete_acad->close();

                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']);
                        $existing_attachment_path = isset($record['existing_attachment_path']) ? sanitize_input($record['existing_attachment_path']) : null;

                        if (empty($exam_type) || empty($exam_year) || empty($subject) || empty($grade)) {
                            continue; // Skip incomplete records
                        }

                        $attachment_path = $existing_attachment_path; // Default to existing if no new upload
                        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)) {
                                // Delete old file if new one is uploaded
                                if ($existing_attachment_path && file_exists(__DIR__ . '/..' . $existing_attachment_path)) {
                                    unlink(__DIR__ . '/..' . $existing_attachment_path);
                                }
                                $new_file_name = uniqid('acad_') . '.' . $file_ext;
                                $upload_dir = __DIR__ . '/uploads/academic_records/';
                                if (!is_dir($upload_dir)) { mkdir($upload_dir, 0777, true); }
                                $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 new academic record file.");
                                }
                            } else {
                                throw new Exception("Invalid file type for academic record: " . $file_name . ". Only PDF, JPG, JPEG, PNG are allowed.");
                            }
                        }

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

                // 3. Handle General Document Updates
                $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)) {
                            // Find and delete old file if it exists
                            $stmt_old_doc = $conn->prepare("SELECT file_path FROM uploaded_documents WHERE applicant_id = ? AND document_type = ?");
                            $stmt_old_doc->bind_param("is", $applicant_id, $doc_type_name);
                            $stmt_old_doc->execute();
                            $result_old_doc = $stmt_old_doc->get_result();
                            if ($old_doc_row = $result_old_doc->fetch_assoc()) {
                                if (file_exists(__DIR__ . '/..' . $old_doc_row['file_path'])) {
                                    unlink(__DIR__ . '/..' . $old_doc_row['file_path']);
                                }
                                // Delete from DB too
                                $stmt_delete_old_doc = $conn->prepare("DELETE FROM uploaded_documents WHERE applicant_id = ? AND document_type = ?");
                                $stmt_delete_old_doc->bind_param("is", $applicant_id, $doc_type_name);
                                $stmt_delete_old_doc->execute();
                                $stmt_delete_old_doc->close();
                            }
                            $stmt_old_doc->close();

                            $new_file_name = uniqid($input_name . '_') . '.' . $file_ext;
                            $upload_dir = __DIR__ . '/uploads/general_documents/';
                            if (!is_dir($upload_dir)) { mkdir($upload_dir, 0777, true); }
                            $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_insert = $conn->prepare("INSERT INTO uploaded_documents (applicant_id, document_type, file_path) VALUES (?, ?, ?)");
                                $stmt_doc_insert->bind_param("iss", $applicant_id, $doc_type_name, $file_path);
                                if (!$stmt_doc_insert->execute()) {
                                    throw new Exception("Error inserting new document: " . $stmt_doc_insert->error);
                                }
                                $stmt_doc_insert->close();
                            } else {
                                throw new Exception("Failed to upload new " . $doc_type_name);
                            }
                        } else {
                            throw new Exception("Invalid file type for " . $doc_type_name . ": " . $file_name . ". Only " . implode(', ', $allowed_ext) . " are allowed.");
                        }
                    }
                }

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

            } catch (Exception $e) {
                $conn->rollback();
                $message = "<div class='message error'>Update failed: " . $e->getMessage() . "</div>";
                error_log("Applicant update failed: " . $e->getMessage() . " for applicant ID " . $applicant_id);
            }
        }
    }
    // Re-fetch data after a failed POST attempt to display current form state
    if (!empty($message)) {
        // Re-fetch existing data using original queries
        $stmt_applicant = $conn->prepare("SELECT * FROM applicants WHERE applicant_id = ? AND branch_id = ?");
        $stmt_applicant->bind_param("ii", $applicant_id, $current_branch_id);
        $stmt_applicant->execute();
        $result_applicant = $stmt_applicant->get_result();
        $applicant = $result_applicant->fetch_assoc(); // Reload applicant data
        $stmt_applicant->close();

        $stmt_acad = $conn->prepare("SELECT * FROM academic_records WHERE applicant_id = ? ORDER BY record_id ASC");
        $stmt_acad->bind_param("i", $applicant_id);
        $stmt_acad->execute();
        $result_acad = $stmt_acad->get_result();
        $academic_records = []; // Clear and reload
        while ($row = $result_acad->fetch_assoc()) {
            $academic_records[] = $row;
        }
        $stmt_acad->close();

        $stmt_docs = $conn->prepare("SELECT * FROM uploaded_documents WHERE applicant_id = ? ORDER BY uploaded_at ASC");
        $stmt_docs->bind_param("i", $applicant_id);
        $stmt_docs->execute();
        $result_docs = $stmt_docs->get_result();
        $uploaded_documents = []; // Clear and reload
        while ($row = $result_docs->fetch_assoc()) {
            $uploaded_documents[] = $row;
        }
        $stmt_docs->close();
    }
}


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

<h2 class="mt-30">View/Edit Applicant: <?php echo htmlspecialchars($applicant['first_name'] . ' ' . $applicant['last_name']); ?> (<?php echo htmlspecialchars($applicant['application_no']); ?>)</h2>

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

<?php if ($applicant['status'] !== 'pending_review'): ?>
    <div class="message info">This application's status is "<?php echo ucwords(str_replace('_', ' ', htmlspecialchars($applicant['status']))); ?>". You can no longer edit it.</div>
<?php endif; ?>

<form action="branch_edit_applicant.php?id=<?php echo $applicant_id; ?>" 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 htmlspecialchars($applicant['first_name']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </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 htmlspecialchars($applicant['last_name']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </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 htmlspecialchars($applicant['other_names']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </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 htmlspecialchars($applicant['date_of_birth']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </div>
    <div class="form-group">
        <label for="marital_status">Marital Status:</label>
        <select id="marital_status" name="marital_status" required <?php echo ($applicant['status'] !== 'pending_review' ? 'disabled' : ''); ?>>
            <option value="">Select Status</option>
            <option value="Single" <?php echo ($applicant['marital_status'] == 'Single') ? 'selected' : ''; ?>>Single</option>
            <option value="Married" <?php echo ($applicant['marital_status'] == 'Married') ? 'selected' : ''; ?>>Married</option>
            <option value="Divorced" <?php echo ($applicant['marital_status'] == 'Divorced') ? 'selected' : ''; ?>>Divorced</option>
            <option value="Widowed" <?php echo ($applicant['marital_status'] == 'Widowed') ? 'selected' : ''; ?>>Widowed</option>
        </select>
    </div>
    <div class="form-group">
        <label for="gender">Gender:</label>
        <select id="gender" name="gender" required <?php echo ($applicant['status'] !== 'pending_review' ? 'disabled' : ''); ?>>
            <option value="">Select Gender</option>
            <option value="Male" <?php echo ($applicant['gender'] == 'Male') ? 'selected' : ''; ?>>Male</option>
            <option value="Female" <?php echo ($applicant['gender'] == 'Female') ? 'selected' : ''; ?>>Female</option>
            <option value="Other" <?php echo ($applicant['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 htmlspecialchars($applicant['tribe']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </div>
    <div class="form-group">
        <label for="address">Address:</label>
        <textarea id="address" name="address" rows="3" required <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>><?php echo htmlspecialchars($applicant['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 htmlspecialchars($applicant['phone_number']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required value="<?php echo htmlspecialchars($applicant['email']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </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 htmlspecialchars($applicant['parent_guardian_name']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </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 htmlspecialchars($applicant['parent_guardian_contact']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </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 htmlspecialchars($applicant['parent_guardian_relationship']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>
    </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 ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>><?php echo htmlspecialchars($applicant['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 <?php echo ($applicant['status'] !== 'pending_review' ? 'disabled' : ''); ?>>
            <option value="">Choose a Course</option>
            <?php foreach ($courses as $course): ?>
                <option value="<?php echo htmlspecialchars($course['course_id']); ?>" <?php echo ($applicant['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="<?php echo htmlspecialchars($applicant['level']); ?>" readonly>
    </div>

    <h3 class="mt-30">Academic Records (WAEC/NECO/Others)</h3>
    <div id="academicRecordsContainer">
        <?php if (empty($academic_records)): ?>
            <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 <?php echo ($applicant['status'] !== 'pending_review' ? 'disabled' : ''); ?>>
                    <option value="">Select Exam Type</option>
                    <option value="WAEC">WAEC</option>
                    <option value="NECO">NECO</option>
                    <option value="Others">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 <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>

                <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 <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>

                <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 <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>

                <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" <?php echo ($applicant['status'] !== 'pending_review' ? 'disabled' : ''); ?>>
            </div>
        <?php else: ?>
            <?php $record_count_js = 0; ?>
            <?php foreach ($academic_records as $index => $record): ?>
                <?php $record_count_js = $index + 1; // For JS counter ?>
                <div class="academic-record-item form-group" id="academic-record-<?php echo $record_count_js; ?>">
                    <h4>Academic Record #<?php echo $record_count_js; ?></h4>
                    <label for="academic_records_<?php echo $record_count_js; ?>_exam_type">Exam Type:</label>
                    <select id="academic_records_<?php echo $record_count_js; ?>_exam_type" name="academic_records[<?php echo $record_count_js; ?>][exam_type]" required <?php echo ($applicant['status'] !== 'pending_review' ? 'disabled' : ''); ?>>
                        <option value="">Select Exam Type</option>
                        <option value="WAEC" <?php echo ($record['exam_type'] == 'WAEC') ? 'selected' : ''; ?>>WAEC</option>
                        <option value="NECO" <?php echo ($record['exam_type'] == 'NECO') ? 'selected' : ''; ?>>NECO</option>
                        <option value="Others" <?php echo ($record['exam_type'] == 'Others') ? 'selected' : ''; ?>>Others</option>
                    </select>

                    <label for="academic_records_<?php echo $record_count_js; ?>_exam_year">Exam Year:</label>
                    <input type="number" id="academic_records_<?php echo $record_count_js; ?>_exam_year" name="academic_records[<?php echo $record_count_js; ?>][exam_year]" placeholder="e.g., 2023" required value="<?php echo htmlspecialchars($record['exam_year']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>

                    <label for="academic_records_<?php echo $record_count_js; ?>_subject">Subject:</label>
                    <input type="text" id="academic_records_<?php echo $record_count_js; ?>_subject" name="academic_records[<?php echo $record_count_js; ?>][subject]" placeholder="e.g., Mathematics" required value="<?php echo htmlspecialchars($record['subject']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>

                    <label for="academic_records_<?php echo $record_count_js; ?>_grade">Grade:</label>
                    <input type="text" id="academic_records_<?php echo $record_count_js; ?>_grade" name="academic_records[<?php echo $record_count_js; ?>][grade]" placeholder="e.g., A1, B2, C6" required value="<?php echo htmlspecialchars($record['grade']); ?>" <?php echo ($applicant['status'] !== 'pending_review' ? 'readonly' : ''); ?>>

                    <label for="academic_records_<?php echo $record_count_js; ?>_attachment">Result Slip (PDF/Image):</label>
                    <?php if ($record['attachment_path']): ?>
                        <p>Current: <a href="<?php echo htmlspecialchars($record['attachment_path']); ?>" target="_blank"><i class="fas fa-file-alt"></i> View File</a></p>
                        <input type="hidden" name="academic_records[<?php echo $record_count_js; ?>][existing_attachment_path]" value="<?php echo htmlspecialchars($record['attachment_path']); ?>">
                        <?php if ($applicant['status'] === 'pending_review'): ?>
                             <p>Replace File:</p>
                             <input type="file" id="academic_records_<?php echo $record_count_js; ?>_attachment" name="academic_records[<?php echo $record_count_js; ?>][attachment]" accept=".pdf,.jpg,.jpeg,.png">
                        <?php endif; ?>
                    <?php else: ?>
                        <input type="file" id="academic_records_<?php echo $record_count_js; ?>_attachment" name="academic_records[<?php echo $record_count_js; ?>][attachment]" accept=".pdf,.jpg,.jpeg,.png" <?php echo ($applicant['status'] !== 'pending_review' ? 'disabled' : ''); ?>>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <?php if ($applicant['status'] === 'pending_review'): ?>
        <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>
    <?php endif; ?>


    <h3 class="mt-30">Required Documents (Photocopies)</h3>
    <p class="message info">View or update clear scanned copies of the following documents:</p>
    <?php
    $document_inputs = [
        'primary_school_cert' => 'Primary School Certificate',
        'secondary_school_cert' => 'Secondary School Certificate',
        'lga_letter' => 'L.G.A Letter',
        'passport_photo' => 'Passport Photograph'
    ];

    foreach ($document_inputs as $input_name => $doc_label):
        $found_doc = null;
        foreach ($uploaded_documents as $doc) {
            if ($doc['document_type'] == $doc_label) {
                $found_doc = $doc;
                break;
            }
        }
    ?>
        <div class="form-group">
            <label for="<?php echo $input_name; ?>"><?php echo $doc_label; ?>:</label>
            <?php if ($found_doc): ?>
                <p>Current: <a href="<?php echo htmlspecialchars($found_doc['file_path']); ?>" target="_blank"><i class="fas fa-file-alt"></i> View File</a></p>
                <?php if ($applicant['status'] !== 'pending_review'): ?>
                    <p>File cannot be changed as application is not pending review.</p>
                <?php else: ?>
                    <p>Replace File:</p>
                    <input type="file" id="<?php echo $input_name; ?>" name="<?php echo $input_name; ?>" accept="<?php echo ($input_name == 'passport_photo' ? '.jpg,.jpeg,.png' : '.pdf,.jpg,.jpeg,.png'); ?>">
                <?php endif; ?>
            <?php else: ?>
                <p class="message error">No file uploaded for this document.</p>
                <?php if ($applicant['status'] === 'pending_review'): ?>
                    <input type="file" id="<?php echo $input_name; ?>" name="<?php echo $input_name; ?>" accept="<?php echo ($input_name == 'passport_photo' ? '.jpg,.jpeg,.png' : '.pdf,.jpg,.jpeg,.png'); ?>" required>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>

    <div class="form-group mt-30">
        <?php if ($applicant['status'] === 'pending_review'): ?>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Update Application</button>
        <?php endif; ?>
        <a href="branch_view_applicants.php" class="btn btn-secondary">Back to Applicants</a>
    </div>
</form>

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