<?php
/**
 * IBVTE - Online Affiliation Application with I Agree Workflow
 */

require_once __DIR__ . '/../config.php';

// Start session only if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$step = intval($_GET['step'] ?? 1);
$flash = getFlashMessage();

// Initialize DB
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
$db = DB();

// Application steps
$totalSteps = 5;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection for all POST steps
    if ($step > 0 && !Auth()->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        redirectWithMessage("apply.php?step=$step", "Security session expired. Please try again.", "danger");
    }

    // Step 1: Agreement
    if ($step === 1 && isset($_POST['i_agree'])) {
        $_SESSION['affiliation_agreed'] = true;
        header('Location: apply.php?step=2');
        exit;
    }

    // Step 2: Save institution details to session & upload Director's Photo
    if ($step === 2) {
        $photoPath = '';
        if (isset($_FILES['director_photo']) && $_FILES['director_photo']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../uploads/affiliation/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            $ext = pathinfo($_FILES['director_photo']['name'], PATHINFO_EXTENSION);
            $fileName = 'photo_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
            if (move_uploaded_file($_FILES['director_photo']['tmp_name'], $uploadDir . $fileName)) {
                $photoPath = 'uploads/affiliation/' . $fileName;
            }
        }

        $_SESSION['aff_step2'] = [
            'institution_name'     => trim($_POST['institution_name'] ?? ''),
            'director_name'        => trim($_POST['director_name'] ?? ''),
            'father_guardian_name' => trim($_POST['father_guardian_name'] ?? ''),
            'registered_address'   => trim($_POST['registered_address'] ?? ''),
            'communication_address'=> trim($_POST['communication_address'] ?? ''),
            'pincode'              => trim($_POST['pincode'] ?? ''),
            'director_mobile'      => trim($_POST['director_mobile'] ?? ''),
            'whatsapp_no'          => trim($_POST['whatsapp_no'] ?? ''),
            'director_email'       => trim($_POST['director_email'] ?? ''),
            'director_photo'       => $photoPath ?: ($_SESSION['aff_step2']['director_photo'] ?? ''),
            'website'              => trim($_POST['website'] ?? ''),
            
            // Section 2
            'institution_type'     => implode(', ', $_POST['institution_type_opts'] ?? []),
            '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'] ?? ''),
            'established_year'     => trim($_POST['established_year'] ?? ''),
            'total_staff'          => intval($_POST['total_staff'] ?? 0),
            'building_type'        => trim($_POST['building_type'] ?? '')
        ];
        header('Location: apply.php?step=3');
        exit;
    }

    // Step 3: Save selected courses & infrastructure to session
    if ($step === 3) {
        // Process Dynamic Faculty Table
        $faculty = [];
        $fnames = $_POST['faculty_name'] ?? [];
        $fquals = $_POST['faculty_qualification'] ?? [];
        $fdesigs = $_POST['faculty_designation'] ?? [];
        $fexps = $_POST['faculty_experience'] ?? [];
        for ($i = 0; $i < count($fnames); $i++) {
            if (!empty(trim($fnames[$i] ?? ''))) {
                $faculty[] = [
                    'sno' => $i + 1,
                    'name' => trim($fnames[$i]),
                    'qualification' => trim($fquals[$i] ?? ''),
                    'designation' => trim($fdesigs[$i] ?? ''),
                    'experience' => trim($fexps[$i] ?? '')
                ];
            }
        }

        // Process Dynamic Applied Courses Table
        $courses = [];
        $cnames = $_POST['applied_course_name'] ?? [];
        $cdurs = $_POST['applied_course_duration'] ?? [];
        $celigs = $_POST['applied_course_eligibility'] ?? [];
        $ccodes = $_POST['applied_course_code'] ?? [];
        for ($i = 0; $i < count($cnames); $i++) {
            if (!empty(trim($cnames[$i] ?? ''))) {
                $courses[] = [
                    'sno' => $i + 1,
                    'name' => trim($cnames[$i]),
                    'duration' => trim($cdurs[$i] ?? ''),
                    'eligibility' => trim($celigs[$i] ?? ''),
                    'code' => trim($ccodes[$i] ?? '')
                ];
            }
        }

        $_SESSION['aff_step3'] = [
            'applied_for'                => $_POST['applied_for_opts'] ?? [],
            'proposed_center_name'       => trim($_POST['proposed_center_name'] ?? ''),
            'classrooms'                 => intval($_POST['classrooms'] ?? 0),
            'total_area'                 => trim($_POST['total_area'] ?? ''),
            'practical_lab_facility'     => intval($_POST['practical_lab_facility'] ?? 0),
            'computer_systems_available' => intval($_POST['computer_systems_available'] ?? 0),
            'total_computers'            => intval($_POST['total_computers'] ?? 0),
            'internet_facility'          => intval($_POST['internet_facility'] ?? 0),
            'power_backup_facility'      => intval($_POST['power_backup_facility'] ?? 0),
            'clean_drinking_water'       => intval($_POST['clean_drinking_water'] ?? 0),
            'furniture_available'        => intval($_POST['furniture_available'] ?? 0),
            'washroom_facility'          => intval($_POST['washroom_facility'] ?? 0),
            'safety_fire_extinguisher'   => intval($_POST['safety_fire_extinguisher'] ?? 0),
            'faculty_details'            => $faculty,
            'courses_details'            => $courses
        ];
        header('Location: apply.php?step=4');
        exit;
    }

    // Step 4: Documents Upload & Declaration
    if ($step === 4) {
        $uploadedDocs = [];
        $uploadDir = __DIR__ . '/../uploads/affiliation/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        // Loop through all dynamic file uploads
        if (!empty($_FILES)) {
            foreach ($_FILES as $inputName => $fileInfo) {
                if (strpos($inputName, 'doc_file_') === 0 && $fileInfo['error'] === UPLOAD_ERR_OK) {
                    $idx = intval(str_replace('doc_file_', '', $inputName));
                    $ext = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
                    $fileName = 'doc_' . $idx . '_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
                    if (move_uploaded_file($fileInfo['tmp_name'], $uploadDir . $fileName)) {
                        $uploadedDocs[$idx] = 'uploads/affiliation/' . $fileName;
                    }
                }
            }
        }

        $_SESSION['aff_step4'] = [
            'documents_attached' => $_POST['documents_attached_opts'] ?? [],
            'uploaded_documents' => $uploadedDocs,
            'applicant_name'     => trim($_POST['applicant_name'] ?? ''),
            'declaration_date'   => trim($_POST['declaration_date'] ?? ''),
            'declaration_place'  => trim($_POST['declaration_place'] ?? '')
        ];
        header('Location: apply.php?step=5');
        exit;
    }

    // Step 5: Final Submission - Save everything to DB
    if ($step === 5) {
        $appNumber = 'AFF' . date('Ymd') . strtoupper(substr(uniqid(), -6));
        $s2        = $_SESSION['aff_step2'] ?? [];
        $s3        = $_SESSION['aff_step3'] ?? [];
        $s4        = $_SESSION['aff_step4'] ?? [];

        try {
            $insertId = $db->insert('affiliation_applications', [
                'application_number'         => $appNumber,
                'institution_name'           => $s2['institution_name'] ?? '',
                'institution_type'           => $s2['institution_type'] ?? '',
                'established_year'           => ($s2['established_year'] ?? '') ?: null,
                'registration_number'        => $s2['registration_number'] ?? '',
                'total_staff'                => $s2['total_staff'] ?? 0,
                'director_name'              => $s2['director_name'] ?? '',
                'director_mobile'            => $s2['director_mobile'] ?? '',
                'director_email'             => $s2['director_email'] ?? '',
                'director_photo'             => $s2['director_photo'] ?? '',
                'landline'                   => $s2['landline'] ?? '',
                'address'                    => $s2['communication_address'] ?: ($s2['registered_address'] ?? ''),
                'city'                       => $s2['city'] ?? '',
                'district'                   => $s2['district'] ?? '',
                'state'                      => $s2['state'] ?? '',
                'pincode'                    => $s2['pincode'] ?? '',
                'building_type'              => $s2['building_type'] ?: null,
                'total_area'                 => $s2['total_area'] ?? '',
                'number_of_classrooms'       => $s3['classrooms'] ?? 0,
                'library_facility'           => 1, // default
                'computer_lab'               => intval($s3['computer_systems_available'] ?? 0),
                'internet_facility'          => intval($s3['internet_facility'] ?? 0),
                'courses_applied'            => json_encode(array_column($s3['courses_details'] ?? [], 'name'), JSON_UNESCAPED_UNICODE),
                'affiliation_fee_transaction_id' => trim($_POST['txn_reference'] ?? ''),
                'application_status'         => 'submitted',
                'submitted_at'               => date('Y-m-d H:i:s'),
                'ip_address'                 => $_SERVER['REMOTE_ADDR'] ?? '',
                
                // New Fields
                'father_guardian_name'       => $s2['father_guardian_name'] ?? '',
                'registered_address'         => $s2['registered_address'] ?? '',
                'communication_address'      => $s2['communication_address'] ?? '',
                'whatsapp_no'                => $s2['whatsapp_no'] ?? '',
                'registration_date'          => $s2['registration_date'] ?? '',
                'pan_gst_no'                 => $s2['pan_gst_no'] ?? '',
                'identity_proof_no'          => $s2['identity_proof_no'] ?? '',
                'bank_name'                  => $s2['bank_name'] ?? '',
                'bank_account_no'            => $s2['bank_account_no'] ?? '',
                'bank_ifsc'                  => $s2['bank_ifsc'] ?? '',
                'applied_for'                => implode(', ', $s3['applied_for'] ?? []),
                'proposed_center_name'       => $s3['proposed_center_name'] ?? '',
                'practical_lab_facility'     => intval($s3['practical_lab_facility'] ?? 0),
                'computer_systems_available' => intval($s3['computer_systems_available'] ?? 0),
                'total_computers'            => intval($s3['total_computers'] ?? 0),
                'power_backup_facility'      => intval($s3['power_backup_facility'] ?? 0),
                'clean_drinking_water'       => intval($s3['clean_drinking_water'] ?? 0),
                'furniture_available'        => intval($s3['furniture_available'] ?? 0),
                'washroom_facility'          => intval($s3['washroom_facility'] ?? 0),
                'safety_fire_extinguisher'   => intval($s3['safety_fire_extinguisher'] ?? 0),
                'faculty_details'            => json_encode($s3['faculty_details'] ?? [], JSON_UNESCAPED_UNICODE),
                'courses_applied_details'    => json_encode($s3['courses_details'] ?? [], JSON_UNESCAPED_UNICODE),
                'documents_attached'         => implode(', ', $s4['documents_attached'] ?? []),
                'uploaded_documents'         => json_encode($s4['uploaded_documents'] ?? [], JSON_UNESCAPED_SLASHES)
            ]);
            if (!$insertId) {
                throw new Exception("DB Error: " . $db->lastError);
            }
            // Clear session data
            unset($_SESSION['aff_step2'], $_SESSION['aff_step3'], $_SESSION['aff_step4'], $_SESSION['affiliation_agreed']);
            $_SESSION['aff_ref_id'] = $appNumber;
        } catch (Exception $e) { die("DB_ERROR: " . $e->getMessage());
            // fallback - still redirect with generated number
            $appNumber = 'AFF' . time();
        }
        redirectWithMessage('apply.php?step=6', 'Application submitted! Ref: ' . $appNumber, 'success');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Affiliation Application - <?= 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-color: #3b0b7c;
            --secondary-color: #6c4ab6;
            --accent-color: #ffd700;
        }
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', sans-serif;
        }
        .application-container {
            max-width: 1100px;
            margin: 30px auto;
        }
        .step-wizard {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            position: relative;
        }
        .step-wizard::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 4px;
            background: rgba(255,255,255,0.3);
            z-index: 0;
        }
        .step-item {
            position: relative;
            z-index: 1;
            text-align: center;
            flex: 1;
        }
        .step-number {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: white;
            color: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin: 0 auto 10px;
            border: 3px solid rgba(255,255,255,0.5);
            transition: all 0.3s;
        }
        .step-item.active .step-number {
            background: var(--accent-color);
            color: #333;
            border-color: var(--accent-color);
            transform: scale(1.1);
        }
        .step-item.completed .step-number {
            background: #28a745;
            color: white;
            border-color: #28a745;
        }
        .step-label {
            color: white;
            font-size: 0.85rem;
            font-weight: 500;
        }
        .step-content {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .step-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 30px;
            text-align: center;
        }
        .step-body {
            padding: 40px;
        }
        .agreement-box {
            background: #f8f9fa;
            border: 2px solid #e0e0e0;
            border-radius: 15px;
            padding: 30px;
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        .agreement-box h5 {
            color: var(--primary-color);
            margin-bottom: 15px;
        }
        .checkbox-wrapper {
            background: #fff8e1;
            border: 2px solid var(--accent-color);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .form-section {
            margin-bottom: 35px;
            background: #fdfdfd;
            padding: 20px;
            border-radius: 12px;
            border-left: 5px solid var(--primary-color);
            box-shadow: 0 2px 10px rgba(0,0,0,0.02);
        }
        .form-section h5 {
            color: var(--primary-color);
            border-bottom: 2px solid #eee;
            padding-bottom: 12px;
            margin-bottom: 20px;
            font-weight: bold;
        }
        .btn-primary-custom {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            border: none;
            border-radius: 10px;
            padding: 12px 30px;
            font-weight: 600;
            color: white !important;
        }
        .btn-primary-custom:hover {
            opacity: 0.9;
        }
        .photo-upload-placeholder {
            width: 140px;
            height: 170px;
            border: 2px dashed #ccc;
            background: #fafafa;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
            border-radius: 8px;
            font-size: 0.8rem;
            color: #666;
            margin: 0 auto;
            overflow: hidden;
        }
        .data-table input {
            border-radius: 4px;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <div class="application-container">
        <!-- Header -->
        <div class="text-center mb-4">
            <img src="../assets/images/logo.jpeg" alt="IBVTE" style="height: 240px; border-radius: 50%; margin-bottom: 15px; border: 4px solid rgba(255,255,255,0.3);">
            <h4 class="text-white fw-bold"><?= APP_NAME ?></h4>
            <p class="text-white opacity-75">Online Affiliation Application Portal</p>
        </div>
        
        <?php if ($flash): ?>
            <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show mx-3">
                <?= $flash['message'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($step < 6): ?>
        <!-- Step Wizard -->
        <div class="step-wizard">
            <div class="step-item <?= $step >= 1 ? 'active' : '' ?> <?= $step > 1 ? 'completed' : '' ?>">
                <div class="step-number"><i class="fas fa-file-signature"></i></div>
                <div class="step-label">Agreement</div>
            </div>
            <div class="step-item <?= $step >= 2 ? 'active' : '' ?> <?= $step > 2 ? 'completed' : '' ?>">
                <div class="step-number"><i class="fas fa-university"></i></div>
                <div class="step-label">Institution Details</div>
            </div>
            <div class="step-item <?= $step >= 3 ? 'active' : '' ?> <?= $step > 3 ? 'completed' : '' ?>">
                <div class="step-number"><i class="fas fa-book"></i></div>
                <div class="step-label">Requirements</div>
            </div>
            <div class="step-item <?= $step >= 4 ? 'active' : '' ?> <?= $step > 4 ? 'completed' : '' ?>">
                <div class="step-number"><i class="fas fa-upload"></i></div>
                <div class="step-label">Documents & Dec</div>
            </div>
            <div class="step-item <?= $step >= 5 ? 'active' : '' ?>">
                <div class="step-number"><i class="fas fa-credit-card"></i></div>
                <div class="step-label">Payment & Submit</div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Step 1: Agreement & Offline Download -->
        <?php if ($step === 1): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-file-contract me-2"></i>Terms & Conditions</h3>
                <p class="mb-0">Please read carefully before proceeding with affiliation application</p>
            </div>
            <div class="step-body">
                <div class="agreement-box">
                    <h5>Affiliation Agreement</h5>
                    <ol>
                        <li>The institution must have valid registration with appropriate government bodies.</li>
                        <li>Minimum infrastructure requirements include:
                            <ul>
                                <li>At least 5 classrooms with adequate seating</li>
                                <li>Computer lab with minimum 20 computers</li>
                                <li>Library with minimum 500 books</li>
                                <li>Clean drinking water and sanitation facilities</li>
                            </ul>
                        </li>
                        <li>Qualified teaching staff as per IBVTE norms must be appointed.</li>
                        <li>Institution must maintain records of all students and examinations.</li>
                        <li>Annual inspection by IBVTE officials is mandatory.</li>
                        <li>Affiliation fees must be paid before the deadline each year.</li>
                        <li>Institution must display IBVTE affiliation certificate prominently.</li>
                        <li>Any change in management or address must be reported within 30 days.</li>
                        <li>IBVTE reserves the right to cancel affiliation for violation of norms.</li>
                        <li>All decisions by IBVTE Governing Body shall be final and binding.</li>
                    </ol>
                    
                    <h5 class="mt-4">Required Documents Checklist:</h5>
                    <ul>
                        <li>Trust/Company Registration Certificate</li>
                        <li>Building Ownership/Rent Agreement</li>
                        <li>Fire Safety Certificate</li>
                        <li>Sanitation Certificate</li>
                        <li>Staff Qualification Certificates</li>
                        <li>Affiliation fee payment proof</li>
                    </ul>
                </div>
                
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                    <div class="checkbox-wrapper">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="i_agree" id="iAgree" required style="width: 24px; height: 24px;">
                            <label class="form-check-label ms-2" for="iAgree" style="font-size: 1.1rem;">
                                <strong>I have read and agree to all terms and conditions</strong><br>
                                <small class="text-muted">I confirm that my institution meets all requirements mentioned above.</small>
                            </label>
                        </div>
                    </div>
                    
                    <div class="d-grid gap-3">
                        <button type="submit" class="btn btn-primary-custom btn-lg" id="proceedBtn" style="pointer-events: none; opacity: 0.6;">
                            <i class="fas fa-arrow-right me-2"></i>Proceed to Online Application
                        </button>
                        
                        <div class="text-center mt-3 pt-3 border-top">
                            <p class="text-muted mb-2">— OR FOR OFFLINE SUBMISSION —</p>
                            <a href="https://ibvte.com/affilation-format.pdf" download target="_blank" class="btn btn-outline-danger btn-lg w-100 fw-bold shadow-sm">
                                <i class="fas fa-file-pdf me-2"></i>Download Affiliation Form for Offline Apply
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <script>
            document.getElementById('iAgree').addEventListener('change', function() {
                const btn = document.getElementById('proceedBtn');
                if (this.checked) {
                    btn.style.pointerEvents = 'auto';
                    btn.style.opacity = '1';
                } else {
                    btn.style.pointerEvents = 'none';
                    btn.style.opacity = '0.6';
                }
            });
        </script>
        <?php endif; ?>
        
        <!-- Step 2: Institution & Legal Status -->
        <?php if ($step === 2): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-university me-2"></i>SECTION 1 & 2: Institution Details & Legal Status</h3>
            </div>
            <div class="step-body">
                <form method="POST" action="?step=2" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                    
                    <!-- SECTION 1 -->
                    <div class="form-section">
                        <h5>SECTION 1: INSTITUTION DETAILS</h5>
                        <div class="row">
                            <div class="col-md-12 mb-3 text-center">
                                <label class="fw-bold d-block mb-2">Director's Photo *</label>
                                <div class="photo-upload-placeholder shadow-sm position-relative" style="cursor: pointer;" onclick="document.getElementById('photoInput').click()">
                                    <i class="fas fa-user-tie fa-3x text-muted mb-2" id="photoPlaceholderIcon"></i>
                                    <span id="photoPlaceholderText" class="small">Click to Upload Photo</span>
                                    <img id="photoPreview" style="display:none; width: 100%; height: 100%; object-fit: cover; position: absolute; top:0; left:0; border-radius: 8px;">
                                </div>
                                <input type="file" name="director_photo" id="photoInput" accept="image/*" class="d-none" onchange="previewPhoto(this)" required>
                                <small class="text-muted d-block mt-1">Accepts PNG, JPG (Max 2MB)</small>
                            </div>

                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Name of Institution / Center *</label>
                                <input type="text" name="institution_name" class="form-control" placeholder="e.g. IBVTE Center of Excellence" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Name of Director / Principal *</label>
                                <input type="text" name="director_name" class="form-control" placeholder="Full name" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Father's / Guardian Name *</label>
                                <input type="text" name="father_guardian_name" class="form-control" required>
                            </div>
                        
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Registered Address *</label>
                                <textarea name="registered_address" class="form-control" rows="2" required placeholder="Legal registered address"></textarea>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Communication Address *</label>
                                <textarea name="communication_address" class="form-control" rows="2" required placeholder="Correspondence / center address"></textarea>
                            </div>
                        
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">PIN Code *</label>
                                <input type="text" name="pincode" class="form-control" pattern="[0-9]{6}" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Mobile No. *</label>
                                <input type="tel" name="director_mobile" class="form-control" pattern="[0-9]{10}" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">WhatsApp No. *</label>
                                <input type="tel" name="whatsapp_no" class="form-control" pattern="[0-9]{10}" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Email ID *</label>
                                <input type="email" name="director_email" class="form-control" required>
                            </div>
                        
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Center Website (if any)</label>
                                <input type="url" name="website" class="form-control" placeholder="https://example.com">
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Established Year</label>
                                <input type="number" name="established_year" class="form-control" min="1950" max="<?= date('Y') ?>">
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Total Staff *</label>
                                <input type="number" name="total_staff" class="form-control" required>
                            </div>
                        </div>
                    </div>
                    
                    <!-- SECTION 2 -->
                    <div class="form-section">
                        <h5>SECTION 2: LEGAL & FINANCIAL STATUS</h5>
                        <div class="mb-4">
                            <label class="fw-bold d-block mb-2">Institution Type *</label>
                            <div class="d-flex flex-wrap gap-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="institution_type_opts[]" value="Trust" id="chkTrust">
                                    <label class="form-check-label" for="chkTrust">Trust</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="institution_type_opts[]" value="Society" id="chkSociety">
                                    <label class="form-check-label" for="chkSociety">Society</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="institution_type_opts[]" value="Proprietorship" id="chkProp">
                                    <label class="form-check-label" for="chkProp">Proprietorship</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="institution_type_opts[]" value="Partnership" id="chkPartner">
                                    <label class="form-check-label" for="chkPartner">Partnership</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="institution_type_opts[]" value="NGO" id="chkNGO">
                                    <label class="form-check-label" for="chkNGO">NGO</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="institution_type_opts[]" value="Other" id="chkOtherType">
                                    <label class="form-check-label" for="chkOtherType">Other</label>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Registration Number *</label>
                                <input type="text" name="registration_number" class="form-control" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Registration Date *</label>
                                <input type="date" name="registration_date" class="form-control" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Building Ownership Type</label>
                                <select name="building_type" class="form-select">
                                    <option value="owned">Owned</option>
                                    <option value="rented">Rented</option>
                                    <option value="leased">Leased</option>
                                </select>
                            </div>
                        
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">PAN / GST No. (if applicable)</label>
                                <input type="text" name="pan_gst_no" class="form-control">
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="fw-bold">Identity Proof No. (Aadhar/Voter ID) *</label>
                                <input type="text" name="identity_proof_no" class="form-control" required>
                            </div>
                        </div>
                        
                        <h6 class="text-secondary fw-bold mt-3 mb-2"><i class="fas fa-university me-2"></i>Institution Bank Details (For Verification)</h6>
                        <div class="row bg-light p-3 rounded">
                            <div class="col-md-12 mb-2">
                                <label class="small fw-bold">Bank Name *</label>
                                <input type="text" name="bank_name" class="form-control form-control-sm" required>
                            </div>
                            <div class="col-md-12 mb-2">
                                <label class="small fw-bold">Account No *</label>
                                <input type="text" name="bank_account_no" class="form-control form-control-sm" required>
                            </div>
                            <div class="col-md-12 mb-2">
                                <label class="small fw-bold">IFSC Code *</label>
                                <input type="text" name="bank_ifsc" class="form-control form-control-sm" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <a href="?step=1" class="btn btn-secondary btn-lg">
                            <i class="fas fa-arrow-left me-2"></i>Back
                        </a>
                        <button type="submit" class="btn btn-primary-custom btn-lg">
                            <i class="fas fa-arrow-right me-2"></i>Next: Requirements & Infrastructure
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <script>
        function previewPhoto(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('photoPreview').src = e.target.result;
                    document.getElementById('photoPreview').style.display = 'block';
                    document.getElementById('photoPlaceholderIcon').style.display = 'none';
                    document.getElementById('photoPlaceholderText').style.display = 'none';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        </script>
        <?php endif; ?>
        
        <!-- Step 3: Requirements, Courses & Infrastructure -->
        <?php if ($step === 3): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-tools me-2"></i>SECTION 3, 4, 5 & 6: Affiliation, Infrastructure & Faculty</h3>
            </div>
            <div class="step-body">
                <form method="POST" action="?step=3">
                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                    
                    <!-- SECTION 3 -->
                    <div class="form-section">
                        <h5>SECTION 3: AFFILIATION REQUIREMENT</h5>
                        <div class="mb-3">
                            <label class="fw-bold d-block mb-2">Applied For (Checkboxes) *</label>
                            <div class="d-flex flex-wrap gap-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="applied_for_opts[]" value="Vocational" id="chkVoc">
                                    <label class="form-check-label" for="chkVoc">Vocational</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="applied_for_opts[]" value="Technical" id="chkTech">
                                    <label class="form-check-label" for="chkTech">Technical</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="applied_for_opts[]" value="Skill Development" id="chkSkill">
                                    <label class="form-check-label" for="chkSkill">Skill Development</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="applied_for_opts[]" value="Computer" id="chkComp">
                                    <label class="form-check-label" for="chkComp">Computer</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="applied_for_opts[]" value="Paramedical" id="chkPara">
                                    <label class="form-check-label" for="chkPara">Paramedical</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="applied_for_opts[]" value="Other" id="chkOtherApp">
                                    <label class="form-check-label" for="chkOtherApp">Other</label>
                                </div>
                            </div>
                        </div>
                        <div class="mb-2">
                            <label class="fw-bold">Proposed Center Name *</label>
                            <input type="text" name="proposed_center_name" class="form-control" required placeholder="Enter center name as it should appear in certificate">
                        </div>
                    </div>
                    
                    <!-- SECTION 4 -->
                    <div class="form-section">
                        <h5>SECTION 4: INFRASTRUCTURE DETAILS</h5>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="fw-bold">Total Rooms / Classrooms *</label>
                                <input type="number" name="classrooms" class="form-control" required>
                            </div>
                            <div class="col-md-6">
                                <label class="fw-bold">Total Covered / Carpet Area (in Sq. Ft.) *</label>
                                <input type="text" name="total_area" class="form-control" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <!-- Radios -->
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Practical Lab Facility Available? *</label>
                                <div class="d-flex gap-3 mt-1">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="practical_lab_facility" value="1" id="labYes">
                                        <label class="form-check-label" for="labYes">Yes</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="practical_lab_facility" value="0" id="labNo" checked>
                                        <label class="form-check-label" for="labNo">No</label>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Computer Systems Available? *</label>
                                <div class="d-flex align-items-center gap-3 mt-1">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="computer_systems_available" value="1" id="compYes" onchange="document.getElementById('totalCompsBox').classList.remove('d-none')">
                                        <label class="form-check-label" for="compYes">Yes</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="computer_systems_available" value="0" id="compNo" checked onchange="document.getElementById('totalCompsBox').classList.add('d-none')">
                                        <label class="form-check-label" for="compNo">No</label>
                                    </div>
                                    <div class="d-none ms-2" id="totalCompsBox">
                                        <input type="number" name="total_computers" class="form-control form-control-sm d-inline-block" style="width:100px;" placeholder="Systems count">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Internet Facility? *</label>
                                <div class="d-flex gap-3">
                                    <div class="form-check"><input class="form-check-input" type="radio" name="internet_facility" value="1" id="intYes"><label class="form-check-label" for="intYes">Yes</label></div>
                                    <div class="form-check"><input class="form-check-input" type="radio" name="internet_facility" value="0" id="intNo" checked><label class="form-check-label" for="intNo">No</label></div>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Power Backup Facility? *</label>
                                <div class="d-flex gap-3">
                                    <div class="form-check"><input class="form-check-input" type="radio" name="power_backup_facility" value="1" id="powerYes"><label class="form-check-label" for="powerYes">Yes</label></div>
                                    <div class="form-check"><input class="form-check-input" type="radio" name="power_backup_facility" value="0" id="powerNo" checked><label class="form-check-label" for="powerNo">No</label></div>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Clean Drinking Water? *</label>
                                <div class="d-flex gap-3">
                                    <div class="form-check"><input class="form-check-input" type="radio" name="clean_drinking_water" value="1" id="waterYes"><label class="form-check-label" for="waterYes">Yes</label></div>
                                    <div class="form-check"><input class="form-check-input" type="radio" name="clean_drinking_water" value="0" id="waterNo" checked><label class="form-check-label" for="waterNo">No</label></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-2">
                                <label class="fw-bold">Furniture Available? *</label>
                                <div class="d-flex gap-3">
                                    <div class="form-check"><input class="form-check-input" type="radio" name="furniture_available" value="1" id="furnYes"><label class="form-check-label" for="furnYes">Yes</label></div>
                                    <div class="form-check"><input class="form-check-input" type="radio" name="furniture_available" value="0" id="furnNo" checked><label class="form-check-label" for="furnNo">No</label></div>
                                </div>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="fw-bold">Washroom Facility? *</label>
                                <div class="d-flex gap-3">
                                    <div class="form-check"><input class="form-check-input" type="radio" name="washroom_facility" value="1" id="washYes"><label class="form-check-label" for="washYes">Yes</label></div>
                                    <div class="form-check"><input class="form-check-input" type="radio" name="washroom_facility" value="0" id="washNo" checked><label class="form-check-label" for="washNo">No</label></div>
                                </div>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="fw-bold">Fire Extinguishers? *</label>
                                <div class="d-flex gap-3">
                                    <div class="form-check"><input class="form-check-input" type="radio" name="safety_fire_extinguisher" value="1" id="fireYes"><label class="form-check-label" for="fireYes">Yes</label></div>
                                    <div class="form-check"><input class="form-check-input" type="radio" name="safety_fire_extinguisher" value="0" id="fireNo" checked><label class="form-check-label" for="fireNo">No</label></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- SECTION 5 -->
                    <div class="form-section">
                        <h5>SECTION 5: STAFF / FACULTY DETAILS</h5>
                        <div class="table-responsive">
                            <table class="table table-bordered align-middle data-table" id="facultyTable">
                                <thead class="table-dark">
                                    <tr>
                                        <th style="width:70px;" class="text-center">S. No.</th>
                                        <th>Name of Faculty *</th>
                                        <th>Qualification</th>
                                        <th>Designation</th>
                                        <th>Experience (in Years)</th>
                                        <th style="width:90px;" class="text-center">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="faculty-row">
                                        <td class="text-center fw-bold row-idx">1</td>
                                        <td><input type="text" name="faculty_name[]" class="form-control form-control-sm" required placeholder="Faculty name"></td>
                                        <td><input type="text" name="faculty_qualification[]" class="form-control form-control-sm" placeholder="e.g. M.Tech, MCA"></td>
                                        <td><input type="text" name="faculty_designation[]" class="form-control form-control-sm" placeholder=" Lecturer"></td>
                                        <td><input type="text" name="faculty_experience[]" class="form-control form-control-sm" placeholder="e.g. 5"></td>
                                        <td class="text-center">
                                            <button type="button" class="btn btn-sm btn-danger" onclick="deleteFacultyRow(this)"><i class="fas fa-trash-alt"></i></button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <button type="button" class="btn btn-outline-primary btn-sm fw-bold mt-2" onclick="addFacultyRow()">
                            <i class="fas fa-plus me-1"></i> Add Faculty / Staff Member
                        </button>
                    </div>
                    
                    <!-- SECTION 6 -->
                    <div class="form-section">
                        <h5>SECTION 6: COURSES APPLIED FOR</h5>
                        <p class="text-muted small mb-3"><i class="fas fa-info-circle me-1"></i>Add dynamic courses in the table below. You can also click on any course from the database list below to auto-fill!</p>
                        
                        <div class="table-responsive mb-4">
                            <table class="table table-bordered align-middle data-table" id="coursesAppliedTable">
                                <thead class="table-primary">
                                    <tr>
                                        <th style="width:70px;" class="text-center">S.No.</th>
                                        <th>Course Name *</th>
                                        <th>Duration</th>
                                        <th>Eligibility</th>
                                        <th>Course Code</th>
                                        <th style="width:90px;" class="text-center">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="course-row">
                                        <td class="text-center fw-bold row-idx">1</td>
                                        <td><input type="text" name="applied_course_name[]" class="form-control form-control-sm course-name-inp" required placeholder="Course Name"></td>
                                        <td><input type="text" name="applied_course_duration[]" class="form-control form-control-sm course-dur-inp" placeholder="e.g. 1 Year"></td>
                                        <td><input type="text" name="applied_course_eligibility[]" class="form-control form-control-sm course-elig-inp" placeholder="e.g. 10th Pass"></td>
                                        <td><input type="text" name="applied_course_code[]" class="form-control form-control-sm course-code-inp" placeholder="e.g. DP01"></td>
                                        <td class="text-center">
                                            <button type="button" class="btn btn-sm btn-danger" onclick="deleteCourseRow(this)"><i class="fas fa-trash-alt"></i></button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <button type="button" class="btn btn-outline-primary btn-sm fw-bold mb-4" onclick="addCourseRow()">
                            <i class="fas fa-plus me-1"></i> Add Course Row
                        </button>

                        <!-- Click to add helper course database list -->
                        <h6 class="fw-bold text-secondary mb-3"><i class="fas fa-graduation-cap me-2"></i>Select Courses from Database to Auto-Fill:</h6>
                        <div class="row g-2 overflow-y-auto" style="max-height: 250px; border: 1px solid #ddd; padding: 15px; border-radius: 8px; background: #fafafa;">
                            <?php 
                            $coursesList = $db->fetchAll("SELECT * FROM courses WHERE is_active = 1 ORDER BY course_name ASC");
                            foreach ($coursesList as $course): 
                            ?>
                            <div class="col-md-4">
                                <button type="button" class="btn btn-sm btn-outline-dark text-start w-100 p-2 truncate-text" 
                                        onclick="autoFillCourse('<?= addslashes($course['course_name']) ?>', '<?= addslashes($course['duration']) ?>', '<?= addslashes($course['eligibility'] ?? '10th / 12th') ?>', '<?= addslashes($course['course_code']) ?>')">
                                    <i class="fas fa-plus-circle text-primary me-1"></i>
                                    <small><strong><?= htmlspecialchars($course['course_code']) ?></strong> - <?= htmlspecialchars($course['course_name']) ?></small>
                                </button>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-between mt-4">
                        <a href="?step=2" class="btn btn-secondary btn-lg">
                            <i class="fas fa-arrow-left me-2"></i>Back
                        </a>
                        <button type="submit" class="btn btn-primary-custom btn-lg">
                            <i class="fas fa-arrow-right me-2"></i>Next: Documents & Declaration
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <script>
            function addFacultyRow() {
                const tbody = document.querySelector('#facultyTable tbody');
                const rowCount = tbody.querySelectorAll('.faculty-row').length + 1;
                const newRow = document.createElement('tr');
                newRow.className = 'faculty-row';
                newRow.innerHTML = `
                    <td class="text-center fw-bold row-idx">${rowCount}</td>
                    <td><input type="text" name="faculty_name[]" class="form-control form-control-sm" required placeholder="Faculty name"></td>
                    <td><input type="text" name="faculty_qualification[]" class="form-control form-control-sm" placeholder="e.g. M.Tech, MCA"></td>
                    <td><input type="text" name="faculty_designation[]" class="form-control form-control-sm" placeholder="Lecturer"></td>
                    <td><input type="text" name="faculty_experience[]" class="form-control form-control-sm" placeholder="e.g. 5"></td>
                    <td class="text-center">
                        <button type="button" class="btn btn-sm btn-danger" onclick="deleteFacultyRow(this)"><i class="fas fa-trash-alt"></i></button>
                    </td>
                `;
                tbody.appendChild(newRow);
            }

            function deleteFacultyRow(btn) {
                const tbody = document.querySelector('#facultyTable tbody');
                const rows = tbody.querySelectorAll('.faculty-row');
                if (rows.length <= 1) {
                    alert("At least one faculty member row must be present.");
                    return;
                }
                btn.closest('.faculty-row').remove();
                
                // Recalculate Serial Numbers
                const updatedRows = tbody.querySelectorAll('.faculty-row');
                updatedRows.forEach((row, idx) => {
                    row.querySelector('.row-idx').textContent = idx + 1;
                });
            }

            function addCourseRow() {
                const tbody = document.querySelector('#coursesAppliedTable tbody');
                const rowCount = tbody.querySelectorAll('.course-row').length + 1;
                const newRow = document.createElement('tr');
                newRow.className = 'course-row';
                newRow.innerHTML = `
                    <td class="text-center fw-bold row-idx">${rowCount}</td>
                    <td><input type="text" name="applied_course_name[]" class="form-control form-control-sm course-name-inp" required placeholder="Course Name"></td>
                    <td><input type="text" name="applied_course_duration[]" class="form-control form-control-sm course-dur-inp" placeholder="e.g. 1 Year"></td>
                    <td><input type="text" name="applied_course_eligibility[]" class="form-control form-control-sm course-elig-inp" placeholder="e.g. 10th Pass"></td>
                    <td><input type="text" name="applied_course_code[]" class="form-control form-control-sm course-code-inp" placeholder="e.g. DP01"></td>
                    <td class="text-center">
                        <button type="button" class="btn btn-sm btn-danger" onclick="deleteCourseRow(this)"><i class="fas fa-trash-alt"></i></button>
                    </td>
                `;
                tbody.appendChild(newRow);
            }

            function deleteCourseRow(btn) {
                const tbody = document.querySelector('#coursesAppliedTable tbody');
                const rows = tbody.querySelectorAll('.course-row');
                if (rows.length <= 1) {
                    alert("At least one course row must be present.");
                    return;
                }
                btn.closest('.course-row').remove();
                
                // Recalculate Serial Numbers
                const updatedRows = tbody.querySelectorAll('.course-row');
                updatedRows.forEach((row, idx) => {
                    row.querySelector('.row-idx').textContent = idx + 1;
                });
            }

            function autoFillCourse(name, duration, eligibility, code) {
                const tbody = document.querySelector('#coursesAppliedTable tbody');
                const rows = tbody.querySelectorAll('.course-row');
                let targetRow = null;
                
                // Find first empty row
                for (let i = 0; i < rows.length; i++) {
                    const nameInput = rows[i].querySelector('.course-name-inp');
                    if (nameInput && nameInput.value.trim() === '') {
                        targetRow = rows[i];
                        break;
                    }
                }
                
                // If all rows are full, add one dynamically
                if (!targetRow) {
                    addCourseRow();
                    const currentRows = tbody.querySelectorAll('.course-row');
                    targetRow = currentRows[currentRows.length - 1];
                }
                
                // Fill inputs
                targetRow.querySelector('.course-name-inp').value = name;
                targetRow.querySelector('.course-dur-inp').value = duration;
                targetRow.querySelector('.course-elig-inp').value = eligibility;
                targetRow.querySelector('.course-code-inp').value = code;
                
                // Highlight filled row briefly
                targetRow.style.background = '#e3f2fd';
                setTimeout(() => {
                    targetRow.style.background = 'transparent';
                }, 800);
            }
        </script>
        <?php endif; ?>
        
        <!-- Step 4: Documents & Declaration -->
        <?php if ($step === 4): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-file-invoice me-2"></i>SECTION 7 & 8: Documents & Declaration</h3>
            </div>
            <div class="step-body">
                <form method="POST" action="?step=4" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                    
                    <!-- SECTION 7 -->
                    <div class="form-section">
                        <h5>SECTION 7: DOCUMENTS ATTACHED & UPLOAD</h5>
                        <p class="text-muted small mb-3"><i class="fas fa-upload me-1"></i>Please check the boxes and upload the corresponding PDF/Image file for each document:</p>
                        
                        <div class="row g-3">
                            <?php 
                            $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'
                            ];
                            foreach ($docsCheck as $idx => $dname):
                            ?>
                            <div class="col-md-12">
                                <div class="p-3 rounded bg-light border d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-3">
                                    <div class="form-check flex-grow-1 mb-0">
                                        <input class="form-check-input ms-0 me-2" type="checkbox" name="documents_attached_opts[]" value="<?= htmlspecialchars($dname) ?>" id="docChk<?= $idx ?>" style="width:18px; height:18px;">
                                        <label class="form-check-label fw-bold text-secondary" for="docChk<?= $idx ?>"><?= $dname ?></label>
                                    </div>
                                    <div class="file-upload-block text-md-end" style="min-width: 320px;">
                                        <input type="file" name="doc_file_<?= $idx ?>" class="form-control form-control-sm" accept=".pdf,image/*">
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <!-- SECTION 8 -->
                    <div class="form-section">
                        <h5>SECTION 8: DECLARATION</h5>
                        <div class="p-3 bg-light rounded border border-warning mb-3">
                            <p class="mb-0 fw-bold text-dark" style="line-height:1.6; font-size:1.05rem;">
                                "I hereby declare that all information furnished in this application is true, correct, and authentic to the best of my knowledge. I agree to abide by all rules, regulations, policies, and constitutional authority of the Board."
                            </p>
                        </div>
                        
                        <div class="form-check mb-4">
                            <input class="form-check-input" type="checkbox" id="declarationConfirm" required style="width:20px; height:20px;">
                            <label class="form-check-label ms-2 fw-bold" for="declarationConfirm">
                                I confirm the declaration above and declare myself responsible for the contents.
                            </label>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Applicant / Director Name *</label>
                                <input type="text" name="applicant_name" class="form-control" required placeholder="Signature / authorized name">
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="fw-bold">Date *</label>
                                <input type="date" name="declaration_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                            </div>
                            <div class="col-md-3 mb-3">
                                <label class="fw-bold">Place *</label>
                                <input type="text" name="declaration_place" class="form-control" required placeholder="e.g. New Delhi">
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-between">
                        <a href="?step=3" class="btn btn-secondary btn-lg">
                            <i class="fas fa-arrow-left me-2"></i>Back
                        </a>
                        <button type="submit" class="btn btn-primary-custom btn-lg">
                            <i class="fas fa-arrow-right me-2"></i>Next: Review & Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Step 5: Payment & Office Use Box Removed -->
        <?php if ($step === 5): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-credit-card me-2"></i>Payment & Submission</h3>
            </div>
            <div class="step-body">
                <form method="POST" action="?step=5">
                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                    <div class="row">
                        <div class="col-md-5">
                            <div class="fee-summary">
                                <h5 class="mb-3"><i class="fas fa-receipt me-2"></i>Fee Summary</h5>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Base Affiliation Fee</span>
                                    <span>₹50,000</span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Processing Charges</span>
                                    <span>₹1,000</span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>GST (18%)</span>
                                    <span>₹9,180</span>
                                </div>
                                <hr class="my-3" style="border-color: rgba(255,255,255,0.3);">
                                <div class="d-flex justify-content-between fw-bold fs-5">
                                    <span>Total Payable</span>
                                    <span>₹60,180</span>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-7">
                            <h5 class="mb-3">Select Payment Method</h5>

                            <!-- Payment Method Dropdown -->
                            <div class="mb-4">
                                <label class="fw-bold mb-2">Payment Mode <span class="text-danger">*</span></label>
                                <select class="form-select form-select-lg" id="paymentMethod" name="payment_method"
                                        onchange="handlePaymentChange(this.value)">
                                    <option value="card" selected>💳 Credit / Debit Card</option>
                                    <option value="upi">📱 UPI (GPay / PhonePe / Paytm)</option>
                                    <option value="netbanking">🏦 Net Banking</option>
                                    <option value="dd">📄 Demand Draft (DD)</option>
                                    <option value="neft">🔁 NEFT / RTGS Transfer</option>
                                    <option value="submitted">✅ Already Submitted — Upload Proof</option>
                                </select>
                            </div>

                            <!-- DD / NEFT details -->  
                            <div id="bankDetails" class="d-none alert alert-secondary">
                                <strong><i class="fas fa-university me-2"></i>Bank Details for DD / NEFT:</strong><br>
                                Bank: <strong>State Bank of India</strong><br>
                                Account Name: <strong>IBVTE New Delhi</strong><br>
                                Account No: <strong>XXXXXXXX1234</strong><br>
                                IFSC: <strong>SBIN0001234</strong><br>
                                Branch: <strong>Connaught Place, New Delhi</strong>
                            </div>

                            <!-- Already Submitted proof upload -->
                            <div id="proofUpload" class="d-none">
                                <div class="mb-3">
                                    <label class="fw-bold">Transaction / Reference Number</label>
                                    <input type="text" name="txn_reference" class="form-control mt-1"
                                           placeholder="e.g. UTR123456789 or DD Number">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-info mt-4">
                        <i class="fas fa-info-circle me-2"></i>
                        After successful payment, you will receive an acknowledgment with application reference number.
                    </div>
                    
                    <div class="d-flex justify-content-between mt-4">
                        <a href="?step=4" class="btn btn-secondary btn-lg">
                            <i class="fas fa-arrow-left me-2"></i>Back
                        </a>
                        <button type="submit" class="btn btn-primary-custom btn-lg">
                            <i class="fas fa-lock me-2"></i>Submit Application & Pay Fee
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <script>
            function handlePaymentChange(val) {
                var bankDetails  = document.getElementById('bankDetails');
                var proofUpload  = document.getElementById('proofUpload');
                
                // Hide all conditional sections first
                bankDetails.classList.add('d-none');
                proofUpload.classList.add('d-none');
                
                // Show relevant section
                if (val === 'dd' || val === 'neft') {
                    bankDetails.classList.remove('d-none');
                }
                if (val === 'submitted') {
                    proofUpload.classList.remove('d-none');
                }
            }
        </script>
        <?php endif; ?>
        
        <!-- Step 6: Confirmation -->
        <?php if ($step === 6): ?>
        <div class="step-content text-center py-5">
            <div class="p-5">
                <i class="fas fa-check-circle fa-5x text-success mb-4"></i>
                <h2 class="fw-bold text-success mb-3">Application Submitted Successfully!</h2>
                <p class="lead mb-4">Your affiliation application has been received and is under review.</p>
                
                <div class="alert alert-info mx-auto" style="max-width: 500px;">
                    <h5 class="alert-heading">Application Reference ID</h5>
                    <p class="mb-0 fs-3 fw-bold text-primary"><?= htmlspecialchars($_SESSION['aff_ref_id'] ?? 'AFF'.time()) ?></p>
                    <small>Please save this ID for tracking your application status</small>
                </div>
                
                <div class="mt-4">
                    <p class="text-muted">You will receive updates via email and SMS</p>
                    <a href="../index.php" class="btn btn-primary-custom btn-lg me-2">
                        <i class="fas fa-home me-2"></i>Go to Home
                    </a>
                    <a href="status.php" class="btn btn-outline-primary btn-lg">
                        <i class="fas fa-search me-2"></i>Track Status
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
