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

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

// Start session only if not already started (config.php may have started it)
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
    if ($step === 2) {
        $_SESSION['aff_step2'] = [
            'institution_name'   => trim($_POST['institution_name'] ?? ''),
            'institution_type'   => trim($_POST['institution_type'] ?? ''),
            'established_year'   => trim($_POST['established_year'] ?? ''),
            'registration_number'=> trim($_POST['registration_number'] ?? ''),
            'total_staff'        => intval($_POST['total_staff'] ?? 0),
            'director_name'      => trim($_POST['director_name'] ?? ''),
            'director_mobile'    => trim($_POST['director_mobile'] ?? ''),
            'director_email'     => trim($_POST['director_email'] ?? ''),
            'landline'           => trim($_POST['landline'] ?? ''),
            'address'            => trim($_POST['address'] ?? ''),
            'city'               => trim($_POST['city'] ?? ''),
            'district'           => trim($_POST['district'] ?? ''),
            'state'              => trim($_POST['state'] ?? ''),
            'pincode'            => trim($_POST['pincode'] ?? ''),
            'website'            => trim($_POST['website'] ?? ''),
            'building_type'      => trim($_POST['building_type'] ?? ''),
            'total_area'         => trim($_POST['total_area'] ?? ''),
            'classrooms'         => intval($_POST['classrooms'] ?? 0),
            'facilities'         => implode(',', array_filter([
                isset($_POST['library'])     ? 'Library'      : '',
                isset($_POST['computer_lab'])? 'Computer Lab'  : '',
                isset($_POST['internet'])    ? 'Internet'      : '',
                isset($_POST['sports'])      ? 'Sports Ground' : '',
            ])),
        ];
        header('Location: apply.php?step=3');
        exit;
    }

    // Step 3: Save selected courses to session
    if ($step === 3) {
        $_SESSION['aff_step3'] = ['courses' => $_POST['courses'] ?? []];
        header('Location: apply.php?step=4');
        exit;
    }

    // Step 4: Documents (skip - files would need actual file handling)
    if ($step === 4) {
        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'] ?? [];
        $courses   = implode(',', $s3['courses'] ?? []);

        try {
            $db->insert('affiliation_applications', [
                'application_number'  => $appNumber,
                'institution_name'    => $s2['institution_name']    ?? '',
                'institution_type'    => $s2['institution_type']    ?? '',
                'established_year'    => ($s2['established_year'] ?? '') ?: null,
                'total_staff'         => $s2['total_staff']         ?? 0,
                'director_name'       => $s2['director_name']       ?? '',
                'director_mobile'     => $s2['director_mobile']     ?? '',
                'director_email'      => $s2['director_email']      ?? '',
                'landline'            => $s2['landline']            ?? '',
                'address'             => $s2['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'=> $s2['classrooms']          ?? 0,
                'library_facility'    => (strpos($s2['facilities'] ?? '', 'Library') !== false) ? 1 : 0,
                'computer_lab'        => (strpos($s2['facilities'] ?? '', 'Computer') !== false) ? 1 : 0,
                'internet_facility'   => (strpos($s2['facilities'] ?? '', 'Internet') !== false) ? 1 : 0,
                'courses_applied'     => $courses,
                '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'] ?? '',
            ]);
            // Clear session data
            unset($_SESSION['aff_step2'], $_SESSION['aff_step3'], $_SESSION['affiliation_agreed']);
            $_SESSION['aff_ref_id'] = $appNumber;
        } catch (Exception $e) {
            // 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: 1000px;
            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: 30px;
        }
        .form-section h5 {
            color: var(--primary-color);
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .course-checkbox {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            transition: all 0.3s;
            cursor: pointer;
        }
        .course-checkbox:hover {
            background: rgba(59, 11, 124, 0.05);
            transform: translateX(5px);
        }
        .course-checkbox input[type="checkbox"] {
            width: 20px;
            height: 20px;
        }
        .file-upload-box {
            border: 2px dashed #ddd;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .file-upload-box:hover {
            border-color: var(--primary-color);
            background: rgba(59, 11, 124, 0.02);
        }
        .fee-summary {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
        }
        .btn-primary-custom {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            border: none;
            border-radius: 10px;
            padding: 12px 30px;
            font-weight: 600;
        }
    </style>
</head>
<body>
    <div class="application-container">
        <!-- Header -->
        <div class="text-center mb-4">
            <img src="../assets/images/logo.jpeg" alt="IBVTE" style="height: 80px; 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">
                <?= htmlspecialchars($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</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">Courses</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</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</div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Step 1: I Agree Terms -->
        <?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">
                        <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 Application
                        </button>
                    </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 Details -->
        <?php if ($step === 2): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-university me-2"></i>Institution Details</h3>
            </div>
            <div class="step-body">
                <form method="POST" action="?step=2">
                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                    <div class="form-section">
                        <h5>Basic Information</h5>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Institution Name *</label>
                                <input type="text" name="institution_name" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Institution Type *</label>
                                <select name="institution_type" class="form-select" required>
                                    <option value="">Select</option>
                                    <option value="college">College</option>
                                    <option value="institute">Institute</option>
                                    <option value="training_center">Training Center</option>
                                    <option value="school">School</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4 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-4 mb-3">
                                <label class="fw-bold">Registration Number *</label>
                                <input type="text" name="registration_number" class="form-control" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Total Staff *</label>
                                <input type="number" name="total_staff" class="form-control" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <h5>Contact Information</h5>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Director/Principal Name *</label>
                                <input type="text" name="director_name" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Mobile Number *</label>
                                <input type="tel" name="director_mobile" class="form-control" pattern="[0-9]{10}" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Email Address *</label>
                                <input type="email" name="director_email" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="fw-bold">Landline</label>
                                <input type="tel" name="landline" class="form-control">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <h5>Address Details</h5>
                        <div class="mb-3">
                            <label class="fw-bold">Full Address *</label>
                            <textarea name="address" class="form-control" rows="3" required></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">City *</label>
                                <input type="text" name="city" class="form-control" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">District</label>
                                <input type="text" name="district" class="form-control">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">State *</label>
                                <input type="text" name="state" class="form-control" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Pincode *</label>
                                <input type="text" name="pincode" class="form-control" pattern="[0-9]{6}" required>
                            </div>
                            <div class="col-md-8 mb-3">
                                <label class="fw-bold">Website (if any)</label>
                                <input type="url" name="website" class="form-control">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <h5>Infrastructure Details</h5>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Building 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-4 mb-3">
                                <label class="fw-bold">Total Area (sq ft)</label>
                                <input type="text" name="total_area" class="form-control">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="fw-bold">Number of Classrooms</label>
                                <input type="number" name="classrooms" class="form-control">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="library" id="library">
                                    <label class="form-check-label" for="library">Library Facility</label>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="computer_lab" id="computerLab">
                                    <label class="form-check-label" for="computerLab">Computer Lab</label>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="internet" id="internet">
                                    <label class="form-check-label" for="internet">Internet Facility</label>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="sports" id="sports">
                                    <label class="form-check-label" for="sports">Sports Ground</label>
                                </div>
                            </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: Select Courses
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Step 3: Course Selection -->
        <?php if ($step === 3): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-book me-2"></i>Course Selection</h3>
                <p class="mb-0">Select all courses you want affiliation for</p>
            </div>
            <div class="step-body">
                <form method="POST" action="?step=3">
                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                    <div class="row">
                        <!-- Apply All / Select All bar -->
                        <div class="col-12 mb-3">
                            <div class="p-3 rounded-3 d-flex align-items-center gap-3"
                                 style="background:linear-gradient(135deg,#3b0b7c,#6c4ab6);">
                                <input class="form-check-input" type="checkbox" id="selectAllCourses"
                                       style="width:22px;height:22px;cursor:pointer;flex-shrink:0;">
                                <label for="selectAllCourses" class="text-white fw-bold mb-0"
                                       style="font-size:1rem;cursor:pointer;">
                                    <i class="fas fa-check-double me-2"></i>Apply All — Select All Courses
                                </label>
                                <span class="badge bg-warning text-dark ms-auto" id="selectedCount">0 selected</span>
                            </div>
                        </div>
                        <?php 
                        $coursesList = $db->fetchAll("SELECT c.*, cf.admission_fee FROM courses c LEFT JOIN course_fees cf ON c.id = cf.course_id AND cf.user_type = 'college' WHERE c.is_active = 1");
                        foreach ($coursesList as $course): 
                        ?>
                        <div class="col-md-6">
                            <div class="course-checkbox">
                                <div class="form-check d-flex align-items-center">
                                    <input class="form-check-input me-3 course-chk" type="checkbox"
                                           name="courses[]" value="<?= $course['id'] ?>"
                                           id="course<?= $course['id'] ?>" onchange="updateCount()">
                                    <label class="form-check-label flex-grow-1" for="course<?= $course['id'] ?>">
                                        <div class="fw-bold"><?= htmlspecialchars($course['course_name']) ?> (<?= htmlspecialchars($course['course_code']) ?>)</div>
                                        <small class="text-muted">Duration: <?= htmlspecialchars($course['duration']) ?></small>
                                    </label>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="alert alert-info mt-4">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Note:</strong> Affiliation fees are calculated per course. Multiple courses discount available.
                    </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: Upload Documents
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <script>
        // Select All courses toggle
        document.getElementById('selectAllCourses').addEventListener('change', function(){
            var chks = document.querySelectorAll('.course-chk');
            chks.forEach(function(chk){ chk.checked = this.checked; }, this);
            updateCount();
        });
        function updateCount(){
            var total   = document.querySelectorAll('.course-chk').length;
            var checked = document.querySelectorAll('.course-chk:checked').length;
            document.getElementById('selectedCount').textContent = checked + ' / ' + total + ' selected';
            // sync master checkbox state
            var master = document.getElementById('selectAllCourses');
            if(master){
                master.checked       = checked === total && total > 0;
                master.indeterminate = checked > 0 && checked < total;
            }
        }
        // Init count on load
        updateCount();
        </script>
        
        <!-- Step 4: Document Upload -->
        <?php if ($step === 4): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-upload me-2"></i>Document Upload</h3>
                <p class="mb-0">Upload supporting documents (PDF, JPG, PNG – Max 2MB each) &bull; <em>All fields are optional</em></p>
            </div>
            <div class="step-body">
                <form method="POST" action="?step=4" enctype="multipart/form-data">
                    <input type="hidden" name="csrf_token" value="<?= Auth()->generateCSRFToken() ?>">
                    <div class="alert alert-warning py-2 mb-4">
                        <i class="fas fa-info-circle me-2"></i>
                        Documents can be uploaded now or submitted later during inspection. No document is mandatory at this stage.
                    </div>
                    <div class="row">
                        <?php 
                        $documents = [
                            ['name' => 'Trust/Company Registration'],
                            ['name' => 'Building Ownership/Rent Deed'],
                            ['name' => 'Fire Safety Certificate'],
                            ['name' => 'Sanitation Certificate'],
                            ['name' => 'Director Photo (Passport Size)'],
                            ['name' => 'Institution Exterior Photo'],
                            ['name' => 'Classroom Photos (Min 3)'],
                            ['name' => 'Library Photo'],
                        ];
                        foreach ($documents as $i => $doc): 
                        ?>
                        <div class="col-md-6 mb-3">
                            <label class="fw-bold"><?= $doc['name'] ?> <span class="text-muted fw-normal small">(Optional)</span></label>
                            <div class="file-upload-box" onclick="document.getElementById('doc<?= $i ?>').click()">
                                <i class="fas fa-cloud-upload-alt fa-2x text-primary mb-2"></i>
                                <p class="mb-1">Click to upload</p>
                                <small class="text-muted">PDF, JPG, PNG (Max 2MB)</small>
                                <input type="file" id="doc<?= $i ?>" name="documents[]" class="d-none"
                                       accept=".pdf,.jpg,.jpeg,.png"
                                       onchange="showFileName(this, 'name<?= $i ?>')">
                                <div class="mt-2 text-primary fw-bold" id="name<?= $i ?>"></div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="d-flex justify-content-between mt-4">
                        <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: Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <script>
            function showFileName(input, displayId) {
                if (input.files && input.files[0]) {
                    document.getElementById(displayId).textContent = 'Selected: ' + input.files[0].name;
                }
            }
        </script>
        <?php endif; ?>
        
        <!-- Step 5: Payment -->
        <?php if ($step === 5): ?>
        <div class="step-content">
            <div class="step-header">
                <h3><i class="fas fa-credit-card me-2"></i>Fee Payment</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">
                                <label class="fw-bold mb-2">Upload Payment Proof <span class="text-danger">*</span></label>
                                <div class="file-upload-box" onclick="document.getElementById('payProofFile').click()">
                                    <i class="fas fa-cloud-upload-alt fa-2x text-success mb-2"></i>
                                    <p class="mb-1">Click to upload receipt / screenshot</p>
                                    <small class="text-muted">PDF, JPG, PNG (Max 5MB)</small>
                                    <input type="file" id="payProofFile" name="payment_proof" class="d-none"
                                           accept=".pdf,.jpg,.jpeg,.png"
                                           onchange="document.getElementById('proofFileName').textContent = 'Selected: ' + this.files[0].name">
                                </div>
                                <div class="mt-2 text-success fw-bold" id="proofFileName"></div>
                                <div class="mb-3 mt-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>Pay ₹60,180 & Submit
                        </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">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>
