<?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        = $_POST['dob'] ?? '';
    $address    = cleanInput($_POST['address']      ?? '');
    $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';

    // Get fee from sub_item or course_fees
    if ($subItemId) {
        $feeRow = $db->fetchOne("SELECT * FROM course_sub_items WHERE id=?", [$subItemId]);
        $totalFee = floatval($feeRow['total_fee'] ?? 0);
        $trainingPeriod = $feeRow['duration_label'] ?? '';
    } else {
        $feeRow = $db->fetchOne("SELECT * FROM course_fees WHERE course_id=? AND user_type='college'", [$courseId]);
        $totalFee = floatval($feeRow['total_fee'] ?? 0);
        $trainingPeriod = $_POST['training_period'] ?? '';
    }

    // 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');

    // 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'])) {
            $dir = __DIR__ . '/../uploads/students/photos/';
            $fn  = $regNo . '_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $dir . $fn)) {
                $photoPath = 'uploads/students/photos/' . $fn;
            }
        }
    }

    $sid = $db->insert('students', [
        'registration_number' => $regNo,
        'full_name'           => $fullName,
        'father_name'         => $fatherName,
        'mother_name'         => $motherName,
        'date_of_birth'       => $dob,
        'address'             => $address,
        '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');
    }
}

// Data
$categories = $db->fetchAll("SELECT * FROM course_categories WHERE is_active=1 ORDER BY 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.category,c.course_name");
$subItems = $db->fetchAll("SELECT * FROM course_sub_items WHERE is_active=1 ORDER BY course_id,duration_value");
// Search and Pagination
$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, csi.sub_name, csi.duration_label 
        FROM students s 
        JOIN courses c ON s.course_id = c.id 
        LEFT JOIN course_sub_items csi ON s.sub_item_id = csi.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):?>
  <a href="?action=add" class="btn btn-primary px-4 fw-bold"><i class="fas fa-plus me-2"></i>New Admission</a>
  <?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>Course</div>
  <div class="row g-3">
    <div class="col-md-4">
      <label class="fw-bold small">Course Category *</label>
      <select class="form-select" id="categorySelect" required onchange="filterCourses(this)">
        <option value="">-- Select Category --</option>
        <?php foreach($categories as $cat):?>
        <option value="<?=htmlspecialchars($cat['name'])?>"><?=htmlspecialchars($cat['name'])?></option>
        <?php endforeach;?>
      </select>
    </div>
    <div class="col-md-4" id="courseWrap" style="display:none;">
      <label class="fw-bold small">Select Course *</label>
      <select class="form-select" id="courseSelect" name="course_id" required onchange="loadSubs(this)">
        <option value="">-- Select Course --</option>
      </select>
    </div>
    <div class="col-md-4" id="subWrap" style="display:none;">
      <label class="fw-bold small">Sub Course / Duration *</label>
      <select class="form-select" id="subSelect" onchange="pickSub(this)">
        <option value="">-- Select Sub Course --</option>
      </select>
    </div>
  </div>
    <div class="col-md-2">
      <label class="fw-bold small">Session</label>
      <input type="text" name="session" class="form-control" value="<?=date('Y').'-'.(date('Y')+1)?>">
    </div>
    <div class="col-md-3">
      <label class="fw-bold small">Admission Date *</label>
      <input type="date" name="admission_date" class="form-control" required value="<?=date('Y-m-d')?>">
    </div>
  </div>

  <!-- STUDENT DETAILS -->
  <div class="sec-title"><i class="fas fa-user me-2"></i>Student Details</div>
  <div class="row g-3">
    <!-- Photo upload -->
    <div class="col-md-2 text-center">
      <label class="fw-bold small d-block mb-2">Photo *</label>
      <div class="photo-preview mx-auto" onclick="document.getElementById('photoInput').click()" id="photoBox">
        <div class="text-center text-muted small"><i class="fas fa-camera fa-2x d-block mb-1 opacity-50"></i>Click to upload</div>
      </div>
      <input type="file" name="photo" id="photoInput" accept="image/jpeg,image/png" class="d-none" required onchange="previewPhoto(this)">
      <small class="text-muted">JPG/PNG, max 2MB</small>
    </div>
    <div class="col-md-10">
      <div class="row g-3">
        <div class="col-md-4"><label class="fw-bold small">Student Name *</label><input type="text" name="full_name" class="form-control" required placeholder="As per documents"></div>
        <div class="col-md-4"><label class="fw-bold small">Father's Name *</label><input type="text" name="father_name" class="form-control" required></div>
        <div class="col-md-4"><label class="fw-bold small">Mother's Name *</label><input type="text" name="mother_name" class="form-control" required></div>
        <div class="col-md-3"><label class="fw-bold small">Date of Birth *</label><input type="date" name="dob" class="form-control" required></div>
        <div class="col-md-3"><label class="fw-bold small">Phone *</label><input type="tel" name="mobile" class="form-control" required pattern="[6-9][0-9]{9}" placeholder="10 digits"></div>
        <div class="col-md-6"><label class="fw-bold small">Email</label><input type="email" name="email" class="form-control" placeholder="optional"></div>
        <div class="col-12"><label class="fw-bold small">Address *</label><textarea name="address" class="form-control" rows="2" required placeholder="Full address with city, state, pin"></textarea></div>
      </div>
    </div>
  </div>

  <!-- TRAINING -->
  <div class="sec-title"><i class="fas fa-school me-2"></i>Training & Examination</div>
  <div class="row g-3">
    <div class="col-md-6">
      <label class="fw-bold small">Training Center</label>
      <input type="text" class="form-control bg-light" value="<?=htmlspecialchars($user['institution_name'])?>" readonly>
    </div>
    <div class="col-md-6">
      <label class="fw-bold small">Examining Body</label>
      <input type="text" class="form-control bg-light fw-bold text-primary" value="INDIAN BOARD OF VOCATIONAL AND TECHNICAL EDUCATION, NEW DELHI" readonly>
      <small class="text-muted">Registrar – INDIAN BOARD OF VOCATIONAL AND TECHNICAL EDUCATION</small>
    </div>
  </div>

  <div class="d-flex gap-3 mt-4">
    <button type="submit" class="btn btn-primary px-5 fw-bold py-2" id="subBtn">
      <i class="fas fa-paper-plane me-2"></i>Submit Admission Request
    </button>
    <a href="students.php" class="btn btn-outline-secondary px-4">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>Admit Card</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: <?= htmlspecialchars($s['roll_number'] ?? 'Pending') ?></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"><?=date('d M Y',strtotime($s['created_at']))?></td>
  <td>
    <a href="admit-card.php?id=<?=$s['id']?>" target="_blank" class="btn btn-sm btn-info text-white shadow-sm">
      <i class="fas fa-id-card me-1"></i>Admit Card
    </a>
  </td>
  <td class="pe-3"><a href="view-student.php?id=<?=$s['id']?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-eye"></i></a></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 subData    = <?=json_encode($subJson)?>;
const courseData = <?=json_encode($courses)?>;

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

    if (!cat) {
        cWrap.style.display = 'none';
        return;
    }

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

function loadSubs(sel) {
    const cid  = sel.value;
    const wrap = document.getElementById('subWrap');
    const sub  = document.getElementById('subSelect');
    document.getElementById('subItemId').value = '';
    if (!cid || !subData[cid] || !subData[cid].length) {
        wrap.style.display = 'none';
        // Use course-level fee
        const opt = sel.options[sel.selectedIndex];
        showFee(parseFloat(opt.dataset.fee||0), opt.dataset.name||'');
        return;
    }
    wrap.style.display = '';
    sub.innerHTML = '<option value="">-- Select Sub Course --</option>';
    subData[cid].forEach(s => {
        sub.innerHTML += `<option value="${s.id}" data-fee="${s.total_fee}" data-name="${s.sub_name}">${s.sub_name} (${s.duration_label}) — ₹${parseFloat(s.total_fee).toLocaleString('en-IN')}</option>`;
    });
    hideFee();
}

function pickSub(sel) {
    const opt = sel.options[sel.selectedIndex];
    document.getElementById('subItemId').value = opt.value || '';
    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'); btn.disabled=true; btn.innerHTML='<i class="fas fa-wallet me-2"></i>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:150px;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';}
</script>
</body></html>
