<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

$collegePage = 'students';
Auth()->requireRole(['college']);
$db   = DB();
$user = Auth()->getUser();
$flash = getFlashMessage();

// Auto Reg No: CollegeCode digits + CourseCode digits + sequence = 10 numeric digits
function genRegNo($db, $collegeCode, $courseCode) {
    // Extract only digits from codes
    $cDig  = preg_replace('/\D/', '', $collegeCode); // e.g. MGS-AHM-004 -> 004
    $crDig = preg_replace('/\D/', '', $courseCode);  // e.g. AUTO001 -> 001
    $year  = date('y'); // 2-digit year
    $seq   = $db->fetchColumn("SELECT COUNT(*)+1 FROM students WHERE YEAR(created_at)=YEAR(NOW())");
    $seq   = str_pad($seq, 3, '0', STR_PAD_LEFT);
    // Build 10-digit: year(2) + cDig last2 + crDig last2 + seq(3) + check(1)
    $raw = $year . str_pad($cDig, 2, '0', STR_PAD_LEFT) . str_pad($crDig, 2, '0', STR_PAD_LEFT) . $seq;
    $raw = substr($raw, 0, 9);
    $check = array_sum(str_split($raw)) % 10;
    return $raw . $check; // 10 digits
}

// POST handler
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_student') {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        redirectWithMessage('students.php', 'Security session expired. Please try again.', 'danger');
    }
    
    $courseId   = intval($_POST['course_id']   ?? 0);
    $subItemId  = intval($_POST['sub_item_id'] ?? 0);
    $fullName   = cleanInput($_POST['full_name']    ?? '');
    $fatherName = cleanInput($_POST['father_name']  ?? '');
    $motherName = cleanInput($_POST['mother_name']  ?? '');
    $dob        = parseDOB($_POST['dob'] ?? '');
    $mobile     = cleanInput($_POST['mobile']       ?? '');
    $email      = cleanInput($_POST['email']        ?? '');
    $admDate    = $_POST['admission_date']           ?? date('Y-m-d');
    $session    = cleanInput($_POST['session']       ?? date('Y').'-'.(date('Y')+1));
    $examining  = 'INDIAN BOARD OF VOCATIONAL AND TECHNICAL EDUCATION (New Delhi)';

    // New Personal Details
    $guardianName  = cleanInput($_POST['guardian_name']  ?? '');
    $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']  ?? '');

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

    $corrSame     = isset($_POST['corr_same']) && $_POST['corr_same'] == '1';
    if ($corrSame) {
        $corrAddress  = $permAddress;
        $corrDistrict = $permDistrict;
        $corrState    = $permState;
        $corrPincode  = $permPincode;
    } else {
        $corrAddress  = cleanInput($_POST['correspondence_address']  ?? '');
        $corrDistrict = cleanInput($_POST['correspondence_district'] ?? '');
        $corrState    = cleanInput($_POST['correspondence_state']    ?? '');
        $corrPincode  = cleanInput($_POST['correspondence_pincode']  ?? '');
    }

    // Qualifications JSON
    $qualifications = [];
    if (isset($_POST['qual_exam']) && is_array($_POST['qual_exam'])) {
        for ($i = 0; $i < count($_POST['qual_exam']); $i++) {
            $exam = cleanInput($_POST['qual_exam'][$i] ?? '');
            $board = cleanInput($_POST['qual_board'][$i] ?? '');
            $year = cleanInput($_POST['qual_year'][$i] ?? '');
            $roll = cleanInput($_POST['qual_roll'][$i] ?? '');
            $pct = cleanInput($_POST['qual_percentage'][$i] ?? '');
            
            if (!empty($board) || !empty($year) || !empty($roll) || !empty($pct)) {
                $qualifications[] = [
                    'exam_passed' => $exam,
                    'board_university' => $board,
                    'year_of_passing' => $year,
                    'roll_no' => $roll,
                    'percentage_division' => $pct
                ];
            }
        }
    }
    $qualificationsJson = json_encode($qualifications);

    // Documents checkboxes (will process files and generate JSON after $regNo is generated)
    $docsAttachedRaw = [];
    if (isset($_POST['docs']) && is_array($_POST['docs'])) {
        foreach ($_POST['docs'] as $doc) {
            $docsAttachedRaw[] = cleanInput($doc);
        }
    }
    $docsAttachedOther = cleanInput($_POST['docs_other'] ?? '');

    // Fee Details
    $admissionFee    = floatval($_POST['admission_fee']    ?? 0);
    $registrationFee = floatval($_POST['registration_fee'] ?? 0);
    $paymentMode     = cleanInput($_POST['payment_mode']     ?? '');
    $paymentReceipt  = cleanInput($_POST['payment_receipt_no'] ?? '');
    $paymentDate     = !empty($_POST['payment_date']) ? $_POST['payment_date'] : null;

    // Declaration Details
    $declarationAccepted = isset($_POST['declaration_accepted']) ? 1 : 0;
    $declDate            = !empty($_POST['declaration_date']) ? $_POST['declaration_date'] : null;
    $declPlace           = cleanInput($_POST['declaration_place'] ?? '');

    // Get fee from course_fees for wallet check
    $feeRow = $db->fetchOne("SELECT * FROM course_fees WHERE course_id=? AND user_type='college'", [$courseId]);
    $totalFee = floatval($feeRow['total_fee'] ?? 0);
    $courseInfo = $db->fetchOne("SELECT duration_text FROM courses WHERE id=?", [$courseId]);
    $trainingPeriod = $courseInfo['duration_text'] ?? '';

    // Wallet check
    $wallet = $db->fetchOne("SELECT balance FROM wallets WHERE user_id=?", [$user['id']]);
    if (($wallet['balance'] ?? 0) < $totalFee) {
        redirectWithMessage('students.php?action=add', "Insufficient wallet balance (Need: ₹$totalFee).", 'danger');
    }

    // Get course code
    $course = $db->fetchOne("SELECT course_code FROM courses WHERE id=?", [$courseId]);
    $regNo  = genRegNo($db, $user['institution_code'] ?? '001', $course['course_code'] ?? '001');

    // Make sure directories exist
    $photoDir = __DIR__ . '/../uploads/students/photos/';
    if (!is_dir($photoDir)) {
        @mkdir($photoDir, 0755, true);
    }
    $sigDir = __DIR__ . '/../uploads/students/signatures/';
    if (!is_dir($sigDir)) {
        @mkdir($sigDir, 0755, true);
    }
    
    // Create documents directory
    $docUploadDir = __DIR__ . '/../uploads/students/documents/';
    if (!is_dir($docUploadDir)) {
        @mkdir($docUploadDir, 0755, true);
    }

    $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'
    ];

    $docsAttached = [];
    foreach ($docsAttachedRaw as $doc) {
        $fileSlug = $docMapping[$doc] ?? '';
        $filePath = '';
        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 . '_' . $regNo . '_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['doc_file_' . $fileSlug]['tmp_name'], $docUploadDir . $fn)) {
                    $filePath = 'uploads/students/documents/' . $fn;
                }
            }
        }
        $docsAttached[$doc] = $filePath;
    }
    $docsAttachedJson = json_encode($docsAttached);

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

    // Student Signature upload
    $studentSigPath = '';
    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_' . $regNo . '_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['student_signature']['tmp_name'], $sigDir . $fn)) {
                $studentSigPath = 'uploads/students/signatures/' . $fn;
            }
        }
    }

    // Parent Signature upload
    $parentSigPath = '';
    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_' . $regNo . '_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['parent_signature']['tmp_name'], $sigDir . $fn)) {
                $parentSigPath = 'uploads/students/signatures/' . $fn;
            }
        }
    }

    $sid = $db->insert('students', [
        'registration_number' => $regNo,
        '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,
        
        // Legacy Address fields (mapping for compatibility)
        'address'             => $permAddress,
        'city'                => $permDistrict,
        'state'               => $permState,
        'pincode'             => $permPincode,
        
        // Detailed Address fields
        '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 and documents
        'qualifications_json'    => $qualificationsJson,
        'documents_attached'     => $docsAttachedJson,
        'documents_attached_other'=> $docsAttachedOther,
        
        // Fee Details
        'admission_fee'          => $admissionFee,
        'registration_fee'       => $registrationFee,
        'payment_mode'           => $paymentMode,
        'payment_receipt_no'     => $paymentReceipt,
        'payment_date'           => $paymentDate,
        
        // Declaration details
        'declaration_accepted'   => $declarationAccepted,
        'student_signature_path' => $studentSigPath,
        'parent_signature_path'  => $parentSigPath,
        'declaration_date'       => $declDate,
        'declaration_place'      => $declPlace,

        'training_center'     => $user['institution_name'],
        'training_period'     => $trainingPeriod,
        'examining_body'      => $examining,
        'mobile'              => $mobile,
        'email'               => $email,
        'photo_path'          => $photoPath,
        'institution_id'      => $user['id'],
        'institution_type'    => 'college',
        'course_id'           => $courseId,
        'sub_item_id'         => $subItemId ?: null,
        'session_year'        => $session,
        'admission_date'      => $admDate,
        'total_fee'           => $totalFee,
        'status'              => 'pending',
        'approval_status'     => 'pending',
        'created_by'          => $user['id'],
        'created_at'          => date('Y-m-d H:i:s'),
    ]);

    if ($sid) {
        $db->query("UPDATE wallets SET balance=balance-?,total_debited=total_debited+? WHERE user_id=?",
            [$totalFee, $totalFee, $user['id']]);
        try { $db->insert('college_activity_logs',['college_id'=>$user['id'],'action'=>'STUDENT_ADDED','description'=>"Admission: $fullName (Reg: $regNo). Fee: ₹$totalFee",'entity_type'=>'student','entity_id'=>$sid,'ip_address'=>$_SERVER['REMOTE_ADDR']??'']); } catch(Exception $e){ error_log("Activity Log Error: " . $e->getMessage()); }
        redirectWithMessage('students.php', "✅ Admission submitted! Reg No: <strong>$regNo</strong>. Fee ₹".number_format($totalFee,2)." deducted.", 'success');
    } else {
        $errorMsg = "Database Error: " . $db->lastError;
        redirectWithMessage('students.php', "❌ Failed to submit admission. " . $errorMsg, 'danger');
    }
}

// Data
$categories = $db->fetchAll("SELECT * FROM course_categories WHERE is_active=1 ORDER BY display_order, name");
$sub_categories = $db->fetchAll("SELECT * FROM course_sub_categories WHERE is_active=1 ORDER BY display_order, name");
$courses = $db->fetchAll("SELECT c.*, cf.total_fee FROM courses c LEFT JOIN course_fees cf ON c.id=cf.course_id AND cf.user_type='college' WHERE c.is_active=1 ORDER BY c.display_order, c.course_name");
$search = cleanInput($_GET['search'] ?? '');
$page = intval($_GET['page'] ?? 1);
if ($page < 1) $page = 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

$where = "WHERE s.institution_id = ?";
$params = [$user['id']];

if (!empty($search)) {
    $where .= " AND (s.full_name LIKE ? OR s.registration_number LIKE ? OR s.mobile LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

// Count total for pagination
$totalStudents = $db->fetchColumn("SELECT COUNT(*) FROM students s $where", $params);
$totalPages = ceil($totalStudents / $perPage);

// Fetch paginated students
$sql = "SELECT s.*, c.course_name, c.course_code, c.duration_text as duration
        FROM students s 
        LEFT JOIN courses c ON s.course_id = c.id 
        $where 
        ORDER BY s.created_at DESC 
        LIMIT $perPage OFFSET $offset";
$students = $db->fetchAll($sql, $params);

$wallet   = $db->fetchOne("SELECT balance FROM wallets WHERE user_id=?", [$user['id']]);
$walletBal = floatval($wallet['balance'] ?? 0);
$showForm = ($_GET['action'] ?? '') === 'add';

// Build sub_items JSON for JS
$subJson = [];
foreach ($subItems as $si) { $subJson[$si['course_id']][] = $si; }
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Students – <?= 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">
<style>
:root{--primary:#3b0b7c;--secondary:#6c4ab6;}
.college-sidebar{width:250px;background:white;min-height:100vh;position:fixed;top:0;left:0;display:flex;flex-direction:column;box-shadow:3px 0 15px rgba(59,11,124,.08);z-index:1040;transition:transform .3s;}
.sidebar-brand{padding:28px 20px 20px;text-align:center;background:linear-gradient(135deg,var(--primary),var(--secondary));}
.sidebar-logo{width:68px;height:68px;border-radius:50%;border:3px solid rgba(255,255,255,.35);object-fit:cover;margin-bottom:12px;}
.sidebar-college-name{color:white;font-weight:700;font-size:.9rem;line-height:1.3;}
.sidebar-code{color:rgba(255,255,255,.65);font-size:.75rem;margin-top:4px;}
.sidebar-nav{flex:1;padding:16px 12px;overflow-y:auto;}
.sidebar-link{display:flex;align-items:center;gap:12px;padding:11px 16px;border-radius:10px;color:#555;text-decoration:none;font-size:.9rem;font-weight:500;margin-bottom:4px;transition:.2s;}
.sidebar-link:hover{background:#f0ebf8;color:var(--primary);transform:translateX(3px);}
.sidebar-link.active{background:linear-gradient(135deg,var(--primary),var(--secondary));color:white!important;box-shadow:0 4px 12px rgba(59,11,124,.25);}
.sidebar-icon{width:18px;text-align:center;flex-shrink:0;}
.sidebar-footer{padding:12px;border-top:1px solid #f0f0f0;}
.sidebar-logout{color:#dc3545!important;}
.college-main{margin-left:250px;padding:30px;min-height:100vh;background:#f8f9fa;}
@media(max-width:768px){.college-sidebar{transform:translateX(-100%)}.college-main{margin-left:0;padding:15px}}
.sec-title{font-weight:700;color:var(--primary);border-left:3px solid var(--secondary);padding-left:10px;margin:20px 0 12px;}
.fee-box{background:linear-gradient(135deg,var(--primary),var(--secondary));color:white;border-radius:12px;padding:16px;display:none;}
.photo-preview{width:120px;height:150px;object-fit:cover;border-radius:10px;border:2px dashed #c4b5da;display:flex;align-items:center;justify-content:center;background:#f8f4ff;cursor:pointer;}
.status-p{background:#fff7e6;color:#b45309;border:1px solid #fcd34d;border-radius:20px;padding:3px 10px;font-size:.75rem;font-weight:700;}
.status-a{background:#ecfdf5;color:#047857;border:1px solid #6ee7b7;border-radius:20px;padding:3px 10px;font-size:.75rem;font-weight:700;}
.status-r{background:#fef2f2;color:#b91c1c;border:1px solid #fca5a5;border-radius:20px;padding:3px 10px;font-size:.75rem;font-weight:700;}
</style>
</head><body>
<?php include __DIR__ . '/../includes/college_sidebar.php'; ?>
<button class="btn btn-sm d-md-none" id="mobileMenuBtn" onclick="toggleSidebar()"
  style="display:none;position:fixed;top:15px;left:15px;z-index:1050;background:var(--primary);color:white;border-radius:8px;padding:8px 12px;">
  <i class="fas fa-bars"></i></button>
<div class="overlay d-none" id="sidebarOverlay" onclick="toggleSidebar()"
  style="position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:1039;"></div>

<div class="college-main">

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

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
  <div><h3 class="fw-bold mb-1"><i class="fas fa-user-graduate me-2 text-primary"></i>Students</h3>
    <small class="text-muted">Wallet: <strong class="text-primary">₹<?=number_format($walletBal,2)?></strong></small></div>
  <?php if(!$showForm):?>
  <div class="d-flex gap-2">
    <a href="https://ibvte.com/admission-form.pdf" target="_blank" class="btn btn-outline-primary px-4 fw-bold"><i class="fas fa-download me-2"></i>Download Admission Form</a>
    <a href="?action=add" class="btn btn-primary px-4 fw-bold"><i class="fas fa-plus me-2"></i>New Admission</a>
  </div>
  <?php else:?>
  <a href="students.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-2"></i>Back</a>
  <?php endif;?>
</div>

<?php if($showForm): ?>
<!-- ══ ADMISSION FORM ══ -->
<div class="card border-0 shadow-sm rounded-4">
  <div class="card-header text-white py-3" style="background:linear-gradient(135deg,var(--primary),var(--secondary));border-radius:15px 15px 0 0;">
    <h5 class="mb-0 fw-bold"><i class="fas fa-user-plus me-2"></i>New Student Admission</h5>
    <small class="opacity-75">Fee deducted from wallet on submit. Pending admin approval.</small>
  </div>
  <div class="card-body p-4">

  <!-- Fee preview -->
  <div class="fee-box mb-3" id="feeBox">
    <div class="d-flex justify-content-between">
      <div><div class="small opacity-75">Course Fee</div><div class="h4 fw-bold mb-0" id="feeAmt">₹0</div><div class="small opacity-75" id="feeName"></div></div>
      <div class="text-end"><div class="small opacity-75">Your Balance</div><div class="h5 fw-bold">₹<?=number_format($walletBal,2)?></div></div>
    </div>
  </div>
  <div class="alert alert-danger d-none" id="feeWarn">
    <i class="fas fa-exclamation-triangle me-2"></i><strong>Insufficient balance!</strong>
    <a href="fund-requests.php" class="alert-link ms-2">Request Funds →</a>
  </div>

  <form method="POST" enctype="multipart/form-data" id="admForm">
  <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
  <input type="hidden" name="action" value="add_student">
  <input type="hidden" name="sub_item_id" id="subItemId" value="">

  <!-- COURSE SECTION -->
  <div class="sec-title"><i class="fas fa-book me-2"></i>Registration Details / पंजीयन का विवरण <span class="float-end text-danger fw-bold small">* अनिवार्य फिल्डस (Mandatory fields)</span></div>
  <div class="table-responsive mb-4 shadow-sm border rounded-3">
    <table class="table table-bordered mb-0 align-middle">
      <tbody>
        <tr>
          <td class="bg-light fw-bold text-dark" style="width: 35%;">Session</td>
          <td><input type="text" name="session" class="form-control" value="<?=date('Y').'-'.(date('Y')+1)?>"></td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Course Category *</td>
          <td>
            <select class="form-select" id="categorySelect" required onchange="filterSubCats(this)">
              <option value="">-- Select Category --</option>
              <?php foreach($categories as $cat):?>
              <option value="<?=htmlspecialchars($cat['id'])?>"><?=htmlspecialchars($cat['name'])?></option>
              <?php endforeach;?>
            </select>
          </td>
        </tr>
        <tr id="subCatWrap" style="display:none;">
          <td class="bg-light fw-bold text-dark">Sub Category *</td>
          <td>
            <select class="form-select" id="subCatSelect" onchange="filterCourses(this)">
              <option value="">-- Select Sub Category --</option>
            </select>
          </td>
        </tr>
        <tr id="courseWrap" style="display:none;">
          <td class="bg-light fw-bold text-dark">Courses / पाठ्यक्रम *</td>
          <td>
            <select class="form-select" id="courseSelect" name="course_id" onchange="pickCourse(this)">
              <option value="">-- Select Course --</option>
            </select>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Medium Hindi/English</td>
          <td>
            <select name="medium" class="form-select">
              <option value="Hindi">Hindi</option>
              <option value="English">English</option>
            </select>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Admission Date *</td>
          <td><input type="date" name="admission_date" class="form-control" required value="<?=date('Y-m-d')?>"></td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- SECTION 1: PERSONAL DETAILS -->
  <div class="sec-title"><i class="fas fa-user-circle me-2"></i>SECTION 1: PERSONAL DETAILS</div>
  <div class="table-responsive mb-4 shadow-sm border rounded-3">
    <table class="table table-bordered mb-0 align-middle">
      <tbody>
        <tr>
          <td class="bg-light fw-bold text-dark" style="width: 35%;">Student full name / आवेदक का पूरा नाम *</td>
          <td>
            <input type="text" name="full_name" class="form-control text-uppercase" required placeholder="As per documents" style="letter-spacing: 0.03em;">
            <small class="text-danger d-block mt-1">( Full name as per the highest / latest qualification certificate or legal certificate )</small>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Father's Name / पिता का नाम *</td>
          <td>
            <input type="text" name="father_name" class="form-control text-uppercase" required placeholder="FATHER'S FULL NAME">
            <small class="text-danger d-block mt-1">( Full Name As Per Educational/Legal Certificate )</small>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Mother's Name / माता का नाम *</td>
          <td>
            <input type="text" name="mother_name" class="form-control text-uppercase" required placeholder="MOTHER'S FULL NAME">
            <small class="text-danger d-block mt-1">( Full Name As Per Educational/Legal Certificate )</small>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Guardian's Name (If Any)</td>
          <td>
            <input type="text" name="guardian_name" class="form-control text-uppercase" placeholder="GUARDIAN'S FULL NAME">
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Date of Birth / जन्म तिथि *</td>
          <td>
            <input type="text" name="dob" class="form-control" required placeholder="DD/MM/YYYY" pattern="[0-9]{2}/[0-9]{2}/[0-9]{4}" title="Enter date in DD/MM/YYYY format">
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Gender / लिंग *</td>
          <td>
            <div class="d-flex gap-4">
              <div class="form-check">
                <input class="form-check-input" type="radio" name="gender" value="Male" id="gender_m" required>
                <label class="form-check-label" for="gender_m">Male</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="gender" value="Female" id="gender_f">
                <label class="form-check-label" for="gender_f">Female</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="gender" value="Other" id="gender_o">
                <label class="form-check-label" for="gender_o">Other</label>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Blood Group</td>
          <td>
            <select name="blood_group" class="form-select">
              <option value="">-- Select --</option>
              <option value="A+">A+</option>
              <option value="A-">A-</option>
              <option value="B+">B+</option>
              <option value="B-">B-</option>
              <option value="O+">O+</option>
              <option value="O-">O-</option>
              <option value="AB+">AB+</option>
              <option value="AB-">AB-</option>
            </select>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Aadhaar No. *</td>
          <td>
            <input type="text" name="aadhaar_no" class="form-control" required pattern="[0-9]{12}" placeholder="12 Digit Aadhaar Number" title="12-digit Aadhaar number">
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Mobile No. *</td>
          <td>
            <input type="tel" name="mobile" class="form-control" required pattern="[6-9][0-9]{9}" placeholder="10 Digit Number" title="10-digit starting with 6-9">
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Email ID</td>
          <td>
            <input type="email" name="email" class="form-control" placeholder="example@email.com">
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Religion</td>
          <td>
            <select name="religion" class="form-select">
              <option value="">-- Select Religion --</option>
              <option value="Hinduism">Hinduism</option>
              <option value="Islam">Islam</option>
              <option value="Sikhism">Sikhism</option>
              <option value="Christianity">Christianity</option>
              <option value="Buddhism">Buddhism</option>
              <option value="Jainism">Jainism</option>
              <option value="Other">Other</option>
            </select>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Category *</td>
          <td>
            <div class="d-flex gap-4 flex-wrap">
              <div class="form-check">
                <input class="form-check-input" type="radio" name="category" value="GEN" id="cat_gen" required>
                <label class="form-check-label" for="cat_gen">GEN</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="category" value="OBC" id="cat_obc">
                <label class="form-check-label" for="cat_obc">OBC</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="category" value="SC" id="cat_sc">
                <label class="form-check-label" for="cat_sc">SC</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="category" value="ST" id="cat_st">
                <label class="form-check-label" for="cat_st">ST</label>
              </div>
              <div class="form-check">
                <input class="form-check-input" type="radio" name="category" value="EWS" id="cat_ews">
                <label class="form-check-label" for="cat_ews">EWS</label>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Domicile State *</td>
          <td>
            <input type="text" name="domicile_state" class="form-control" required placeholder="e.g. Uttar Pradesh">
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Student Photo *</td>
          <td>
            <div class="photo-preview shadow-sm" onclick="document.getElementById('photoInput').click()" id="photoBox" style="width: 120px; height: 145px; background: #faf8ff; border: 2px dashed #a881e6; border-radius: 12px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s;">
              <div class="text-center text-muted small"><i class="fas fa-camera fa-2x d-block mb-1 text-primary opacity-75"></i>Click to upload</div>
            </div>
            <input type="file" name="photo" id="photoInput" accept="image/jpeg,image/png" style="opacity:0; position:absolute; z-index:-1; width:0; height:0;" required onchange="previewPhoto(this)">
            <small class="text-muted d-block mt-2" style="font-size: 0.75rem;">JPG/PNG, max 2MB</small>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- SECTION 2: ADDRESS DETAILS -->
  <div class="sec-title"><i class="fas fa-map-marked-alt me-2"></i>SECTION 2: ADDRESS DETAILS</div>
  <div class="table-responsive mb-4 shadow-sm border rounded-3">
    <table class="table table-bordered mb-0 align-middle">
      <thead class="bg-light">
        <tr>
          <th colspan="2" class="text-primary"><i class="fas fa-home me-2"></i>Permanent Address</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="bg-light fw-bold text-dark" style="width: 35%;">Street Address *</td>
          <td><textarea name="permanent_address" id="perm_address" class="form-control" rows="2" required placeholder="House No, Street, Landmark..."></textarea></td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">District *</td>
          <td><input type="text" name="permanent_district" id="perm_district" class="form-control" required placeholder="District"></td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">State *</td>
          <td><input type="text" name="permanent_state" id="perm_state" class="form-control" required placeholder="State"></td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Pin Code *</td>
          <td><input type="text" name="permanent_pincode" id="perm_pincode" class="form-control" required pattern="[0-9]{6}" placeholder="PIN" title="6-digit pin code"></td>
        </tr>
      </tbody>
      <thead class="bg-light">
        <tr>
          <th colspan="2" class="text-primary">
            <div class="d-flex justify-content-between align-items-center">
              <span><i class="fas fa-envelope-open-text me-2"></i>Correspondence Address</span>
              <div class="form-check m-0 fw-normal">
                <input class="form-check-input" type="checkbox" name="corr_same" value="1" id="corrSameCheck" onchange="copyAddress()">
                <label class="form-check-label text-secondary small" for="corrSameCheck">Same as Permanent Address</label>
              </div>
            </div>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="bg-light fw-bold text-dark">Street Address *</td>
          <td><textarea name="correspondence_address" id="corr_address" class="form-control" rows="2" required placeholder="House No, Street, Landmark..."></textarea></td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">District *</td>
          <td><input type="text" name="correspondence_district" id="corr_district" class="form-control" required placeholder="District"></td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">State *</td>
          <td><input type="text" name="correspondence_state" id="corr_state" class="form-control" required placeholder="State"></td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark">Pin Code *</td>
          <td><input type="text" name="correspondence_pincode" id="corr_pincode" class="form-control" required pattern="[0-9]{6}" placeholder="PIN" title="6-digit pin code"></td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- SECTION 3: EDUCATIONAL QUALIFICATION -->
  <div class="sec-title"><i class="fas fa-graduation-cap me-2"></i>SECTION 3: EDUCATIONAL QUALIFICATION</div>
  <div class="table-responsive mb-4 rounded-3 border shadow-sm">
    <table class="table table-bordered table-striped align-middle mb-0" style="min-width: 800px;">
      <thead class="table-dark" style="background: var(--primary);">
        <tr>
          <th style="width: 70px;" class="text-center">S.No</th>
          <th style="width: 250px;">Exam Passed</th>
          <th>Board / University *</th>
          <th style="width: 140px;">Year of Passing</th>
          <th style="width: 160px;">Roll No.</th>
          <th style="width: 180px;">Percentage / Division</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="text-center fw-bold text-secondary">1</td>
          <td><input type="text" name="qual_exam[]" class="form-control-plaintext fw-bold ps-2" value="High School" readonly></td>
          <td><input type="text" name="qual_board[]" class="form-control form-control-sm" placeholder="e.g. CBSE / UP BOARD" required></td>
          <td><input type="text" name="qual_year[]" class="form-control form-control-sm text-center" placeholder="YYYY" required pattern="[0-9]{4}"></td>
          <td><input type="text" name="qual_roll[]" class="form-control form-control-sm" placeholder="Roll No" required></td>
          <td><input type="text" name="qual_percentage[]" class="form-control form-control-sm" placeholder="e.g. 78% / 1st" required></td>
        </tr>
        <tr>
          <td class="text-center fw-bold text-secondary">2</td>
          <td><input type="text" name="qual_exam[]" class="form-control-plaintext fw-bold ps-2" value="Intermediate" readonly></td>
          <td><input type="text" name="qual_board[]" class="form-control form-control-sm" placeholder="e.g. CBSE / STATE BOARD"></td>
          <td><input type="text" name="qual_year[]" class="form-control form-control-sm text-center" placeholder="YYYY" pattern="[0-9]{4}"></td>
          <td><input type="text" name="qual_roll[]" class="form-control form-control-sm" placeholder="Roll No"></td>
          <td><input type="text" name="qual_percentage[]" class="form-control form-control-sm" placeholder="e.g. 82% / 1st"></td>
        </tr>
        <tr>
          <td class="text-center fw-bold text-secondary">3</td>
          <td><input type="text" name="qual_exam[]" class="form-control-plaintext fw-bold ps-2" value="Graduation" readonly></td>
          <td><input type="text" name="qual_board[]" class="form-control form-control-sm" placeholder="e.g. CCS University"></td>
          <td><input type="text" name="qual_year[]" class="form-control form-control-sm text-center" placeholder="YYYY" pattern="[0-9]{4}"></td>
          <td><input type="text" name="qual_roll[]" class="form-control form-control-sm" placeholder="Roll No"></td>
          <td><input type="text" name="qual_percentage[]" class="form-control form-control-sm" placeholder="e.g. 64% / 1st"></td>
        </tr>
        <tr>
          <td class="text-center fw-bold text-secondary">4</td>
          <td><input type="text" name="qual_exam[]" class="form-control-plaintext fw-bold ps-2" value="Other" readonly></td>
          <td><input type="text" name="qual_board[]" class="form-control form-control-sm" placeholder="Board / University"></td>
          <td><input type="text" name="qual_year[]" class="form-control form-control-sm text-center" placeholder="YYYY" pattern="[0-9]{4}"></td>
          <td><input type="text" name="qual_roll[]" class="form-control form-control-sm" placeholder="Roll No"></td>
          <td><input type="text" name="qual_percentage[]" class="form-control form-control-sm" placeholder="e.g. Diploma"></td>
        </tr>
        <tr>
          <td class="text-center fw-bold text-secondary">5</td>
          <td><input type="text" name="qual_exam[]" class="form-control form-control-sm fw-bold border-bottom-primary" placeholder="Specify Other Exam" value="Other"></td>
          <td><input type="text" name="qual_board[]" class="form-control form-control-sm" placeholder="Board / University"></td>
          <td><input type="text" name="qual_year[]" class="form-control form-control-sm text-center" placeholder="YYYY" pattern="[0-9]{4}"></td>
          <td><input type="text" name="qual_roll[]" class="form-control form-control-sm" placeholder="Roll No"></td>
          <td><input type="text" name="qual_percentage[]" class="form-control form-control-sm" placeholder="Percentage / Div"></td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- SECTION 4: DOCUMENTS ATTACHED -->
  <div class="sec-title"><i class="fas fa-paperclip me-2"></i>SECTION 4: DOCUMENTS ATTACHED (Tick if Submitted)</div>
  <div class="table-responsive mb-4 shadow-sm border rounded-3">
    <table class="table table-bordered mb-0 align-middle">
      <tbody>
        <!-- Passport Size Photos -->
        <tr>
          <td class="bg-light fw-bold text-dark" style="width: 35%;">
            <div class="form-check m-0">
              <input class="form-check-input border-primary" type="checkbox" name="docs[]" value="Passport Size Photos" id="doc_photos" checked onchange="toggleDocUpload('photos')" style="cursor:pointer;">
              <label class="form-check-label ms-2" for="doc_photos" style="cursor:pointer;">Passport Size Photos</label>
            </div>
          </td>
          <td>
            <div id="upload_wrap_photos">
              <input type="file" name="doc_file_photos" class="form-control form-control-sm" accept="image/jpeg,image/png,application/pdf">
              <small class="text-muted" style="font-size:0.75rem;">Upload Document (JPG, PNG, or PDF – Max 2MB)</small>
            </div>
          </td>
        </tr>
        <!-- Aadhaar Card Copy -->
        <tr>
          <td class="bg-light fw-bold text-dark">
            <div class="form-check m-0">
              <input class="form-check-input border-primary" type="checkbox" name="docs[]" value="Aadhaar Card Copy" id="doc_aadhaar" onchange="toggleDocUpload('aadhaar')" style="cursor:pointer;">
              <label class="form-check-label ms-2" for="doc_aadhaar" style="cursor:pointer;">Aadhaar Card Copy</label>
            </div>
          </td>
          <td>
            <div id="upload_wrap_aadhaar" style="display:none;">
              <input type="file" name="doc_file_aadhaar" class="form-control form-control-sm" accept="image/jpeg,image/png,application/pdf" disabled>
              <small class="text-muted" style="font-size:0.75rem;">Upload Document (JPG, PNG, or PDF – Max 2MB)</small>
            </div>
          </td>
        </tr>
        <!-- Marksheets Copy -->
        <tr>
          <td class="bg-light fw-bold text-dark">
            <div class="form-check m-0">
              <input class="form-check-input border-primary" type="checkbox" name="docs[]" value="Marksheets Copy" id="doc_marksheets" onchange="toggleDocUpload('marksheets')" style="cursor:pointer;">
              <label class="form-check-label ms-2" for="doc_marksheets" style="cursor:pointer;">Marksheets Copy</label>
            </div>
          </td>
          <td>
            <div id="upload_wrap_marksheets" style="display:none;">
              <input type="file" name="doc_file_marksheets" class="form-control form-control-sm" accept="image/jpeg,image/png,application/pdf" disabled>
              <small class="text-muted" style="font-size:0.75rem;">Upload Document (JPG, PNG, or PDF – Max 2MB)</small>
            </div>
          </td>
        </tr>
        <!-- Transfer Certificate (TC) -->
        <tr>
          <td class="bg-light fw-bold text-dark">
            <div class="form-check m-0">
              <input class="form-check-input border-primary" type="checkbox" name="docs[]" value="Transfer Certificate (TC)" id="doc_tc" onchange="toggleDocUpload('tc')" style="cursor:pointer;">
              <label class="form-check-label ms-2" for="doc_tc" style="cursor:pointer;">Transfer Certificate (TC)</label>
            </div>
          </td>
          <td>
            <div id="upload_wrap_tc" style="display:none;">
              <input type="file" name="doc_file_tc" class="form-control form-control-sm" accept="image/jpeg,image/png,application/pdf" disabled>
              <small class="text-muted" style="font-size:0.75rem;">Upload Document (JPG, PNG, or PDF – Max 2MB)</small>
            </div>
          </td>
        </tr>
        <!-- Migration Certificate -->
        <tr>
          <td class="bg-light fw-bold text-dark">
            <div class="form-check m-0">
              <input class="form-check-input border-primary" type="checkbox" name="docs[]" value="Migration Certificate" id="doc_migration" onchange="toggleDocUpload('migration')" style="cursor:pointer;">
              <label class="form-check-label ms-2" for="doc_migration" style="cursor:pointer;">Migration Certificate</label>
            </div>
          </td>
          <td>
            <div id="upload_wrap_migration" style="display:none;">
              <input type="file" name="doc_file_migration" class="form-control form-control-sm" accept="image/jpeg,image/png,application/pdf" disabled>
              <small class="text-muted" style="font-size:0.75rem;">Upload Document (JPG, PNG, or PDF – Max 2MB)</small>
            </div>
          </td>
        </tr>
        <!-- Category Certificate -->
        <tr>
          <td class="bg-light fw-bold text-dark">
            <div class="form-check m-0">
              <input class="form-check-input border-primary" type="checkbox" name="docs[]" value="Category Certificate" id="doc_category" onchange="toggleDocUpload('category')" style="cursor:pointer;">
              <label class="form-check-label ms-2" for="doc_category" style="cursor:pointer;">Category Certificate</label>
            </div>
          </td>
          <td>
            <div id="upload_wrap_category" style="display:none;">
              <input type="file" name="doc_file_category" class="form-control form-control-sm" accept="image/jpeg,image/png,application/pdf" disabled>
              <small class="text-muted" style="font-size:0.75rem;">Upload Document (JPG, PNG, or PDF – Max 2MB)</small>
            </div>
          </td>
        </tr>
        <!-- Address Proof -->
        <tr>
          <td class="bg-light fw-bold text-dark">
            <div class="form-check m-0">
              <input class="form-check-input border-primary" type="checkbox" name="docs[]" value="Address Proof" id="doc_addr_proof" onchange="toggleDocUpload('addr_proof')" style="cursor:pointer;">
              <label class="form-check-label ms-2" for="doc_addr_proof" style="cursor:pointer;">Address Proof</label>
            </div>
          </td>
          <td>
            <div id="upload_wrap_addr_proof" style="display:none;">
              <input type="file" name="doc_file_addr_proof" class="form-control form-control-sm" accept="image/jpeg,image/png,application/pdf" disabled>
              <small class="text-muted" style="font-size:0.75rem;">Upload Document (JPG, PNG, or PDF – Max 2MB)</small>
            </div>
          </td>
        </tr>
        <!-- Domicile Certificate -->
        <tr>
          <td class="bg-light fw-bold text-dark">
            <div class="form-check m-0">
              <input class="form-check-input border-primary" type="checkbox" name="docs[]" value="Domicile Certificate" id="doc_domicile" onchange="toggleDocUpload('domicile')" style="cursor:pointer;">
              <label class="form-check-label ms-2" for="doc_domicile" style="cursor:pointer;">Domicile Certificate</label>
            </div>
          </td>
          <td>
            <div id="upload_wrap_domicile" style="display:none;">
              <input type="file" name="doc_file_domicile" class="form-control form-control-sm" accept="image/jpeg,image/png,application/pdf" disabled>
              <small class="text-muted" style="font-size:0.75rem;">Upload Document (JPG, PNG, or PDF – Max 2MB)</small>
            </div>
          </td>
        </tr>
        <tr>
          <td class="bg-light fw-bold text-dark text-secondary">Other Attached Documents</td>
          <td>
            <input type="text" name="docs_other" class="form-control form-control-sm" placeholder="Type here if any other document is attached...">
          </td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- SECTION 5: FEE DETAILS -->
  <div class="sec-title"><i class="fas fa-rupee-sign me-2"></i>SECTION 5: FEE DETAILS (Student Payment Record)</div>
  <div class="p-3 bg-light rounded-3 border mb-4 shadow-sm">
    <div class="row g-3">
      <div class="col-md-4 col-sm-6">
        <label class="fw-bold small mb-1">Admission Fee Charged (₹) *</label>
        <input type="number" step="0.01" name="admission_fee" id="adm_fee" class="form-control" required placeholder="0.00" oninput="calcTotalFee()">
      </div>
      <div class="col-md-4 col-sm-6">
        <label class="fw-bold small mb-1">Registration Fee Charged (₹) *</label>
        <input type="number" step="0.01" name="registration_fee" id="reg_fee" class="form-control" required placeholder="0.00" oninput="calcTotalFee()">
      </div>
      <div class="col-md-4 col-sm-12">
        <label class="fw-bold small mb-1 text-primary">Total Paid by Student (₹)</label>
        <input type="text" id="total_student_fee" class="form-control bg-white fw-bold text-primary fs-5 py-1" readonly value="₹ 0.00" style="border: 2px solid var(--primary);">
      </div>
      <div class="col-md-4 col-sm-6">
        <label class="fw-bold small mb-1">Payment Mode *</label>
        <select name="payment_mode" class="form-select" required>
          <option value="">-- Select Mode --</option>
          <option value="Cash">Cash</option>
          <option value="Online">Online</option>
          <option value="DD / UPI">DD / UPI</option>
        </select>
      </div>
      <div class="col-md-4 col-sm-6">
        <label class="fw-bold small mb-1">Receipt No. / Transaction ID *</label>
        <input type="text" name="payment_receipt_no" class="form-control text-uppercase" required placeholder="REC00123 / TXN98765">
      </div>
      <div class="col-md-4 col-sm-12">
        <label class="fw-bold small mb-1">Payment Date *</label>
        <input type="date" name="payment_date" class="form-control" required value="<?=date('Y-m-d')?>">
      </div>
    </div>
  </div>

  <!-- SECTION 6: DECLARATION BY STUDENT / PARENT -->
  <div class="sec-title"><i class="fas fa-file-contract me-2"></i>SECTION 6: DECLARATION BY STUDENT / PARENT</div>
  <div class="p-4 bg-light rounded-3 border mb-4 shadow-sm" style="background-color: #fbfbff!important;">
    <div class="p-3 bg-white rounded-3 border border-warning mb-3">
      <p class="mb-0 text-justify text-dark" style="line-height: 1.6; font-size: 0.92rem;">
        <i class="fas fa-quote-left text-warning me-2 fa-lg"></i>
        <strong>I hereby declare that the information furnished above is true and correct to the best of my knowledge. I agree to abide by all rules, regulations, fee policies, and examination norms of the Board/Institution.</strong>
      </p>
    </div>
    
    <div class="form-check mb-4 py-1">
      <input class="form-check-input border-primary" type="checkbox" name="declaration_accepted" value="1" id="decl_check" required style="width: 1.25em; height: 1.25em;">
      <label class="form-check-label fw-bold text-danger ms-2" for="decl_check" style="cursor: pointer; font-size: 0.95rem;">
        I / We Agree to the Declaration *
      </label>
    </div>
    
    <div class="row g-4 border-top pt-4">
      <div class="col-md-6">
        <label class="fw-bold small mb-1">Declaration Date *</label>
        <input type="date" name="declaration_date" class="form-control" required value="<?=date('Y-m-d')?>">
      </div>
      <div class="col-md-6">
        <label class="fw-bold small mb-1">Declaration Place *</label>
        <input type="text" name="declaration_place" class="form-control text-uppercase" required placeholder="e.g. MEERUT">
      </div>
    </div>
    
    <div class="row g-4 mt-2 border-top pt-4">
      <div class="col-md-6">
        <label class="fw-bold small mb-1">Student Signature (Image) *</label>
        <input type="file" name="student_signature" class="form-control" accept="image/jpeg,image/png" required>
        <small class="text-muted" style="font-size: 0.75rem;">Upload student's signature (JPG/PNG)</small>
      </div>
      <div class="col-md-6">
        <label class="fw-bold small mb-1">Parent Signature (Image)</label>
        <input type="file" name="parent_signature" class="form-control" accept="image/jpeg,image/png">
        <small class="text-muted" style="font-size: 0.75rem;">Optional</small>
      </div>
    </div>
  </div>

  <!-- TRAINING & EXAMINATION DETAILS -->
  <div class="sec-title"><i class="fas fa-shield-halved me-2"></i>Board & Center Credentials</div>
  <div class="row g-3 mb-4">
    <div class="col-md-6">
      <label class="fw-bold small mb-1">Authorized Training Center</label>
      <input type="text" class="form-control bg-light fw-bold" value="<?=htmlspecialchars($user['institution_name'])?>" readonly>
    </div>
    <div class="col-md-6">
      <label class="fw-bold small mb-1">Examining Board</label>
      <input type="text" class="form-control bg-light fw-bold text-primary" value="INDIAN BOARD OF VOCATIONAL AND TECHNICAL EDUCATION (New Delhi)" readonly>
    </div>
  </div>

  <div class="d-flex gap-3 mt-5 border-top pt-4">
    <button type="submit" class="btn btn-primary px-5 fw-bold py-3 shadow" id="subBtn" style="font-size: 1.05rem;">
      <i class="fas fa-paper-plane me-2"></i>Submit Student Admission Request
    </button>
    <a href="students.php" class="btn btn-outline-secondary px-4 py-3">Cancel</a>
  </div>
  </form>
  </div>
</div>

<?php else: ?>
<!-- ══ STUDENTS LIST ══ -->
<div class="card border-0 shadow-sm rounded-4 mb-4">
  <div class="card-body p-3">
    <form method="GET" class="row g-2">
      <div class="col-md-10">
        <div class="input-group">
          <span class="input-group-text bg-white border-end-0"><i class="fas fa-search text-muted"></i></span>
          <input type="text" name="search" class="form-control border-start-0" placeholder="Search by Name, Reg No or Mobile..." value="<?=htmlspecialchars($search)?>">
        </div>
      </div>
      <div class="col-md-2">
        <button type="submit" class="btn btn-primary w-100 fw-bold">Search</button>
      </div>
    </form>
  </div>
</div>

<div class="card border-0 shadow-sm rounded-4">
<div class="card-body p-0"><div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="bg-light">
<tr><th class="ps-3">Reg No</th><th>Student</th><th>Course</th><th>Fee</th><th>Status</th><th>Date</th><th class="pe-3">View</th></tr>
</thead><tbody>
<?php if(empty($students)):?><tr><td colspan="7" class="text-center py-5 text-muted"><i class="fas fa-user-graduate fa-2x d-block mb-2 opacity-25"></i>No students yet. <a href="?action=add">Add first</a>.</td></tr><?php endif;?>
<?php foreach($students as $s):
  $ap=$s['approval_status']??'pending';
  $cls=match($ap){'approved'=>'status-a','rejected'=>'status-r',default=>'status-p'};
?>
<tr>
  <td class="ps-3"><span class="badge bg-light border text-dark fw-bold" style="font-family:monospace"><?=htmlspecialchars($s['registration_number']??'S-'.$s['id'])?></span></td>
  <td>
    <div class="fw-bold"><?=htmlspecialchars($s['full_name'])?></div>
    <div class="small fw-bold text-primary">Roll No: <?= formatRollNumber($s['roll_number'] ?? '') ?></div>
    <small class="text-muted">📞 <?=htmlspecialchars($s['mobile']??'-')?></small>
  </td>
  <td><div class="small fw-bold"><?=htmlspecialchars($s['course_name'])?></div>
    <small class="text-muted"><?=htmlspecialchars($s['sub_name']??$s['duration_label']??'')?></small></td>
  <td class="fw-bold text-success small">₹<?=number_format($s['total_fee']??0,0)?></td>
  <td><span class="<?=$cls?>"><?=ucfirst($ap)?></span></td>
  <td class="small"><?= formatDate($s['created_at']) ?></td>

  <td class="pe-3">
    <div class="d-flex gap-1 justify-content-end">
      <a href="view-student.php?id=<?=$s['id']?>" class="btn btn-sm btn-outline-primary" title="View Profile"><i class="fas fa-eye"></i></a>
    </div>
  </td>
</tr>
<?php endforeach;?>
</tbody></table></div></div></div>

<?php if ($totalPages > 1): ?>
<nav class="mt-4">
  <ul class="pagination justify-content-center">
    <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
      <a class="page-link shadow-sm rounded-pill px-3 me-2" href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>">Previous</a>
    </li>
    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
    <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
      <a class="page-link shadow-sm mx-1 rounded-circle" style="width:40px;height:40px;display:flex;align-items:center;justify-content:center;" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
    </li>
    <?php endfor; ?>
    <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : '' ?>">
      <a class="page-link shadow-sm rounded-pill px-3 ms-2" href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>">Next</a>
    </li>
  </ul>
</nav>
<?php endif; ?>

<?php endif;?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const walletBal  = <?=json_encode($walletBal)?>;
const subCatData = <?=json_encode($sub_categories)?>;
const courseData = <?=json_encode($courses)?>;

function filterSubCats(sel) {
    const catId = sel.value;
    const sWrap = document.getElementById('subCatWrap');
    const sSelect = document.getElementById('subCatSelect');
    const cWrap = document.getElementById('courseWrap');
    
    sSelect.innerHTML = '<option value="">-- Select Sub Category --</option>';
    document.getElementById('courseSelect').innerHTML = '<option value="">-- Select Course --</option>';
    sWrap.style.display = 'none';
    cWrap.style.display = 'none';
    hideFee();

    if (!catId) return;

    const filtered = subCatData.filter(s => s.category_id == catId);
    if (filtered.length > 0) {
        sWrap.style.display = '';
        sSelect.required = true;
        filtered.forEach(s => {
            sSelect.innerHTML += `<option value="${s.id}">${s.name}</option>`;
        });
    }
}

function filterCourses(sel) {
    const subCatId = sel.value;
    const cWrap = document.getElementById('courseWrap');
    const cSelect = document.getElementById('courseSelect');
    
    cSelect.innerHTML = '<option value="">-- Select Course --</option>';
    cWrap.style.display = 'none';
    cSelect.required = false;
    hideFee();

    if (!subCatId) return;

    const filtered = courseData.filter(c => c.sub_category_id == subCatId);
    if (filtered.length > 0) {
        cWrap.style.display = '';
        cSelect.required = true;
        filtered.forEach(c => {
            cSelect.innerHTML += `<option value="${c.id}" data-fee="${c.total_fee||0}" data-name="${c.course_name}">${c.course_name}</option>`;
        });
    }
}

function pickCourse(sel) {
    const opt = sel.options[sel.selectedIndex];
    if (opt.value) showFee(parseFloat(opt.dataset.fee||0), opt.dataset.name||'');
    else hideFee();
}

function showFee(fee, name) {
    document.getElementById('feeAmt').textContent = '₹' + fee.toLocaleString('en-IN',{minimumFractionDigits:2});
    document.getElementById('feeName').textContent = name;
    document.getElementById('feeBox').style.display = '';
    const warn = document.getElementById('feeWarn');
    const btn  = document.getElementById('subBtn');
    if (walletBal < fee) {
        warn.classList.remove('d-none');
        // Keep button enabled but show warning
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Submit Admission Request (Insufficient Balance)';
    } else {
        warn.classList.add('d-none');
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Submit Admission Request';
    }
}
function hideFee() { document.getElementById('feeBox').style.display='none'; }

function previewPhoto(inp) {
    if (!inp.files[0]) return;
    const box = document.getElementById('photoBox');
    const reader = new FileReader();
    reader.onload = e => box.innerHTML = `<img src="${e.target.result}" style="width:120px;height:145px;object-fit:cover;border-radius:10px;">`;
    reader.readAsDataURL(inp.files[0]);
}

function toggleSidebar(){
    document.getElementById('collegeSidebar').classList.toggle('open');
    document.getElementById('sidebarOverlay').classList.toggle('d-none');
}
if(window.innerWidth<768){const b=document.getElementById('mobileMenuBtn');if(b)b.style.display='flex';}

// --- NEW HELPER JAVASCRIPT ---

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_student_fee').value = '₹ ' + total.toLocaleString('en-IN', {minimumFractionDigits: 2});
}

// Add real-time sync event listeners to permanent address fields
document.addEventListener('DOMContentLoaded', () => {
    const fields = ['address', 'district', 'state', 'pincode'];
    fields.forEach(f => {
        const permEl = document.getElementById('perm_' + f);
        if (permEl) {
            permEl.addEventListener('input', () => {
                const check = document.getElementById('corrSameCheck');
                if (check && check.checked) {
                    const corrEl = document.getElementById('corr_' + f);
                    if (corrEl) {
                        corrEl.value = permEl.value;
                    }
                }
            });
        }
    });
});

function toggleDocUpload(slug) {
    const chk = document.getElementById('doc_' + slug);
    const wrap = document.getElementById('upload_wrap_' + slug);
    if (chk && wrap) {
        const inp = wrap.querySelector('input[type="file"]');
        if (chk.checked) {
            wrap.style.display = '';
            if (inp) inp.disabled = false;
        } else {
            wrap.style.display = 'none';
            if (inp) {
                inp.disabled = true;
                inp.value = '';
            }
        }
    }
}
</script>
</body></html>
