<?php
/**
 * IBVTE Admin – Edit Student Details
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (!checkDBConnection()) exit;
Auth()->requireRole(['super_admin', 'admin']);

$db     = DB();
$user   = Auth()->getUser();
$id     = intval($_GET['id'] ?? 0);
$flash  = null;

$student = $db->fetchOne("
    SELECT s.*, c.course_name, c.course_code, c.duration_text as duration_label, cat.name as course_category,
           sub.name as sub_name
    FROM students s
    LEFT JOIN courses c ON s.course_id = c.id
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN course_sub_categories sub ON c.sub_category_id = sub.id
    WHERE s.id = ?
", [$id]);

if (!$student) {
    redirectWithMessage('students.php', 'Student not found.', 'danger');
}

// Fetch Courses and Categories for Dropdowns
$categories = $db->fetchAll("SELECT * FROM course_categories WHERE is_active=1 ORDER BY name");
$courses = $db->fetchAll("SELECT c.*, cf.total_fee, cat.name as cat_name FROM courses c LEFT JOIN course_fees cf ON c.id=cf.course_id AND cf.user_type='college' LEFT JOIN course_categories cat ON c.category_id=cat.id WHERE c.is_active=1 ORDER BY cat.name, c.course_name");

// Decode JSON arrays
$qualifications = [];
if (!empty($student['qualifications_json'])) {
    $qualifications = json_decode($student['qualifications_json'], true) ?: [];
}

$docsAttached = [];
if (!empty($student['documents_attached'])) {
    $docsAttached = json_decode($student['documents_attached'], true) ?: [];
}

// Handle Update POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $flash = ['type' => 'danger', 'message' => 'Security session expired. Please try again.'];
    } else {
        // Retrieve inputs
        $fullName      = cleanInput($_POST['full_name'] ?? '');
        $fatherName    = cleanInput($_POST['father_name'] ?? '');
        $motherName    = cleanInput($_POST['mother_name'] ?? '');
        $guardianName  = cleanInput($_POST['guardian_name'] ?? '');
        $dob           = cleanInput($_POST['date_of_birth'] ?? '');
        $genderRaw     = cleanInput($_POST['gender'] ?? '');
        $gender        = strtolower($genderRaw);
        $bloodGroup    = cleanInput($_POST['blood_group'] ?? '');
        $aadhaarNo     = cleanInput($_POST['aadhaar_no'] ?? '');
        $religion      = cleanInput($_POST['religion'] ?? '');
        $catRaw        = cleanInput($_POST['category'] ?? '');
        $category      = ($catRaw === 'GEN') ? 'general' : strtolower($catRaw);
        $domicileState = cleanInput($_POST['domicile_state'] ?? '');

        $permAddress   = cleanInput($_POST['permanent_address'] ?? '');
        $permDistrict  = cleanInput($_POST['permanent_district'] ?? '');
        $permState     = cleanInput($_POST['permanent_state'] ?? '');
        $permPincode   = cleanInput($_POST['permanent_pincode'] ?? '');

        $corrAddress   = cleanInput($_POST['correspondence_address'] ?? '');
        $corrDistrict  = cleanInput($_POST['correspondence_district'] ?? '');
        $corrState     = cleanInput($_POST['correspondence_state'] ?? '');
        $corrPincode   = cleanInput($_POST['correspondence_pincode'] ?? '');

        $mobile        = cleanInput($_POST['mobile'] ?? '');
        $email         = cleanInput($_POST['email'] ?? '');
        $trainingPeriod = cleanInput($_POST['training_period'] ?? '');
        $examining     = cleanInput($_POST['examining_body'] ?? 'INDIAN BOARD OF VOCATIONAL AND TECHNICAL EDUCATION (New Delhi)');

        $session       = cleanInput($_POST['session_year'] ?? '');
        $courseId      = intval($_POST['course_id'] ?? 0);
        $admDate       = cleanInput($_POST['admission_date'] ?? '');
        
        $rollNumber    = cleanInput($_POST['roll_number'] ?? '');
        $status        = cleanInput($_POST['status'] ?? 'pending');
        $approvalStatus= cleanInput($_POST['approval_status'] ?? 'pending');

        $admissionFee  = floatval($_POST['admission_fee'] ?? 0);
        $registrationFee = floatval($_POST['registration_fee'] ?? 0);
        $totalFee      = $admissionFee + $registrationFee;
        $paymentMode   = cleanInput($_POST['payment_mode'] ?? '');
        $paymentReceipt = cleanInput($_POST['payment_receipt_no'] ?? '');
        $paymentDate   = cleanInput($_POST['payment_date'] ?? '');

        // Educational qualifications json array
        $newQualifications = [];
        if (isset($_POST['exam_passed']) && is_array($_POST['exam_passed'])) {
            foreach ($_POST['exam_passed'] as $idx => $exam) {
                if (!empty($exam)) {
                    $newQualifications[] = [
                        'exam_passed' => cleanInput($exam),
                        'board_university' => cleanInput($_POST['board_university'][$idx] ?? ''),
                        'year_of_passing' => cleanInput($_POST['year_of_passing'][$idx] ?? ''),
                        'roll_no' => cleanInput($_POST['roll_no'][$idx] ?? ''),
                        'percentage_division' => cleanInput($_POST['percentage_division'][$idx] ?? '')
                    ];
                }
            }
        }
        $qualificationsJson = json_encode($newQualifications);

        // Upload folders
        $photoDir = __DIR__ . '/../uploads/students/photos/';
        $sigDir   = __DIR__ . '/../uploads/students/signatures/';
        $docDir   = __DIR__ . '/../uploads/students/documents/';

        foreach ([$photoDir, $sigDir, $docDir] as $d) {
            if (!is_dir($d)) @mkdir($d, 0777, true);
        }

        // Photo Upload
        $photoPath = $student['photo_path'];
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === 0) {
            $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png'])) {
                $fn  = $student['registration_number'] . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['photo']['tmp_name'], $photoDir . $fn)) {
                    $photoPath = 'uploads/students/photos/' . $fn;
                }
            }
        }

        // Student Signature
        $studentSigPath = $student['student_signature_path'];
        if (isset($_FILES['student_signature']) && $_FILES['student_signature']['error'] === 0) {
            $ext = strtolower(pathinfo($_FILES['student_signature']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png'])) {
                $fn  = 'student_sig_' . $student['registration_number'] . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['student_signature']['tmp_name'], $sigDir . $fn)) {
                    $studentSigPath = 'uploads/students/signatures/' . $fn;
                }
            }
        }

        // Parent Signature
        $parentSigPath = $student['parent_signature_path'];
        if (isset($_FILES['parent_signature']) && $_FILES['parent_signature']['error'] === 0) {
            $ext = strtolower(pathinfo($_FILES['parent_signature']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png'])) {
                $fn  = 'parent_sig_' . $student['registration_number'] . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['parent_signature']['tmp_name'], $sigDir . $fn)) {
                    $parentSigPath = 'uploads/students/signatures/' . $fn;
                }
            }
        }

        // Dynamic Document Uploads
        $docMapping = [
            'Passport Size Photos'      => 'photos',
            'Aadhaar Card Copy'         => 'aadhaar',
            'Marksheets Copy'           => 'marksheets',
            'Transfer Certificate (TC)' => 'tc',
            'Migration Certificate'     => 'migration',
            'Category Certificate'      => 'category',
            'Address Proof'             => 'addr_proof',
            'Domicile Certificate'      => 'domicile'
        ];

        $newDocsAttached = $docsAttached; // keep previous values by default
        if (isset($_POST['documents_attached']) && is_array($_POST['documents_attached'])) {
            // Re-evaluate checkboxes
            $submittedCheckboxes = $_POST['documents_attached'];
            
            // Clean up missing/unchecked ones
            foreach ($newDocsAttached as $docName => $oldPath) {
                if (!in_array($docName, $submittedCheckboxes)) {
                    unset($newDocsAttached[$docName]);
                }
            }

            // Process checkboxes and handle uploaded files
            foreach ($submittedCheckboxes as $docName) {
                $fileSlug = $docMapping[$docName] ?? '';
                $filePath = $newDocsAttached[$docName] ?? ''; // default to existing path
                
                if ($fileSlug && isset($_FILES['doc_file_' . $fileSlug]) && $_FILES['doc_file_' . $fileSlug]['error'] === 0) {
                    $ext = strtolower(pathinfo($_FILES['doc_file_' . $fileSlug]['name'], PATHINFO_EXTENSION));
                    if (in_array($ext, ['jpg', 'jpeg', 'png', 'pdf'])) {
                        $fn = 'doc_' . $fileSlug . '_' . $student['registration_number'] . '_' . time() . '.' . $ext;
                        if (move_uploaded_file($_FILES['doc_file_' . $fileSlug]['tmp_name'], $docDir . $fn)) {
                            $filePath = 'uploads/students/documents/' . $fn;
                        }
                    }
                }
                $newDocsAttached[$docName] = $filePath;
            }
        } else {
            $newDocsAttached = [];
        }
        $docsAttachedJson = json_encode($newDocsAttached);
        $docsAttachedOther = cleanInput($_POST['documents_attached_other'] ?? '');

        // Update database record
        $db->update('students', [
            'full_name'              => $fullName,
            'father_name'            => $fatherName,
            'mother_name'            => $motherName,
            'guardian_name'          => $guardianName,
            'date_of_birth'          => $dob,
            'gender'                 => $gender,
            'blood_group'            => $bloodGroup,
            'aadhaar_no'             => $aadhaarNo,
            'religion'               => $religion,
            'category'               => $category,
            'domicile_state'         => $domicileState,
            
            'address'                => $permAddress,
            'city'                   => $permDistrict,
            'state'                  => $permState,
            'pincode'                => $permPincode,
            
            'permanent_address'      => $permAddress,
            'permanent_district'     => $permDistrict,
            'permanent_state'        => $permState,
            'permanent_pincode'      => $permPincode,
            'correspondence_address' => $corrAddress,
            'correspondence_district'=> $corrDistrict,
            'correspondence_state'   => $corrState,
            'correspondence_pincode' => $corrPincode,
            
            'qualifications_json'    => $qualificationsJson,
            'documents_attached'     => $docsAttachedJson,
            'documents_attached_other'=> $docsAttachedOther,
            
            'admission_fee'          => $admissionFee,
            'registration_fee'       => $registrationFee,
            'payment_mode'           => $paymentMode,
            'payment_receipt_no'     => $paymentReceipt,
            'payment_date'           => $paymentDate ? $paymentDate : null,
            
            'student_signature_path' => $studentSigPath,
            'parent_signature_path'  => $parentSigPath,
            'training_period'        => $trainingPeriod,
            'examining_body'         => $examining,
            'mobile'                 => $mobile,
            'email'                  => $email,
            'photo_path'             => $photoPath,
            'course_id'              => $courseId,
            'session_year'           => $session,
            'admission_date'         => $admDate ? $admDate : null,
            'roll_number'            => $rollNumber,
            'status'                 => $status,
            'approval_status'        => $approvalStatus
        ], ['id' => $id]);

        redirectWithMessage("view-student.php?id=$id", "✅ Student details updated successfully.", "success");
    }
}

// No more sub_items array
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Edit Student – Admin Panel – <?= APP_SHORT_NAME ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link href="../assets/css/admin-style.css" rel="stylesheet">
<style>
:root{--primary:#3b0b7c;--secondary:#6c4ab6;}
.sect-title {
    font-weight: 700;
    color: var(--primary);
    border-left: 4px solid var(--secondary);
    padding-left: 12px;
    margin: 30px 0 15px;
    font-size: 1.05rem;
    display: flex;
    align-items: center;
    gap: 8px;
}
.image-preview-container {
    width: 130px;
    height: 165px;
    object-fit: cover;
    border-radius: 12px;
    border: 3px solid #e0d8f0;
    margin-bottom: 10px;
}
.sig-preview-container {
    max-height: 90px;
    max-width: 220px;
    border-radius: 6px;
    border: 1px solid #ddd;
    margin-bottom: 10px;
}
</style>
</head>
<body>
<?php include __DIR__ . '/../includes/admin_header.php'; ?>
<div class="container-fluid">
<div class="row">
<?php include __DIR__ . '/../includes/admin_sidebar.php'; ?>
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
    <div>
        <a href="view-student.php?id=<?= $id ?>" class="btn btn-outline-secondary btn-sm mb-2 shadow-sm">
            <i class="fas fa-arrow-left me-1"></i>Cancel & Back to Profile
        </a>
        <h2 class="h3 fw-bold mb-0 text-dark"><i class="fas fa-edit text-primary me-2"></i>Edit Student Profile</h2>
    </div>
</div>

<?php if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show shadow-sm rounded-3">
    <?= htmlspecialchars($flash['message']) ?><button class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm rounded-4 p-4 mb-5">
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
        
        <!-- ADMIN STATUS OVERRIDES -->
        <div class="sect-title mt-0"><i class="fas fa-shield-halved"></i>Administrative Status Overrides</div>
        <div class="row g-3">
            <div class="col-md-4">
                <label class="fw-bold small form-label">Roll Number</label>
                <input type="text" name="roll_number" class="form-control" value="<?= htmlspecialchars($student['roll_number'] ?? '') ?>" placeholder="Leave blank if not generated yet">
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Approval Status *</label>
                <select name="approval_status" class="form-select" required>
                    <option value="pending" <?= ($student['approval_status'] === 'pending') ? 'selected' : '' ?>>Pending</option>
                    <option value="approved" <?= ($student['approval_status'] === 'approved') ? 'selected' : '' ?>>Approved</option>
                    <option value="rejected" <?= ($student['approval_status'] === 'rejected') ? 'selected' : '' ?>>Rejected</option>
                </select>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">System Access Status *</label>
                <select name="status" class="form-select" required>
                    <option value="pending" <?= ($student['status'] === 'pending') ? 'selected' : '' ?>>Pending</option>
                    <option value="active" <?= ($student['status'] === 'active') ? 'selected' : '' ?>>Active</option>
                    <option value="inactive" <?= ($student['status'] === 'inactive') ? 'selected' : '' ?>>Inactive</option>
                </select>
            </div>
        </div>

        <!-- COURSE DETAILS -->
        <div class="sect-title"><i class="fas fa-book"></i>Course & Session Details</div>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="fw-bold small form-label">Main Course *</label>
                <select name="course_id" id="courseSelect" class="form-select" required>
                    <option value="">-- Select Course --</option>
                    <?php 
                    $curCat = '';
                    foreach ($courses as $c): 
                        if ($curCat !== $c['cat_name']) {
                            if ($curCat !== '') echo '</optgroup>';
                            $curCat = $c['cat_name'];
                            echo '<optgroup label="' . htmlspecialchars($curCat) . '">';
                        }
                    ?>
                        <option value="<?= $c['id'] ?>" <?= ($student['course_id'] == $c['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['course_name']) ?> (<?= htmlspecialchars($c['course_code']) ?>)
                        </option>
                    <?php endforeach; 
                    if ($curCat !== '') echo '</optgroup>';
                    ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Session *</label>
                <input type="text" name="session_year" class="form-control" value="<?= htmlspecialchars($student['session_year'] ?? '') ?>" placeholder="e.g. 2026-27" required>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Admission Date *</label>
                <input type="date" name="admission_date" class="form-control" value="<?= htmlspecialchars($student['admission_date'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Training Period</label>
                <input type="text" name="training_period" class="form-control" value="<?= htmlspecialchars($student['training_period'] ?? '') ?>" placeholder="e.g. 1 Year">
            </div>
            <div class="col-md-12">
                <label class="fw-bold small form-label">Examining Body</label>
                <input type="text" name="examining_body" class="form-control" value="<?= htmlspecialchars($student['examining_body'] ?? 'INDIAN BOARD OF VOCATIONAL AND TECHNICAL EDUCATION (New Delhi)') ?>">
            </div>
        </div>

        <!-- PERSONAL DETAILS -->
        <div class="sect-title"><i class="fas fa-user-circle"></i>SECTION 1: PERSONAL DETAILS</div>
        <div class="row g-3">
            <div class="col-md-4">
                <label class="fw-bold small form-label">Student Name *</label>
                <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($student['full_name'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Father's Name *</label>
                <input type="text" name="father_name" class="form-control" value="<?= htmlspecialchars($student['father_name'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Mother's Name *</label>
                <input type="text" name="mother_name" class="form-control" value="<?= htmlspecialchars($student['mother_name'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Guardian's Name</label>
                <input type="text" name="guardian_name" class="form-control" value="<?= htmlspecialchars($student['guardian_name'] ?? '') ?>">
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Date of Birth *</label>
                <input type="date" name="date_of_birth" class="form-control" value="<?= htmlspecialchars($student['date_of_birth'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Gender *</label>
                <select name="gender" class="form-select" required>
                    <option value="male" <?= ($student['gender'] === 'male') ? 'selected' : '' ?>>Male</option>
                    <option value="female" <?= ($student['gender'] === 'female') ? 'selected' : '' ?>>Female</option>
                    <option value="other" <?= ($student['gender'] === 'other') ? 'selected' : '' ?>>Other</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="fw-bold small form-label">Blood Group</label>
                <input type="text" name="blood_group" class="form-control" value="<?= htmlspecialchars($student['blood_group'] ?? '') ?>" placeholder="e.g. O+">
            </div>
            <div class="col-md-3">
                <label class="fw-bold small form-label">Aadhaar No. *</label>
                <input type="text" name="aadhaar_no" class="form-control" value="<?= htmlspecialchars($student['aadhaar_no'] ?? '') ?>" required>
            </div>
            <div class="col-md-3">
                <label class="fw-bold small form-label">Mobile No. *</label>
                <input type="text" name="mobile" class="form-control" value="<?= htmlspecialchars($student['mobile'] ?? '') ?>" required>
            </div>
            <div class="col-md-3">
                <label class="fw-bold small form-label">Email ID</label>
                <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($student['email'] ?? '') ?>">
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Religion *</label>
                <input type="text" name="religion" class="form-control" value="<?= htmlspecialchars($student['religion'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Category *</label>
                <select name="category" class="form-select" required>
                    <option value="GEN" <?= (strtoupper($student['category']) === 'GENERAL' || strtoupper($student['category']) === 'GEN') ? 'selected' : '' ?>>GEN</option>
                    <option value="OBC" <?= (strtoupper($student['category']) === 'OBC') ? 'selected' : '' ?>>OBC</option>
                    <option value="SC" <?= (strtoupper($student['category']) === 'SC') ? 'selected' : '' ?>>SC</option>
                    <option value="ST" <?= (strtoupper($student['category']) === 'ST') ? 'selected' : '' ?>>ST</option>
                    <option value="EWS" <?= (strtoupper($student['category']) === 'EWS') ? 'selected' : '' ?>>EWS</option>
                    <option value="other" <?= (strtoupper($student['category']) === 'OTHER') ? 'selected' : '' ?>>Other</option>
                </select>
            </div>
            <div class="col-md-4">
                <label class="fw-bold small form-label">Domicile State *</label>
                <input type="text" name="domicile_state" class="form-control" value="<?= htmlspecialchars($student['domicile_state'] ?? '') ?>" required>
            </div>
        </div>

        <!-- ADDRESS DETAILS -->
        <div class="sect-title"><i class="fas fa-map-marked-alt"></i>SECTION 2: ADDRESS DETAILS</div>
        <div class="row g-4">
            <div class="col-md-6">
                <div class="p-3 rounded-3 border bg-light h-100">
                    <div class="fw-bold text-primary mb-3 small text-uppercase"><i class="fas fa-home me-1"></i>Permanent Address</div>
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="fw-bold small form-label">House/Street Address *</label>
                            <textarea name="permanent_address" id="perm_address" class="form-control" rows="2" required><?= htmlspecialchars($student['permanent_address'] ?? $student['address'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-4">
                            <label class="fw-bold small form-label">District *</label>
                            <input type="text" name="permanent_district" id="perm_district" class="form-control" value="<?= htmlspecialchars($student['permanent_district'] ?? $student['city'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="fw-bold small form-label">State *</label>
                            <input type="text" name="permanent_state" id="perm_state" class="form-control" value="<?= htmlspecialchars($student['permanent_state'] ?? $student['state'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="fw-bold small form-label">Pincode *</label>
                            <input type="text" name="permanent_pincode" id="perm_pincode" class="form-control" value="<?= htmlspecialchars($student['permanent_pincode'] ?? $student['pincode'] ?? '') ?>" required>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="p-3 rounded-3 border bg-light h-100">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div class="fw-bold text-primary small text-uppercase"><i class="fas fa-envelope me-1"></i>Correspondence Address</div>
                        <div class="form-check form-switch small">
                            <input class="form-check-input" type="checkbox" id="corrSameCheck" onchange="copyAddress()">
                            <label class="form-check-label fw-bold text-secondary" for="corrSameCheck">Same as Permanent</label>
                        </div>
                    </div>
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="fw-bold small form-label">House/Street Address *</label>
                            <textarea name="correspondence_address" id="corr_address" class="form-control" rows="2" required><?= htmlspecialchars($student['correspondence_address'] ?? $student['address'] ?? '') ?></textarea>
                        </div>
                        <div class="col-md-4">
                            <label class="fw-bold small form-label">District *</label>
                            <input type="text" name="correspondence_district" id="corr_district" class="form-control" value="<?= htmlspecialchars($student['correspondence_district'] ?? $student['city'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="fw-bold small form-label">State *</label>
                            <input type="text" name="correspondence_state" id="corr_state" class="form-control" value="<?= htmlspecialchars($student['correspondence_state'] ?? $student['state'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-4">
                            <label class="fw-bold small form-label">Pincode *</label>
                            <input type="text" name="correspondence_pincode" id="corr_pincode" class="form-control" value="<?= htmlspecialchars($student['correspondence_pincode'] ?? $student['pincode'] ?? '') ?>" required>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- EDUCATIONAL QUALIFICATIONS -->
        <div class="sect-title"><i class="fas fa-graduation-cap"></i>SECTION 3: EDUCATIONAL QUALIFICATION</div>
        <div class="table-responsive rounded-3 border">
            <table class="table table-bordered table-striped align-middle mb-0 text-center small" id="qualificationsTable">
                <thead class="table-dark">
                    <tr>
                        <th style="width: 50px;">S.No</th>
                        <th>Exam Passed *</th>
                        <th>Board / University *</th>
                        <th>Year of Passing *</th>
                        <th>Roll No. *</th>
                        <th>Percentage / Division *</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $rowsToShow = max(3, count($qualifications));
                    for ($i = 0; $i < $rowsToShow; $i++):
                        $q = $qualifications[$i] ?? [];
                    ?>
                    <tr>
                        <td><?= $i + 1 ?></td>
                        <td><input type="text" name="exam_passed[]" class="form-control form-control-sm" value="<?= htmlspecialchars($q['exam_passed'] ?? '') ?>" placeholder="e.g. 10th / Secondary"></td>
                        <td><input type="text" name="board_university[]" class="form-control form-control-sm" value="<?= htmlspecialchars($q['board_university'] ?? '') ?>" placeholder="Board name"></td>
                        <td><input type="text" name="year_of_passing[]" class="form-control form-control-sm" value="<?= htmlspecialchars($q['year_of_passing'] ?? '') ?>" placeholder="YYYY"></td>
                        <td><input type="text" name="roll_no[]" class="form-control form-control-sm" value="<?= htmlspecialchars($q['roll_no'] ?? '') ?>" placeholder="Roll no"></td>
                        <td><input type="text" name="percentage_division[]" class="form-control form-control-sm" value="<?= htmlspecialchars($q['percentage_division'] ?? '') ?>" placeholder="e.g. 78% / First"></td>
                    </tr>
                    <?php endfor; ?>
                </tbody>
            </table>
        </div>

        <!-- DOCUMENTS ATTACHED -->
        <div class="sect-title"><i class="fas fa-paperclip"></i>SECTION 4: DOCUMENTS ATTACHED & UPLOADS</div>
        <div class="p-3 bg-light rounded-3 border">
            <div class="row g-3">
                <?php
                $availDocs = [
                    'Passport Size Photos'      => 'photos',
                    'Aadhaar Card Copy'         => 'aadhaar',
                    'Marksheets Copy'           => 'marksheets',
                    'Transfer Certificate (TC)' => 'tc',
                    'Migration Certificate'     => 'migration',
                    'Category Certificate'      => 'category',
                    'Address Proof'             => 'addr_proof',
                    'Domicile Certificate'      => 'domicile'
                ];
                
                foreach ($availDocs as $docName => $slug):
                    $hasDoc = isset($docsAttached[$docName]);
                    $docPath = $docsAttached[$docName] ?? '';
                ?>
                <div class="col-md-6 col-lg-4">
                    <div class="p-2 border bg-white rounded-3 shadow-sm h-100 d-flex flex-column justify-content-between">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="documents_attached[]" value="<?= $docName ?>" id="doc_check_<?= $slug ?>" <?= $hasDoc ? 'checked' : '' ?>>
                            <label class="form-check-label fw-semibold small" for="doc_check_<?= $slug ?>">
                                <?= $docName ?>
                            </label>
                        </div>
                        <div class="mt-2">
                            <input type="file" name="doc_file_<?= $slug ?>" class="form-control form-control-sm" accept="image/*,application/pdf">
                            <?php if ($hasDoc && !empty($docPath)): ?>
                                <div class="mt-1 d-flex align-items-center gap-2">
                                    <span class="badge bg-success small"><i class="fas fa-check-circle me-1"></i>Saved</span>
                                    <a href="../<?= htmlspecialchars($docPath) ?>" target="_blank" class="btn btn-xs btn-outline-primary py-0 px-2" style="font-size: 0.75rem;">
                                        <i class="fas fa-eye me-1"></i>View
                                    </a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <div class="col-12 mt-3">
                    <label class="fw-bold small form-label">Other Attached Documents (Optional)</label>
                    <input type="text" name="documents_attached_other" class="form-control" value="<?= htmlspecialchars($student['documents_attached_other'] ?? '') ?>" placeholder="List other documents separated by comma">
                </div>
            </div>
        </div>

        <!-- FEE DETAILS -->
        <div class="sect-title"><i class="fas fa-rupee-sign"></i>SECTION 5: FEE DETAILS (Student Payment Details)</div>
        <div class="row g-3">
            <div class="col-md-3">
                <label class="fw-bold small form-label">Admission Fee Charged (₹)</label>
                <input type="number" name="admission_fee" id="adm_fee" class="form-control" step="0.01" value="<?= htmlspecialchars($student['admission_fee'] ?? 0) ?>" oninput="calcTotalFee()">
            </div>
            <div class="col-md-3">
                <label class="fw-bold small form-label">Registration Fee Charged (₹)</label>
                <input type="number" name="registration_fee" id="reg_fee" class="form-control" step="0.01" value="<?= htmlspecialchars($student['registration_fee'] ?? 0) ?>" oninput="calcTotalFee()">
            </div>
            <div class="col-md-3">
                <label class="fw-bold small form-label">Total Student Fee</label>
                <div class="form-control bg-light fw-bold text-primary" id="total_fee_display">₹<?= number_format(($student['admission_fee'] ?? 0) + ($student['registration_fee'] ?? 0), 2) ?></div>
            </div>
            <div class="col-md-3">
                <label class="fw-bold small form-label">Payment Mode</label>
                <input type="text" name="payment_mode" class="form-control" value="<?= htmlspecialchars($student['payment_mode'] ?? '') ?>" placeholder="e.g. Cash, Online, Bank Transfer">
            </div>
            <div class="col-md-6">
                <label class="fw-bold small form-label">Receipt / Transaction ID</label>
                <input type="text" name="payment_receipt_no" class="form-control" value="<?= htmlspecialchars($student['payment_receipt_no'] ?? '') ?>" placeholder="e.g. Txn1826038290">
            </div>
            <div class="col-md-6">
                <label class="fw-bold small form-label">Payment Date</label>
                <input type="date" name="payment_date" class="form-control" value="<?= htmlspecialchars($student['payment_date'] ?? '') ?>">
            </div>
        </div>

        <!-- IMAGE AND SIGNATURE UPLOADS -->
        <div class="sect-title"><i class="fas fa-image"></i>SECTION 6: MEDIA FILES & UPLOADS</div>
        <div class="row g-4 text-center">
            <div class="col-md-4 border-end">
                <div class="fw-bold text-secondary small mb-2 text-uppercase">Student Photo</div>
                <div class="d-flex flex-column align-items-center">
                    <?php if (!empty($student['photo_path']) && file_exists('../' . $student['photo_path'])): ?>
                        <img src="../<?= htmlspecialchars($student['photo_path']) ?>" class="image-preview-container shadow-sm bg-white" id="photo_preview" alt="Student Photo">
                    <?php else: ?>
                        <div class="image-preview-container d-flex align-items-center justify-content-center bg-light shadow-sm" id="photo_preview">
                            <i class="fas fa-user fa-3x text-secondary opacity-50"></i>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="photo" class="form-control form-control-sm w-75" accept="image/*" onchange="previewImage(this, 'photo_preview')">
                </div>
            </div>
            <div class="col-md-4 border-end">
                <div class="fw-bold text-secondary small mb-2 text-uppercase">Student Signature</div>
                <div class="d-flex flex-column align-items-center">
                    <?php if (!empty($student['student_signature_path']) && file_exists('../' . $student['student_signature_path'])): ?>
                        <img src="../<?= htmlspecialchars($student['student_signature_path']) ?>" class="sig-preview-container shadow-sm bg-white" id="stud_sig_preview" alt="Student Signature">
                    <?php else: ?>
                        <div class="sig-preview-container d-flex align-items-center justify-content-center bg-light shadow-sm" style="height:90px; width:220px;" id="stud_sig_preview">
                            <span class="small text-muted">No Signature</span>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="student_signature" class="form-control form-control-sm w-75 mt-2" accept="image/*" onchange="previewImage(this, 'stud_sig_preview')">
                </div>
            </div>
            <div class="col-md-4">
                <div class="fw-bold text-secondary small mb-2 text-uppercase">Parent / Guardian Signature</div>
                <div class="d-flex flex-column align-items-center">
                    <?php if (!empty($student['parent_signature_path']) && file_exists('../' . $student['parent_signature_path'])): ?>
                        <img src="../<?= htmlspecialchars($student['parent_signature_path']) ?>" class="sig-preview-container shadow-sm bg-white" id="parent_sig_preview" alt="Parent Signature">
                    <?php else: ?>
                        <div class="sig-preview-container d-flex align-items-center justify-content-center bg-light shadow-sm" style="height:90px; width:220px;" id="parent_sig_preview">
                            <span class="small text-muted">No Signature</span>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="parent_signature" class="form-control form-control-sm w-75 mt-2" accept="image/*" onchange="previewImage(this, 'parent_sig_preview')">
                </div>
            </div>
        </div>

        <div class="d-flex gap-2 justify-content-end mt-5 border-top pt-3">
            <a href="view-student.php?id=<?= $id ?>" class="btn btn-outline-secondary px-4 py-2">
                <i class="fas fa-times-circle me-1"></i>Cancel
            </a>
            <button type="submit" class="btn btn-primary px-5 py-2 fw-bold">
                <i class="fas fa-save me-1"></i>Save Student Details
            </button>
        </div>
    </form>
</div>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function copyAddress() {
    const isSame = document.getElementById('corrSameCheck').checked;
    const fields = ['address', 'district', 'state', 'pincode'];
    fields.forEach(f => {
        const permEl = document.getElementById('perm_' + f);
        const corrEl = document.getElementById('corr_' + f);
        if (permEl && corrEl) {
            if (isSame) {
                corrEl.value = permEl.value;
                corrEl.readOnly = true;
                corrEl.classList.add('bg-light');
            } else {
                corrEl.readOnly = false;
                corrEl.classList.remove('bg-light');
            }
        }
    });
}

function calcTotalFee() {
    const adm = parseFloat(document.getElementById('adm_fee').value) || 0;
    const reg = parseFloat(document.getElementById('reg_fee').value) || 0;
    const total = adm + reg;
    document.getElementById('total_fee_display').textContent = '₹' + total.toFixed(2);
}

function previewImage(inp, previewId) {
    if (!inp.files || !inp.files[0]) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        const preview = document.getElementById(previewId);
        if (preview.tagName === 'IMG') {
            preview.src = e.target.result;
        } else {
            preview.innerHTML = `<img src="${e.target.result}" class="w-100 h-100" style="object-fit:cover; border-radius:inherit;">`;
        }
    };
    reader.readAsDataURL(inp.files[0]);
}
</script>
</body>
</html>
