<?php
/**
 * IBVTE Admin – Affiliation Applications
 * View/Edit/Approve/Reject applications submitted via apply.php
 */
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();
$admin = Auth()->getUser();
$flash = getFlashMessage();
$action = $_GET['action'] ?? 'list';
$id     = intval($_GET['id'] ?? 0);

// ── APPROVE ──────────────────────────────────────────────────────────────────
if ($action === 'approve' && $id) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        redirectWithMessage('affiliations.php', 'Security session expired. Please try again.', 'danger');
    }

    $app = $db->fetchOne("SELECT * FROM affiliation_applications WHERE id = ?", [$id]);
    if ($app && $app['application_status'] !== 'approved') {
        $name     = preg_replace('/[^A-Z0-9]/i', '', strtoupper($app['institution_name']));
        $username = 'CLG' . substr($name, 0, 5) . rand(100, 999);
        $password = 'Ibvte@' . rand(1000, 9999);
        $passHash = password_hash($password, PASSWORD_DEFAULT);
        $instCode = 'IBVTE' . date('Y') . str_pad($id, 4, '0', STR_PAD_LEFT);

        $userId = null;
        try {
            $userId = $db->insert('users', [
                'role_id'             => ROLE_COLLEGE,
                'username'            => $username,
                'email'               => $app['director_email'],
                'password_hash'       => $passHash,
                'full_name'           => $app['director_name'],
                'mobile'              => $app['director_mobile'],
                'institution_name'    => $app['institution_name'],
                'institution_code'    => $instCode,
                'city'                => $app['city'],
                'state'               => $app['state'],
                'affiliation_status'  => 'approved',
                'is_active'           => 1,
                'created_at'          => date('Y-m-d H:i:s'),
            ]);
            $db->insert('wallets', [
                'user_id'     => $userId,
                'wallet_type' => 'college',
                'balance'     => 0,
                'created_at'  => date('Y-m-d H:i:s'),
            ]);
        } catch (Exception $e) {
            error_log("Affiliation Approval Error: " . $e->getMessage());
        }

        $db->update('affiliation_applications', [
            'application_status'  => 'approved',
            'approved_by'         => $admin['id'],
            'approved_at'         => date('Y-m-d H:i:s'),
            'approval_valid_from' => date('Y-m-d'),
            'approval_valid_until'=> date('Y-m-d', strtotime('+3 years')),
        ], ['id' => $id]);

        $_SESSION['cred_modal'] = [
            'username' => $username,
            'password' => $password,
            'inst'     => $app['institution_name'],
            'code'     => $instCode,
        ];
        redirectWithMessage('affiliations.php', "✅ Approved! College account created: <strong>$username</strong>", 'success');
    }
}

// ── REJECT ────────────────────────────────────────────────────────────────────
if ($action === 'reject' && $id) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        redirectWithMessage('affiliations.php', 'Security session expired. Please try again.', 'danger');
    }

    $db->update('affiliation_applications', [
        'application_status' => 'rejected',
        'approved_by'        => $admin['id'],
        'approved_at'        => date('Y-m-d H:i:s'),
        'review_remarks'     => trim($_GET['reason'] ?? 'Rejected by admin'),
    ], ['id' => $id]);
    redirectWithMessage('affiliations.php', '❌ Application rejected.', 'warning');
}

// ── UNDER REVIEW ──────────────────────────────────────────────────────────────
if ($action === 'review' && $id) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_GET['csrf_token'] ?? '')) {
        redirectWithMessage('affiliations.php', 'Security session expired. Please try again.', 'danger');
    }

    $db->update('affiliation_applications', ['application_status' => 'under_review'], ['id' => $id]);
    redirectWithMessage('affiliations.php', '🔍 Marked as Under Review.', 'info');
}

// ── SAVE EDIT ─────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_edit'])) {
    // CSRF Protection
    if (!Auth()->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        redirectWithMessage('affiliations.php', 'Security session expired. Please try again.', 'danger');
    }

    $eid = intval($_POST['edit_id']);
    $app = $db->fetchOne("SELECT * FROM affiliation_applications WHERE id = ?", [$eid]);
    if (!$app) {
        redirectWithMessage('affiliations.php', 'Application not found.', 'danger');
    }

    // Process Director Photo
    $directorPhoto = $app['director_photo'] ?? '';
    if (isset($_POST['delete_director_photo']) && $_POST['delete_director_photo'] == '1') {
        $directorPhoto = '';
    }
    if (isset($_FILES['director_photo_file']) && $_FILES['director_photo_file']['error'] === UPLOAD_ERR_OK) {
        $fileTmp = $_FILES['director_photo_file']['tmp_name'];
        $fileName = $_FILES['director_photo_file']['name'];
        $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg', 'jpeg', 'png'])) {
            $destDir = __DIR__ . '/../uploads/affiliation';
            if (!is_dir($destDir)) {
                mkdir($destDir, 0777, true);
            }
            $newFileName = 'photo_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
            if (move_uploaded_file($fileTmp, $destDir . '/' . $newFileName)) {
                $directorPhoto = 'uploads/affiliation/' . $newFileName;
            }
        }
    }

    // Process Documents
    $uploadedDocs = json_decode($app['uploaded_documents'] ?? '[]', true);
    if (!is_array($uploadedDocs)) {
        $uploadedDocs = [];
    }

    $docsCheck = [
        0 => 'Registration Certificate of Trust/Society/Firm',
        1 => "Director's ID Proof (Aadhar Card / PAN Card)",
        2 => "Director's Address Proof",
        3 => 'Building Ownership Proof / Rent Agreement',
        4 => 'Staff & Faculty Qualification Documents',
        5 => 'Center Infrastructure Photos (Inner & Outer View)',
        6 => 'Processing Fee Receipt',
        7 => 'Copy of Institution PAN Card',
        8 => 'Other Documents'
    ];

    for ($i = 0; $i <= 8; $i++) {
        // Check delete
        if (isset($_POST["delete_doc_$i"]) && $_POST["delete_doc_$i"] == '1') {
            unset($uploadedDocs[$i]);
        }
        // Check upload
        if (isset($_FILES["doc_file_$i"]) && $_FILES["doc_file_$i"]['error'] === UPLOAD_ERR_OK) {
            $fileTmp = $_FILES["doc_file_$i"]['tmp_name'];
            $fileName = $_FILES["doc_file_$i"]['name'];
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            if (in_array($ext, ['pdf', 'jpg', 'jpeg', 'png'])) {
                $destDir = __DIR__ . '/../uploads/affiliation';
                if (!is_dir($destDir)) {
                    mkdir($destDir, 0777, true);
                }
                $newFileName = 'doc_' . $i . '_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
                if (move_uploaded_file($fileTmp, $destDir . '/' . $newFileName)) {
                    $uploadedDocs[$i] = 'uploads/affiliation/' . $newFileName;
                }
            }
        }
    }

    // Re-generate documents_attached string based on current keys in uploadedDocs
    $attachedNames = [];
    foreach ($uploadedDocs as $idx => $path) {
        if (isset($docsCheck[$idx])) {
            $attachedNames[] = $docsCheck[$idx];
        }
    }
    $documentsAttachedStr = implode(', ', $attachedNames);

    // Process Faculty & Courses arrays
    $facultyDetailsJson = $_POST['faculty_details'] ?? '[]';
    $coursesAppliedDetailsJson = $_POST['courses_applied_details'] ?? '[]';

    // Parse courses to extract names for JSON CHECK constraint validation
    $coursesArr = json_decode($coursesAppliedDetailsJson, true);
    if (!is_array($coursesArr)) {
        $coursesArr = [];
    }
    $courseNames = array_column($coursesArr, 'name');
    $coursesAppliedJson = json_encode($courseNames, JSON_UNESCAPED_UNICODE);

    // Process checkboxes for Applied For
    $appliedForArr = $_POST['applied_for_opts'] ?? [];
    $appliedForStr = implode(', ', $appliedForArr);

    $db->update('affiliation_applications', [
        'institution_name'           => trim($_POST['institution_name']),
        'proposed_center_name'       => trim($_POST['proposed_center_name'] ?? ''),
        'director_name'              => trim($_POST['director_name']),
        'father_guardian_name'       => trim($_POST['father_guardian_name'] ?? ''),
        'director_mobile'            => trim($_POST['director_mobile']),
        'whatsapp_no'                => trim($_POST['whatsapp_no'] ?? ''),
        'director_email'             => trim($_POST['director_email']),
        'director_photo'             => $directorPhoto,
        'registered_address'         => trim($_POST['registered_address'] ?? ''),
        'communication_address'      => trim($_POST['communication_address'] ?? ''),
        'city'                       => trim($_POST['city']),
        'state'                      => trim($_POST['state']),
        'pincode'                    => trim($_POST['pincode'] ?? ''),
        'district'                   => trim($_POST['district'] ?? ''),
        'registration_number'        => trim($_POST['registration_number'] ?? ''),
        'registration_date'          => trim($_POST['registration_date'] ?? ''),
        'pan_gst_no'                 => trim($_POST['pan_gst_no'] ?? ''),
        'identity_proof_no'          => trim($_POST['identity_proof_no'] ?? ''),
        'bank_name'                  => trim($_POST['bank_name'] ?? ''),
        'bank_account_no'            => trim($_POST['bank_account_no'] ?? ''),
        'bank_ifsc'                  => trim($_POST['bank_ifsc'] ?? ''),
        
        'applied_for'                => $appliedForStr,
        'building_type'              => trim($_POST['building_type'] ?? ''),
        'total_area'                 => trim($_POST['total_area'] ?? ''),
        'number_of_classrooms'       => intval($_POST['number_of_classrooms'] ?? 0),
        'library_facility'           => isset($_POST['library_facility']) ? 1 : 0,
        'computer_lab'               => isset($_POST['computer_lab']) ? 1 : 0,
        'internet_facility'          => isset($_POST['internet_facility']) ? 1 : 0,
        'total_staff'                => intval($_POST['total_staff'] ?? 0),
        'practical_lab_facility'     => isset($_POST['practical_lab_facility']) ? 1 : 0,
        'computer_systems_available' => isset($_POST['computer_systems_available']) ? 1 : 0,
        'total_computers'            => intval($_POST['total_computers'] ?? 0),
        'power_backup_facility'      => isset($_POST['power_backup_facility']) ? 1 : 0,
        'clean_drinking_water'       => isset($_POST['clean_drinking_water']) ? 1 : 0,
        'furniture_available'        => isset($_POST['furniture_available']) ? 1 : 0,
        'washroom_facility'          => isset($_POST['washroom_facility']) ? 1 : 0,
        'safety_fire_extinguisher'   => isset($_POST['safety_fire_extinguisher']) ? 1 : 0,
        
        'faculty_details'            => $facultyDetailsJson,
        'courses_applied_details'    => $coursesAppliedDetailsJson,
        'courses_applied'            => $coursesAppliedJson,
        
        'uploaded_documents'         => json_encode($uploadedDocs, JSON_UNESCAPED_SLASHES),
        'documents_attached'         => $documentsAttachedStr,
        
        'review_remarks'             => trim($_POST['review_remarks']),
    ], ['id' => $eid]);

    redirectWithMessage('affiliations.php', '✏️ Application updated successfully.', 'success');
}

// ── FETCH DATA ────────────────────────────────────────────────────────────────
$statusFilter = $_GET['status'] ?? '';
$sql    = "SELECT * FROM affiliation_applications";
$params = [];
if ($statusFilter) { $sql .= " WHERE application_status = ?"; $params[] = $statusFilter; }
$sql .= " ORDER BY created_at DESC";
$applications = $db->fetchAll($sql, $params);

$counts = [
    'all'          => $db->count('affiliation_applications'),
    'submitted'    => $db->count('affiliation_applications', ['application_status' => 'submitted']),
    'under_review' => $db->count('affiliation_applications', ['application_status' => 'under_review']),
    'approved'     => $db->count('affiliation_applications', ['application_status' => 'approved']),
    'rejected'     => $db->count('affiliation_applications', ['application_status' => 'rejected']),
];

$viewApp   = ($action === 'view' && $id) ? $db->fetchOne("SELECT * FROM affiliation_applications WHERE id = ?", [$id]) : null;
$credModal = $_SESSION['cred_modal'] ?? null;
unset($_SESSION['cred_modal']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Affiliation Applications – <?= 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>
        .details-badge {
            font-size: 0.8rem;
            padding: 5px 10px;
            border-radius: 6px;
        }
        .board-office-section {
            border: 2px dashed #dc3545;
            background: #fff8f8;
            border-radius: 10px;
            padding: 20px;
            margin-top: 25px;
        }
        .card-header-purple {
            background: linear-gradient(135deg, #3b0b7c, #6c4ab6);
            color: white;
        }
    </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">
                <h2 class="h3"><i class="fas fa-file-signature me-2 text-primary"></i>Affiliation Applications</h2>
                <div>
                    <span class="badge bg-warning text-dark fs-6 me-2"><?= $counts['submitted'] ?> New</span>
                    <span class="badge bg-info fs-6"><?= $counts['under_review'] ?> Under Review</span>
                </div>
            </div>

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

            <!-- Status Filter Tabs -->
            <ul class="nav nav-pills mb-4 flex-wrap gap-1">
                <li class="nav-item"><a class="nav-link <?= !$statusFilter ? 'active' : '' ?>" href="affiliations.php">All (<?= $counts['all'] ?>)</a></li>
                <li class="nav-item"><a class="nav-link <?= $statusFilter==='submitted'    ? 'active' : '' ?>" href="?status=submitted">📥 New (<?= $counts['submitted'] ?>)</a></li>
                <li class="nav-item"><a class="nav-link <?= $statusFilter==='under_review' ? 'active' : '' ?>" href="?status=under_review">🔍 Under Review (<?= $counts['under_review'] ?>)</a></li>
                <li class="nav-item"><a class="nav-link <?= $statusFilter==='approved'     ? 'active' : '' ?>" href="?status=approved">✅ Approved (<?= $counts['approved'] ?>)</a></li>
                <li class="nav-item"><a class="nav-link <?= $statusFilter==='rejected'     ? 'active' : '' ?>" href="?status=rejected">❌ Rejected (<?= $counts['rejected'] ?>)</a></li>
            </ul>

            <!-- Table -->
            <div class="card shadow-sm border-0 mb-4" style="border-radius:15px;">
                <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">App No.</th>
                                    <th>Institution</th>
                                    <th>Contact</th>
                                    <th>Location</th>
                                    <th>Status</th>
                                    <th>Submitted</th>
                                    <th class="text-end pe-3">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if (empty($applications)): ?>
                                <tr><td colspan="7" class="text-center py-5 text-muted">
                                    <i class="fas fa-inbox fa-2x mb-2 d-block opacity-50"></i>No applications found.
                                </td></tr>
                            <?php endif; ?>
                            <?php foreach ($applications as $a):
                                $badge = match($a['application_status']) {
                                    'approved'     => 'bg-success',
                                    'rejected'     => 'bg-danger',
                                    'under_review' => 'bg-info',
                                    'submitted'    => 'bg-warning text-dark',
                                    default        => 'bg-secondary',
                                };
                                $label = match($a['application_status']) {
                                    'submitted'    => 'New',
                                    'under_review' => 'Under Review',
                                    'approved'     => 'Approved',
                                    'rejected'     => 'Rejected',
                                    default        => ucfirst($a['application_status']),
                                };
                            ?>
                            <tr>
                                <td class="ps-3">
                                    <span class="badge bg-dark"><?= htmlspecialchars($a['application_number'] ?? '#'.$a['id']) ?></span>
                                </td>
                                <td>
                                    <div class="fw-bold text-primary"><?= htmlspecialchars($a['institution_name']) ?></div>
                                    <small class="text-muted"><?= htmlspecialchars($a['institution_type'] ?: 'Institution') ?></small>
                                </td>
                                <td>
                                    <div><?= htmlspecialchars($a['director_name']) ?></div>
                                    <small class="text-muted"><?= htmlspecialchars($a['director_mobile']) ?></small>
                                </td>
                                <td><small><?= htmlspecialchars(($a['city'] ?? '') . ', ' . ($a['state'] ?? '')) ?></small></td>
                                <td><span class="badge <?= $badge ?>"><?= $label ?></span></td>
                                <td><small><?= $a['submitted_at'] ? date('d M Y', strtotime($a['submitted_at'])) : date('d M Y', strtotime($a['created_at'])) ?></small></td>
                                <td class="text-end pe-3">
                                    <div class="btn-group btn-group-sm">
                                        <a href="?action=view&id=<?= $a['id'] ?>#detailPanel" class="btn btn-outline-primary" title="View Details">
                                            <i class="fas fa-eye"></i> View Details
                                        </a>
                                        <button class="btn btn-outline-secondary" title="Edit"
                                                onclick='openEdit(<?= json_encode($a) ?>)'>
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <?php if (in_array($a['application_status'], ['submitted','under_review'])): ?>
                                        <a href="?action=review&id=<?= $a['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-outline-info" title="Mark Under Review">
                                            <i class="fas fa-search"></i>
                                        </a>
                                        <a href="?action=approve&id=<?= $a['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-success" title="Approve"
                                           onclick="return confirm('Approve and create college login account?')">
                                            <i class="fas fa-check"></i>
                                        </a>
                                        <a href="?action=reject&id=<?= $a['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-danger" title="Reject"
                                           onclick="return confirm('Reject this application?')">
                                            <i class="fas fa-times"></i>
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Detail Panel -->
            <?php if ($viewApp): 
                $facultyArr = json_decode($viewApp['faculty_details'] ?? '[]', true);
                $coursesArr = json_decode($viewApp['courses_applied_details'] ?? '[]', true);
            ?>
            <div class="card mt-4 shadow border-0" id="detailPanel" style="border-radius:15px; overflow:hidden;">
                <div class="card-header d-flex justify-content-between align-items-center card-header-purple px-4 py-3">
                    <h5 class="mb-0"><i class="fas fa-university me-2"></i><?= htmlspecialchars($viewApp['institution_name']) ?>
                        &nbsp;<small class="badge bg-light text-dark"><?= htmlspecialchars($viewApp['application_number'] ?? '#'.$viewApp['id']) ?></small>
                    </h5>
                    <a href="affiliations.php" class="btn btn-sm btn-light">✕ Close</a>
                </div>
                <div class="card-body px-4 py-4">
                    
                    <div class="row g-4">
                        <!-- SECTION 1 -->
                        <div class="col-md-6">
                            <h6 class="text-primary fw-bold border-bottom pb-2 mb-3"><i class="fas fa-info-circle me-1"></i>SECTION 1: Institution & Director Details</h6>
                            <div class="row">
                                <div class="col-8">
                                    <table class="table table-sm table-borderless">
                                        <tr><td class="text-muted w-45">Institution Name:</td><td><strong><?= htmlspecialchars($viewApp['institution_name']) ?></strong></td></tr>
                                        <tr><td class="text-muted">Director Name:</td><td><?= htmlspecialchars($viewApp['director_name']) ?></td></tr>
                                        <tr><td class="text-muted">Father/Guardian:</td><td><?= htmlspecialchars($viewApp['father_guardian_name'] ?? '-') ?></td></tr>
                                        <tr><td class="text-muted">Registered Address:</td><td><?= htmlspecialchars($viewApp['registered_address'] ?? '-') ?></td></tr>
                                        <tr><td class="text-muted">Communication Address:</td><td><?= htmlspecialchars($viewApp['communication_address'] ?? $viewApp['address'] ?? '-') ?></td></tr>
                                        <tr><td class="text-muted">PIN Code:</td><td><?= htmlspecialchars($viewApp['pincode'] ?? '-') ?></td></tr>
                                        <tr><td class="text-muted">Mobile No:</td><td><?= htmlspecialchars($viewApp['director_mobile'] ?? '-') ?></td></tr>
                                        <tr><td class="text-muted">WhatsApp No:</td><td><?= htmlspecialchars($viewApp['whatsapp_no'] ?? '-') ?></td></tr>
                                        <tr><td class="text-muted">Email ID:</td><td><?= htmlspecialchars($viewApp['director_email'] ?? '-') ?></td></tr>
                                        <tr><td class="text-muted">Website:</td><td><a href="<?= htmlspecialchars($viewApp['website'] ?? '') ?>" target="_blank"><?= htmlspecialchars($viewApp['website'] ?? '-') ?></a></td></tr>
                                    </table>
                                </div>
                                <div class="col-4 text-center">
                                    <?php if (!empty($viewApp['director_photo'])): ?>
                                        <img src="../<?= htmlspecialchars($viewApp['director_photo']) ?>" alt="Director Photo" class="img-thumbnail shadow-sm mb-1" style="max-height: 140px; width: 120px; object-fit: cover; border-radius: 8px; border: 2px solid #6c4ab6;">
                                        <div class="small fw-bold text-muted mt-1">Director's Photo</div>
                                    <?php else: ?>
                                        <div class="border rounded p-2 text-muted bg-light small d-flex flex-column align-items-center justify-content-center" style="height: 140px; border-style: dashed !important;">
                                            <i class="fas fa-user-tie fa-2x mb-2 text-muted"></i>
                                            <span>No Photo</span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- SECTION 2 -->
                        <div class="col-md-6">
                            <h6 class="text-primary fw-bold border-bottom pb-2 mb-3"><i class="fas fa-balance-scale me-1"></i>SECTION 2: Legal, Financial & Bank Details</h6>
                            <table class="table table-sm table-borderless">
                                <tr><td class="text-muted w-40">Institution Type:</td><td><span class="badge bg-secondary"><?= htmlspecialchars($viewApp['institution_type'] ?? '-') ?></span></td></tr>
                                <tr><td class="text-muted">Registration No:</td><td><?= htmlspecialchars($viewApp['registration_number'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Registration Date:</td><td><?= htmlspecialchars($viewApp['registration_date'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">PAN / GST No:</td><td><?= htmlspecialchars($viewApp['pan_gst_no'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Identity Proof No:</td><td><?= htmlspecialchars($viewApp['identity_proof_no'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Building Ownership:</td><td><span class="badge bg-light text-dark"><?= htmlspecialchars(ucfirst($viewApp['building_type'] ?? '-')) ?></span></td></tr>
                                <tr><td class="text-muted">Established Year:</td><td><?= htmlspecialchars($viewApp['established_year'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Total Staff Count:</td><td><?= htmlspecialchars($viewApp['total_staff'] ?? '-') ?></td></tr>
                            </table>
                            
                            <h6 class="text-secondary fw-bold mt-3 mb-2 small"><i class="fas fa-university me-1"></i>Institution Bank Details</h6>
                            <table class="table table-sm table-bordered bg-light mb-0">
                                <tr><td class="text-muted small w-40">Bank Name</td><td class="small fw-bold"><?= htmlspecialchars($viewApp['bank_name'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted small">Account No</td><td class="small fw-bold"><?= htmlspecialchars($viewApp['bank_account_no'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted small">IFSC Code</td><td class="small fw-bold"><?= htmlspecialchars($viewApp['bank_ifsc'] ?? '-') ?></td></tr>
                            </table>
                        </div>
                    </div>

                    <div class="row g-4 mt-1">
                        <!-- SECTION 3 & 4 -->
                        <div class="col-md-6">
                            <h6 class="text-primary fw-bold border-bottom pb-2 mb-3"><i class="fas fa-clipboard-list me-1"></i>SECTION 3 & 4: Requirements & Infrastructure</h6>
                            <table class="table table-sm table-borderless">
                                <tr><td class="text-muted w-40">Applied For:</td><td><strong><?= htmlspecialchars($viewApp['applied_for'] ?? '-') ?></strong></td></tr>
                                <tr><td class="text-muted">Proposed Center Name:</td><td><strong class="text-purple"><?= htmlspecialchars($viewApp['proposed_center_name'] ?? '-') ?></strong></td></tr>
                                <tr><td class="text-muted">Classrooms:</td><td><?= htmlspecialchars($viewApp['number_of_classrooms'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Covered Area (Sq Ft):</td><td><?= htmlspecialchars($viewApp['total_area'] ?? '-') ?></td></tr>
                                <tr><td class="text-muted">Practical Lab:</td><td><?= $viewApp['practical_lab_facility'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Computers Lab:</td><td><?= $viewApp['computer_systems_available'] ? '<span class="badge bg-success">Yes (Total: '.$viewApp['total_computers'].')</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Internet Facility:</td><td><?= $viewApp['internet_facility'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Power Backup:</td><td><?= $viewApp['power_backup_facility'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Clean Drinking Water:</td><td><?= $viewApp['clean_drinking_water'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Furniture Available:</td><td><?= $viewApp['furniture_available'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Washrooms:</td><td><?= $viewApp['washroom_facility'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                                <tr><td class="text-muted">Fire Extinguishers:</td><td><?= $viewApp['safety_fire_extinguisher'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-secondary">No</span>' ?></td></tr>
                            </table>
                        </div>

                        <!-- SECTION 7 & 8 -->
                        <div class="col-md-6">
                            <h6 class="text-primary fw-bold border-bottom pb-2 mb-3"><i class="fas fa-folder-open me-1"></i>SECTION 7 & 8: Documents & Declaration</h6>
                            
                            <label class="fw-bold small text-secondary d-block mb-2">Attached Documents Checkbox List & Uploads:</label>
                            <div class="p-2 border rounded bg-light mb-3" style="max-height: 200px; overflow-y: auto;">
                                <?php 
                                $docs = explode(', ', $viewApp['documents_attached'] ?? '');
                                $uploadedDocsArr = json_decode($viewApp['uploaded_documents'] ?? '[]', true);
                                
                                $docsCheckList = [
                                    'Registration Certificate of Trust/Society/Firm',
                                    "Director's ID Proof (Aadhar Card / PAN Card)",
                                    "Director's Address Proof",
                                    'Building Ownership Proof / Rent Agreement',
                                    'Staff & Faculty Qualification Documents',
                                    'Center Infrastructure Photos (Inner & Outer View)',
                                    'Processing Fee Receipt',
                                    'Copy of Institution PAN Card',
                                    'Other Documents'
                                ];

                                if (empty($docs) || $docs[0] === ''):
                                    echo '<div class="text-muted small">No documents checked</div>';
                                else:
                                    foreach ($docs as $d):
                                        $idx = array_search($d, $docsCheckList);
                                        $uploadLink = '';
                                        if ($idx !== false && !empty($uploadedDocsArr[$idx])) {
                                            $uploadLink = '<a href="../' . htmlspecialchars($uploadedDocsArr[$idx]) . '" target="_blank" class="badge bg-primary text-decoration-none ms-2"><i class="fas fa-external-link-alt me-1"></i>View File</a>';
                                        }
                                ?>
                                    <div class="small fw-bold text-success mb-2 d-flex align-items-center justify-content-between">
                                        <span><i class="fas fa-check-square me-1"></i> <?= htmlspecialchars($d) ?></span>
                                        <?= $uploadLink ?>
                                    </div>
                                <?php 
                                    endforeach;
                                endif; 
                                ?>
                            </div>

                            <table class="table table-sm table-borderless">
                                <tr><td class="text-muted w-40">Declaration Signed:</td><td><strong>Yes, confirmed online</strong></td></tr>
                                <tr><td class="text-muted">Applicant Name:</td><td><?= htmlspecialchars($viewApp['director_name']) ?></td></tr>
                                <tr><td class="text-muted">Submission Date:</td><td><?= htmlspecialchars($viewApp['submitted_at'] ? date('d-M-Y H:i', strtotime($viewApp['submitted_at'])) : '-') ?></td></tr>
                                <tr><td class="text-muted">Payment Txn UTR/DD:</td><td><span class="badge bg-dark fs-6"><?= htmlspecialchars($viewApp['affiliation_fee_transaction_id'] ?: 'N/A') ?></span></td></tr>
                            </table>
                        </div>
                    </div>

                    <!-- SECTION 5: Staff details -->
                    <div class="mt-4">
                        <h6 class="text-primary fw-bold border-bottom pb-2 mb-3"><i class="fas fa-users me-1"></i>SECTION 5: Staff & Faculty Details Table</h6>
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped table-sm align-middle">
                                <thead class="table-dark">
                                    <tr>
                                        <th style="width:60px;" class="text-center">S.No.</th>
                                        <th>Name of Faculty</th>
                                        <th>Qualification</th>
                                        <th>Designation</th>
                                        <th>Experience (in Years)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($facultyArr)): ?>
                                        <tr><td colspan="5" class="text-center text-muted">No staff details filled</td></tr>
                                    <?php else: foreach ($facultyArr as $f): ?>
                                        <tr>
                                            <td class="text-center fw-bold"><?= htmlspecialchars($f['sno']) ?></td>
                                            <td><?= htmlspecialchars($f['name']) ?></td>
                                            <td><?= htmlspecialchars($f['qualification']) ?></td>
                                            <td><?= htmlspecialchars($f['designation']) ?></td>
                                            <td><?= htmlspecialchars($f['experience']) ?></td>
                                        </tr>
                                    <?php endforeach; endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- SECTION 6: Courses details -->
                    <div class="mt-4">
                        <h6 class="text-primary fw-bold border-bottom pb-2 mb-3"><i class="fas fa-graduation-cap me-1"></i>SECTION 6: Courses Applied For Table</h6>
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped table-sm align-middle">
                                <thead class="table-primary">
                                    <tr>
                                        <th style="width:60px;" class="text-center">S.No.</th>
                                        <th>Course Name</th>
                                        <th>Duration</th>
                                        <th>Eligibility</th>
                                        <th>Course Code</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($coursesArr)): ?>
                                        <tr><td colspan="5" class="text-center text-muted">No courses details filled</td></tr>
                                    <?php else: foreach ($coursesArr as $c): ?>
                                        <tr>
                                            <td class="text-center fw-bold"><?= htmlspecialchars($c['sno']) ?></td>
                                            <td><strong><?= htmlspecialchars($c['name']) ?></strong></td>
                                            <td><?= htmlspecialchars($c['duration']) ?></td>
                                            <td><?= htmlspecialchars($c['eligibility']) ?></td>
                                            <td><span class="badge bg-secondary"><?= htmlspecialchars($c['code']) ?></span></td>
                                        </tr>
                                    <?php endforeach; endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- BOARD OFFICE USE ONLY -->
                    <div class="board-office-section shadow-sm">
                        <h5 class="text-danger fw-bold border-bottom pb-2 mb-3"><i class="fas fa-lock me-2"></i>[FOR BOARD OFFICE USE ONLY]</h5>
                        <div class="row">
                            <div class="col-md-4 mb-2">
                                <span class="text-muted d-block small">Application Received By:</span>
                                <strong><?= htmlspecialchars($admin['full_name']) ?></strong>
                            </div>
                            <div class="col-md-4 mb-2">
                                <span class="text-muted d-block small">Verification Status:</span>
                                <span class="badge bg-danger fs-6"><?= htmlspecialchars(strtoupper($viewApp['application_status'])) ?></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <span class="text-muted d-block small">Inspection Date:</span>
                                <strong><?= $viewApp['approved_at'] ? date('d-M-Y', strtotime($viewApp['approved_at'])) : 'Pending Inspection' ?></strong>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-6 mb-2">
                                <span class="text-muted d-block small">Affiliation Number Issued:</span>
                                <span class="badge bg-dark fs-6"><?= ($viewApp['application_status'] === 'approved') ? 'IBVTE'.date('Y').str_pad($viewApp['id'], 4, '0', STR_PAD_LEFT) : 'Not Issued' ?></span>
                            </div>
                            <div class="col-md-6 mb-2 text-end">
                                <span class="text-muted d-block small">Authorized Signature with Seal:</span>
                                <strong class="text-success"><i class="fas fa-check-circle me-1"></i> Authorized by IBVTE Board</strong>
                            </div>
                        </div>
                    </div>

                    <?php if ($viewApp['review_remarks']): ?>
                    <div class="alert alert-warning mt-4 mb-0"><strong>Internal Remarks:</strong> <?= htmlspecialchars($viewApp['review_remarks']) ?></div>
                    <?php endif; ?>
                    
                    <?php if (in_array($viewApp['application_status'], ['submitted','under_review'])): ?>
                    <div class="d-flex gap-2 mt-4">
                        <a href="?action=approve&id=<?= $viewApp['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-success btn-lg"
                           onclick="return confirm('Approve and create college account?')">
                            <i class="fas fa-check me-1"></i>Approve Application
                        </a>
                        <a href="?action=reject&id=<?= $viewApp['id'] ?>&csrf_token=<?= Auth()->generateCSRFToken() ?>" class="btn btn-danger btn-lg"
                           onclick="return confirm('Reject this application?')">
                            <i class="fas fa-times me-1"></i>Reject
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

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

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content" style="border-radius:15px; overflow:hidden;">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                <div class="modal-header card-header-purple text-white">
                    <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Complete Affiliation Application</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body px-4 py-3">
                    <input type="hidden" name="edit_id" id="edit_id">
                    <input type="hidden" name="faculty_details" id="ei_faculty_details">
                    <input type="hidden" name="courses_applied_details" id="ei_courses_applied_details">

                    <!-- Tabbed Layout for Sleek Form Navigation -->
                    <ul class="nav nav-tabs mb-4" id="editAppTabs" role="tablist">
                        <li class="nav-item">
                            <button class="nav-link active fw-bold" id="tab-basic-tab" data-bs-toggle="tab" data-bs-target="#tab-basic" type="button" role="tab"><i class="fas fa-id-card me-1"></i>Basic & Director</button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link fw-bold" id="tab-infra-tab" data-bs-toggle="tab" data-bs-target="#tab-infra" type="button" role="tab"><i class="fas fa-building me-1"></i>Infra & Facilities</button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link fw-bold" id="tab-faculty-tab" data-bs-toggle="tab" data-bs-target="#tab-faculty" type="button" role="tab"><i class="fas fa-users-cog me-1"></i>Faculty & Courses</button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link fw-bold" id="tab-docs-tab" data-bs-toggle="tab" data-bs-target="#tab-docs" type="button" role="tab"><i class="fas fa-paperclip me-1"></i>Photos & Docs</button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link fw-bold text-danger" id="tab-remarks-tab" data-bs-toggle="tab" data-bs-target="#tab-remarks" type="button" role="tab"><i class="fas fa-lock me-1"></i>Review Remarks</button>
                        </li>
                    </ul>

                    <div class="tab-content" id="editAppTabsContent">
                        
                        <!-- TAB 1: BASIC & DIRECTOR -->
                        <div class="tab-pane fade show active" id="tab-basic" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="fw-bold small text-secondary">Institution / Center Name *</label>
                                    <input type="text" name="institution_name" id="ei_name" class="form-control form-control-sm" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold small text-secondary">Proposed Center Name</label>
                                    <input type="text" name="proposed_center_name" id="ei_proposed" class="form-control form-control-sm">
                                </div>
                                
                                <div class="col-md-6">
                                    <label class="fw-bold small text-secondary">Director / Principal Name *</label>
                                    <input type="text" name="director_name" id="ei_dir" class="form-control form-control-sm" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold small text-secondary">Father's / Guardian Name</label>
                                    <input type="text" name="father_guardian_name" id="ei_father" class="form-control form-control-sm">
                                </div>

                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">Mobile No *</label>
                                    <input type="text" name="director_mobile" id="ei_mob" class="form-control form-control-sm" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">WhatsApp No</label>
                                    <input type="text" name="whatsapp_no" id="ei_whatsapp" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">Email ID *</label>
                                    <input type="email" name="director_email" id="ei_email" class="form-control form-control-sm" required>
                                </div>

                                <div class="col-md-6">
                                    <label class="fw-bold small text-secondary">Registered Address</label>
                                    <textarea name="registered_address" id="ei_reg_addr" class="form-control form-control-sm" rows="2"></textarea>
                                </div>
                                <div class="col-md-6">
                                    <label class="fw-bold small text-secondary">Communication Address</label>
                                    <textarea name="communication_address" id="ei_comm_addr" class="form-control form-control-sm" rows="2"></textarea>
                                </div>

                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">City</label>
                                    <input type="text" name="city" id="ei_city" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">District</label>
                                    <input type="text" name="district" id="ei_district" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">State</label>
                                    <input type="text" name="state" id="ei_state" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">PIN Code</label>
                                    <input type="text" name="pincode" id="ei_pin" class="form-control form-control-sm">
                                </div>

                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">Registration Number</label>
                                    <input type="text" name="registration_number" id="ei_reg_no" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">Registration Date</label>
                                    <input type="date" name="registration_date" id="ei_reg_date" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">PAN / GST No</label>
                                    <input type="text" name="pan_gst_no" id="ei_pan" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">Identity Proof No</label>
                                    <input type="text" name="identity_proof_no" id="ei_id_proof" class="form-control form-control-sm">
                                </div>

                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">Bank Name</label>
                                    <input type="text" name="bank_name" id="ei_bank_name" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">Bank Account No</label>
                                    <input type="text" name="bank_account_no" id="ei_bank_acc" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">Bank IFSC Code</label>
                                    <input type="text" name="bank_ifsc" id="ei_bank_ifsc" class="form-control form-control-sm">
                                </div>
                            </div>
                        </div>

                        <!-- TAB 2: INFRASTRUCTURE & FACILITIES -->
                        <div class="tab-pane fade" id="tab-infra" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary mb-2 d-block">Applied For</label>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="checkbox" name="applied_for_opts[]" value="Technical" id="apply_technical">
                                        <label class="form-check-label text-dark" for="apply_technical">Technical</label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="checkbox" name="applied_for_opts[]" value="Skill Development" id="apply_skill">
                                        <label class="form-check-label text-dark" for="apply_skill">Skill Development</label>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <label class="fw-bold small text-secondary">Building Type</label>
                                    <select name="building_type" id="ei_building_type" class="form-select form-select-sm">
                                        <option value="">-- Select --</option>
                                        <option value="owned">Owned</option>
                                        <option value="rented">Rented</option>
                                        <option value="leased">Leased</option>
                                    </select>
                                </div>
                                <div class="col-md-5">
                                    <label class="fw-bold small text-secondary">Total Area (sq. ft.)</label>
                                    <input type="text" name="total_area" id="ei_total_area" class="form-control form-control-sm" placeholder="e.g. 2500 sq ft">
                                </div>

                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">Number of Classrooms</label>
                                    <input type="number" name="number_of_classrooms" id="ei_classrooms" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">Total Staff Members</label>
                                    <input type="number" name="total_staff" id="ei_total_staff" class="form-control form-control-sm">
                                </div>
                                <div class="col-md-4">
                                    <label class="fw-bold small text-secondary">Total Computers Available</label>
                                    <input type="number" name="total_computers" id="ei_total_computers" class="form-control form-control-sm">
                                </div>

                                <div class="col-12"><hr class="my-2"></div>
                                <div class="col-12">
                                    <h6 class="fw-bold text-primary mb-3"><i class="fas fa-check-square me-1"></i>Center Facilities Checklist</h6>
                                    <div class="row g-2">
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="library_facility" id="ei_library_facility">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_library_facility">Library Facility</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="computer_lab" id="ei_computer_lab">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_computer_lab">Computer Lab</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="internet_facility" id="ei_internet_facility">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_internet_facility">Internet Facility</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="practical_lab_facility" id="ei_practical_lab">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_practical_lab">Practical Lab Facility</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="computer_systems_available" id="ei_computer_systems">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_computer_systems">Computer Systems Installed</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="power_backup_facility" id="ei_power_backup">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_power_backup">Power Backup Facility</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="clean_drinking_water" id="ei_drinking_water">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_drinking_water">Clean Drinking Water</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="furniture_available" id="ei_furniture">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_furniture">Furniture Available</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="washroom_facility" id="ei_washroom">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_washroom">Washroom Facility</label>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch bg-light p-2 rounded border">
                                                <input class="form-check-input ms-0 me-2" type="checkbox" name="safety_fire_extinguisher" id="ei_safety_fire">
                                                <label class="form-check-label text-dark fw-bold small" for="ei_safety_fire">Safety Fire Extinguisher</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- TAB 3: FACULTY & COURSES -->
                        <div class="tab-pane fade" id="tab-faculty" role="tabpanel">
                            <div class="row">
                                <!-- SECTION 5: STAFF/FACULTY DETAILS -->
                                <div class="col-12 mb-4">
                                    <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-3">
                                        <h6 class="fw-bold text-primary mb-0"><i class="fas fa-users me-1"></i>SECTION 5: STAFF / FACULTY DETAILS</h6>
                                        <button type="button" class="btn btn-sm btn-purple px-3" onclick="addFacultyRow()"><i class="fas fa-plus me-1"></i>Add Staff Member</button>
                                    </div>
                                    <div class="table-responsive bg-light p-2 rounded border" style="max-height: 250px; overflow-y: auto;">
                                        <table class="table table-sm table-hover mb-0 align-middle">
                                            <thead class="table-secondary">
                                                <tr>
                                                    <th style="width: 50px;">S.No</th>
                                                    <th>Name *</th>
                                                    <th>Qualification</th>
                                                    <th>Designation</th>
                                                    <th>Experience</th>
                                                    <th class="text-center" style="width: 60px;">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody id="faculty_tbody">
                                                <!-- Dynamic Rows -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>

                                <!-- SECTION 6: COURSES APPLIED FOR -->
                                <div class="col-12">
                                    <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-3">
                                        <h6 class="fw-bold text-primary mb-0"><i class="fas fa-graduation-cap me-1"></i>SECTION 6: COURSES APPLIED FOR</h6>
                                        <button type="button" class="btn btn-sm btn-purple px-3" onclick="addCourseRow()"><i class="fas fa-plus me-1"></i>Add Course Slot</button>
                                    </div>
                                    <div class="table-responsive bg-light p-2 rounded border" style="max-height: 250px; overflow-y: auto;">
                                        <table class="table table-sm table-hover mb-0 align-middle">
                                            <thead class="table-secondary">
                                                <tr>
                                                    <th style="width: 50px;">S.No</th>
                                                    <th>Course Name *</th>
                                                    <th>Duration</th>
                                                    <th>Eligibility</th>
                                                    <th>Code</th>
                                                    <th class="text-center" style="width: 60px;">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody id="courses_tbody">
                                                <!-- Dynamic Rows -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- TAB 4: PHOTOS & DOCS -->
                        <div class="tab-pane fade" id="tab-docs" role="tabpanel">
                            <div class="row g-3">
                                <!-- Director Photo Upload Box -->
                                <div class="col-12 mb-3">
                                    <div class="p-3 rounded border bg-light">
                                        <h6 class="fw-bold text-primary mb-2"><i class="fas fa-user-circle me-1"></i>Director's Passport Size Photo</h6>
                                        <div id="director_photo_container" class="mb-2"></div>
                                        <input type="file" name="director_photo_file" class="form-control form-control-sm" accept="image/*">
                                        <small class="text-muted">Upload a new photo to update/replace the current one (JPG, JPEG, PNG only).</small>
                                    </div>
                                </div>

                                <!-- Document Slots Grid -->
                                <div class="col-12">
                                    <h6 class="fw-bold text-primary border-bottom pb-2 mb-3"><i class="fas fa-file-upload me-1"></i>SECTION 7: Documents Attached & Upload Slots</h6>
                                    <div class="row g-3" id="documents_list_container">
                                        <!-- Dynamic Docs Grid -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- TAB 5: REVIEW REMARKS -->
                        <div class="tab-pane fade" id="tab-remarks" role="tabpanel">
                            <div class="row g-3">
                                <div class="col-12">
                                    <label class="fw-bold text-danger mb-2"><i class="fas fa-lock me-1"></i>Internal Admin Review Remarks & Verification Feedback</label>
                                    <textarea name="review_remarks" id="ei_remarks" class="form-control" rows="6" placeholder="Enter inspection details, missing documents feedback, or internal approval status notes..."></textarea>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
                <div class="modal-footer px-4 py-3">
                    <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="save_edit" class="btn btn-purple px-4 fw-bold"><i class="fas fa-save me-1"></i>Save Complete Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Credentials Modal (auto-show after approve) -->
<?php if ($credModal): ?>
<div class="modal fade" id="newCredModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">🎉 College Account Created!</h5>
            </div>
            <div class="modal-body text-center py-4">
                <h6 class="mb-3"><?= htmlspecialchars($credModal['inst']) ?></h6>
                <table class="table table-bordered">
                    <tr><td class="text-muted">Institution Code</td><td><strong><?= htmlspecialchars($credModal['code']) ?></strong></td></tr>
                    <tr><td class="text-muted">Username</td><td><strong class="text-primary"><?= htmlspecialchars($credModal['username']) ?></strong></td></tr>
                    <tr><td class="text-muted">Password</td><td><strong class="text-danger"><?= htmlspecialchars($credModal['password']) ?></strong></td></tr>
                </table>
                <div class="alert alert-warning text-start small mb-0">⚠️ Save these now — password won't be shown again in plain text.</div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-success" data-bs-dismiss="modal"><i class="fas fa-check me-1"></i>I've Saved the Credentials</button>
            </div>
        </div>
    </div>
</div>
<script>window.addEventListener('DOMContentLoaded',function(){new bootstrap.Modal(document.getElementById('newCredModal')).show();});</script>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let currentFaculty = [];
let currentCourses = [];

const docsCheck = [
    'Registration Certificate of Trust/Society/Firm',
    "Director's ID Proof (Aadhar Card / PAN Card)",
    "Director's Address Proof",
    'Building Ownership Proof / Rent Agreement',
    'Staff & Faculty Qualification Documents',
    'Center Infrastructure Photos (Inner & Outer View)',
    'Processing Fee Receipt',
    'Copy of Institution PAN Card',
    'Other Documents'
];

function renderFacultyTable() {
    const tbody = document.getElementById('faculty_tbody');
    tbody.innerHTML = '';
    if (currentFaculty.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted small py-3">No staff details. Click "Add Staff Member" to add rows.</td></tr>';
        updateFacultyHiddenInput();
        return;
    }
    currentFaculty.forEach((f, idx) => {
        tbody.innerHTML += `
            <tr>
                <td>${idx + 1}</td>
                <td><input type="text" class="form-control form-control-sm fac-input" data-idx="${idx}" data-field="name" value="${f.name || ''}" placeholder="Name" required></td>
                <td><input type="text" class="form-control form-control-sm fac-input" data-idx="${idx}" data-field="qualification" value="${f.qualification || ''}" placeholder="Qualification"></td>
                <td><input type="text" class="form-control form-control-sm fac-input" data-idx="${idx}" data-field="designation" value="${f.designation || ''}" placeholder="Designation"></td>
                <td><input type="text" class="form-control form-control-sm fac-input" data-idx="${idx}" data-field="experience" value="${f.experience || ''}" placeholder="Experience"></td>
                <td class="text-center">
                    <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2" onclick="removeFacultyRow(${idx})"><i class="fas fa-trash-alt"></i></button>
                </td>
            </tr>
        `;
    });
    updateFacultyHiddenInput();
}

function addFacultyRow() {
    currentFaculty.push({ sno: currentFaculty.length + 1, name: '', qualification: '', designation: '', experience: '' });
    renderFacultyTable();
}

function removeFacultyRow(idx) {
    currentFaculty.splice(idx, 1);
    currentFaculty.forEach((f, i) => { f.sno = i + 1; });
    renderFacultyTable();
}

function updateFacultyHiddenInput() {
    document.getElementById('ei_faculty_details').value = JSON.stringify(currentFaculty);
}

function renderCoursesTable() {
    const tbody = document.getElementById('courses_tbody');
    tbody.innerHTML = '';
    if (currentCourses.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted small py-3">No courses applied. Click "Add Course Slot" to add rows.</td></tr>';
        updateCoursesHiddenInput();
        return;
    }
    currentCourses.forEach((c, idx) => {
        tbody.innerHTML += `
            <tr>
                <td>${idx + 1}</td>
                <td><input type="text" class="form-control form-control-sm course-input" data-idx="${idx}" data-field="name" value="${c.name || ''}" placeholder="Course Name" required></td>
                <td><input type="text" class="form-control form-control-sm course-input" data-idx="${idx}" data-field="duration" value="${c.duration || ''}" placeholder="Duration"></td>
                <td><input type="text" class="form-control form-control-sm course-input" data-idx="${idx}" data-field="eligibility" value="${c.eligibility || ''}" placeholder="Eligibility"></td>
                <td><input type="text" class="form-control form-control-sm course-input" data-idx="${idx}" data-field="code" value="${c.code || ''}" placeholder="Code"></td>
                <td class="text-center">
                    <button type="button" class="btn btn-sm btn-outline-danger py-0 px-2" onclick="removeCourseRow(${idx})"><i class="fas fa-trash-alt"></i></button>
                </td>
            </tr>
        `;
    });
    updateCoursesHiddenInput();
}

function addCourseRow() {
    currentCourses.push({ sno: currentCourses.length + 1, name: '', duration: '', eligibility: '', code: '' });
    renderCoursesTable();
}

function removeCourseRow(idx) {
    currentCourses.splice(idx, 1);
    currentCourses.forEach((c, i) => { c.sno = i + 1; });
    renderCoursesTable();
}

function updateCoursesHiddenInput() {
    document.getElementById('ei_courses_applied_details').value = JSON.stringify(currentCourses);
}

// Live capture inputs
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('fac-input')) {
        const idx = parseInt(e.target.getAttribute('data-idx'));
        const field = e.target.getAttribute('data-field');
        currentFaculty[idx][field] = e.target.value;
        updateFacultyHiddenInput();
    }
    if (e.target.classList.contains('course-input')) {
        const idx = parseInt(e.target.getAttribute('data-idx'));
        const field = e.target.getAttribute('data-field');
        currentCourses[idx][field] = e.target.value;
        updateCoursesHiddenInput();
    }
});

function renderDocumentsSection(uploadedDocsObj) {
    const container = document.getElementById('documents_list_container');
    container.innerHTML = '';
    docsCheck.forEach((dname, idx) => {
        const filePath = uploadedDocsObj[idx];
        let fileDisplay = '';
        if (filePath) {
            fileDisplay = `
                <div class="d-flex align-items-center gap-2 mb-1">
                    <a href="../${filePath}" target="_blank" class="btn btn-xs btn-outline-success py-0 px-2 small" style="font-size: 0.75rem;"><i class="fas fa-eye me-1"></i>View Current File</a>
                    <div class="form-check form-check-inline mb-0 ms-2">
                        <input class="form-check-input" type="checkbox" name="delete_doc_${idx}" value="1" id="delDoc_${idx}">
                        <label class="form-check-label text-danger fw-bold small" for="delDoc_${idx}" style="font-size: 0.75rem; cursor: pointer;">Remove</label>
                    </div>
                </div>
            `;
        } else {
            fileDisplay = `<span class="badge bg-secondary mb-1" style="font-size: 0.7rem;"><i class="fas fa-times me-1"></i>No File Uploaded</span>`;
        }
        
        container.innerHTML += `
            <div class="col-md-6">
                <div class="p-2 rounded bg-light border">
                    <div class="fw-bold small text-secondary mb-1" style="font-size: 0.8rem;">${idx + 1}. ${dname}</div>
                    ${fileDisplay}
                    <div class="mt-1">
                        <input type="file" name="doc_file_${idx}" class="form-control form-control-sm" accept=".pdf,image/*">
                    </div>
                </div>
            </div>
        `;
    });
}

function openEdit(a) {
    // Reset active tab to basic
    const basicTabTrigger = document.querySelector('#tab-basic-tab');
    if (basicTabTrigger) {
        new bootstrap.Tab(basicTabTrigger).show();
    }

    document.getElementById('edit_id').value    = a.id;
    document.getElementById('ei_name').value    = a.institution_name;
    document.getElementById('ei_proposed').value = a.proposed_center_name || '';
    document.getElementById('ei_dir').value     = a.director_name;
    document.getElementById('ei_father').value  = a.father_guardian_name || '';
    document.getElementById('ei_mob').value     = a.director_mobile;
    document.getElementById('ei_whatsapp').value = a.whatsapp_no || '';
    document.getElementById('ei_email').value   = a.director_email;
    document.getElementById('ei_reg_addr').value = a.registered_address || '';
    document.getElementById('ei_comm_addr').value = a.communication_address || a.address || '';
    document.getElementById('ei_city').value    = a.city    || '';
    document.getElementById('ei_district').value = a.district || '';
    document.getElementById('ei_state').value   = a.state   || '';
    document.getElementById('ei_pin').value     = a.pincode || '';
    document.getElementById('ei_reg_no').value  = a.registration_number || '';
    document.getElementById('ei_reg_date').value = a.registration_date || '';
    document.getElementById('ei_pan').value     = a.pan_gst_no || '';
    document.getElementById('ei_id_proof').value = a.identity_proof_no || '';
    document.getElementById('ei_bank_name').value = a.bank_name || '';
    document.getElementById('ei_bank_acc').value = a.bank_account_no || '';
    document.getElementById('ei_bank_ifsc').value = a.bank_ifsc || '';
    document.getElementById('ei_remarks').value = a.review_remarks || '';

    // Tab 2 details
    const appliedFor = a.applied_for || '';
    const appliedForArr = appliedFor.split(',').map(s => s.trim());
    document.getElementById('apply_technical').checked = appliedForArr.includes('Technical');
    document.getElementById('apply_skill').checked = appliedForArr.includes('Skill Development');

    document.getElementById('ei_building_type').value = a.building_type || '';
    document.getElementById('ei_total_area').value = a.total_area || '';
    document.getElementById('ei_classrooms').value = a.number_of_classrooms || 0;
    document.getElementById('ei_total_staff').value = a.total_staff || 0;
    document.getElementById('ei_total_computers').value = a.total_computers || 0;

    // Checklist toggles
    document.getElementById('ei_library_facility').checked = parseInt(a.library_facility) === 1;
    document.getElementById('ei_computer_lab').checked = parseInt(a.computer_lab) === 1;
    document.getElementById('ei_internet_facility').checked = parseInt(a.internet_facility) === 1;
    document.getElementById('ei_practical_lab').checked = parseInt(a.practical_lab_facility) === 1;
    document.getElementById('ei_computer_systems').checked = parseInt(a.computer_systems_available) === 1;
    document.getElementById('ei_power_backup').checked = parseInt(a.power_backup_facility) === 1;
    document.getElementById('ei_drinking_water').checked = parseInt(a.clean_drinking_water) === 1;
    document.getElementById('ei_furniture').checked = parseInt(a.furniture_available) === 1;
    document.getElementById('ei_washroom').checked = parseInt(a.washroom_facility) === 1;
    document.getElementById('ei_safety_fire').checked = parseInt(a.safety_fire_extinguisher) === 1;

    // Dynamic Lists (Staff & Courses)
    try {
        currentFaculty = JSON.parse(a.faculty_details || '[]');
        if (!Array.isArray(currentFaculty)) currentFaculty = [];
    } catch(e) {
        currentFaculty = [];
    }
    renderFacultyTable();

    try {
        currentCourses = JSON.parse(a.courses_applied_details || '[]');
        if (!Array.isArray(currentCourses)) currentCourses = [];
    } catch(e) {
        currentCourses = [];
    }
    renderCoursesTable();

    // Director Photo display
    let photoHtml = '';
    if (a.director_photo) {
        photoHtml = `
            <div class="d-flex align-items-center gap-2 mb-1">
                <img src="../${a.director_photo}" style="height: 50px; border-radius: 5px; border: 1px solid #ccc;">
                <a href="../${a.director_photo}" target="_blank" class="btn btn-xs btn-outline-success py-0 px-2 small" style="font-size: 0.75rem;"><i class="fas fa-eye me-1"></i>View Current Photo</a>
                <div class="form-check form-check-inline mb-0 ms-2">
                    <input class="form-check-input" type="checkbox" name="delete_director_photo" value="1" id="delPhoto">
                    <label class="form-check-label text-danger fw-bold small" for="delPhoto" style="font-size: 0.75rem; cursor: pointer;">Remove Photo</label>
                </div>
            </div>
        `;
    } else {
        photoHtml = `<span class="badge bg-secondary mb-1" style="font-size: 0.7rem;"><i class="fas fa-times me-1"></i>No Photo Uploaded</span>`;
    }
    document.getElementById('director_photo_container').innerHTML = photoHtml;

    // Document slots grid rendering
    let uploadedDocs = {};
    try {
        uploadedDocs = JSON.parse(a.uploaded_documents || '{}');
        if (typeof uploadedDocs !== 'object' || uploadedDocs === null) uploadedDocs = {};
    } catch(e) {
        uploadedDocs = {};
    }
    renderDocumentsSection(uploadedDocs);

    new bootstrap.Modal(document.getElementById('editModal')).show();
}
</script>
</body>
</html>