<?php
/**
 * Student Admission Form — Original Design (preserved) + Fixes
 *
 * Features:
 *   - Password field REMOVED (auto-generated from phone's last 6 digits)
 *   - Course dropdown FIXED — shows ALL active courses
 *   - Batch dropdown ADDED — shows branch's upcoming/running batches
 *   - Father's Name field ADDED back
 *   - Photo upload ADDED (max 50KB, JPG/PNG only)
 *   - PDF Preview button — opens a beautifully designed preview page with Download button
 *
 * Upload to: /gmind/branch/Views/students/create.php
 */

$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
?>
<div class="admin-page-header">
    <h2>Add Student</h2>
    <div style="display:flex; gap:8px; flex-wrap:wrap;">
        <button type="button" class="admin-btn admin-btn-outline" onclick="previewAdmissionForm()" style="background:#dc2626; color:#fff; border-color:#dc2626;">
            <i class="fas fa-file-pdf"></i> Preview Form PDF
        </button>
        <a href="<?= $bp ?>/branch/students" class="admin-btn admin-btn-outline">&larr; Back to Students</a>
    </div>
</div>

<div class="admin-card">
    <div class="admin-card-body">
        <form method="POST" action="<?= $bp ?>/branch/students" class="admin-form" novalidate id="admissionForm" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">

            <!-- Photo Upload Row -->
            <div class="admin-form-row">
                <div class="admin-form-group">
                    <label for="photo" class="admin-form-label">Student Photo <span style="color:#6b7280; font-weight:400;">(max 50KB, JPG/PNG)</span></label>
                    <input type="file" id="photo" name="photo" accept="image/jpeg,image/png,image/jpg" class="admin-form-input" onchange="validatePhoto(this)">
                    <small id="photoError" style="color:#dc2626; font-size:0.78rem; display:none;">
                        <i class="fas fa-exclamation-triangle"></i> Photo must be under 50KB
                    </small>
                    <div id="photoPreviewWrap" style="margin-top:8px; display:none;">
                        <img id="photoPreviewImg" src="" style="max-width:120px; max-height:160px; border:2px solid #16a085; border-radius:6px;">
                    </div>
                </div>
                <div class="admin-form-group">
                    <!-- spacer for alignment -->
                </div>
            </div>

            <div class="admin-form-row">
                <div class="admin-form-group">
                    <label for="name" class="admin-form-label">Full Name <span class="admin-required">*</span></label>
                    <input type="text" id="name" name="name" class="admin-form-input"
                           placeholder="Enter student's full name" required
                           value="<?= htmlspecialchars($_POST['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>
                <div class="admin-form-group">
                    <label for="email" class="admin-form-label">Email <span class="admin-required">*</span></label>
                    <input type="email" id="email" name="email" class="admin-form-input"
                           placeholder="student@example.com" required
                           value="<?= htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>
            </div>

            <div class="admin-form-row">
                <div class="admin-form-group">
                    <label for="phone" class="admin-form-label">Phone <span class="admin-required">*</span></label>
                    <input type="tel" id="phone" name="phone" class="admin-form-input"
                           placeholder="Enter phone number" required
                           value="<?= htmlspecialchars($_POST['phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                    <small style="color:#6b7280; font-size:0.78rem;">
                        <i class="fas fa-info-circle"></i> Password will be auto-generated (last 6 digits of phone)
                    </small>
                </div>
                <div class="admin-form-group">
                    <label for="father_name" class="admin-form-label">Father's Name</label>
                    <input type="text" id="father_name" name="father_name" class="admin-form-input"
                           placeholder="Enter father's name"
                           value="<?= htmlspecialchars($_POST['father_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>
            </div>

            <div class="admin-form-row">
                <div class="admin-form-group">
                    <label for="course_id" class="admin-form-label">Course <span class="admin-required">*</span></label>
                    <select id="course_id" name="course_id" class="admin-form-select" required>
                        <option value="">Select a course</option>
                        <?php foreach ($courses ?? [] as $c): ?>
                        <option value="<?= (int)($c['id'] ?? 0) ?>"
                                data-fee="<?= htmlspecialchars(number_format((float)($c['fee_amount'] ?? 0), 2), ENT_QUOTES, 'UTF-8') ?>"
                                <?= (($_POST['course_id'] ?? '') == ($c['id'] ?? '')) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['name'] ?? '', ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($c['duration'] ?? '', ENT_QUOTES, 'UTF-8') ?>)
                            &#8377; <?= htmlspecialchars(number_format((float)($c['fee_amount'] ?? 0), 2), ENT_QUOTES, 'UTF-8') ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="admin-form-group">
                    <label for="batch_id" class="admin-form-label">Batch</label>
                    <select id="batch_id" name="batch_id" class="admin-form-select">
                        <option value="">Select a batch (Optional)</option>
                        <?php foreach ($batches ?? [] as $b): ?>
                        <option value="<?= (int)($b['id'] ?? 0) ?>"
                                <?= (($_POST['batch_id'] ?? '') == ($b['id'] ?? '')) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($b['batch_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                            <?php if (!empty($b['start_time']) || !empty($b['end_time'])): ?>
                                (<?= htmlspecialchars($b['start_time'] ?? '', ENT_QUOTES) ?>-<?= htmlspecialchars($b['end_time'] ?? '', ENT_QUOTES) ?>)
                            <?php endif; ?>
                            [<?= htmlspecialchars(ucfirst($b['status'] ?? ''), ENT_QUOTES, 'UTF-8') ?>]
                        </option>
                        <?php endforeach; ?>
                        <?php if (empty($batches)): ?>
                        <option value="" disabled style="color:#9ca3af;">No batches available — create one first</option>
                        <?php endif; ?>
                    </select>
                </div>
            </div>

            <div class="admin-form-row">
                <div class="admin-form-group">
                    <label for="admission_date" class="admin-form-label">Admission Date</label>
                    <input type="date" id="admission_date" name="admission_date" class="admin-form-input"
                           value="<?= htmlspecialchars($_POST['admission_date'] ?? date('Y-m-d'), ENT_QUOTES, 'UTF-8') ?>">
                </div>
                <div class="admin-form-group">
                    <label for="dob" class="admin-form-label">Date of Birth</label>
                    <input type="date" id="dob" name="dob" class="admin-form-input"
                           value="<?= htmlspecialchars($_POST['dob'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>
            </div>

            <div class="admin-form-row">
                <div class="admin-form-group">
                    <label for="guardian_name" class="admin-form-label">Guardian Name</label>
                    <input type="text" id="guardian_name" name="guardian_name" class="admin-form-input"
                           placeholder="Enter guardian's name"
                           value="<?= htmlspecialchars($_POST['guardian_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>
                <div class="admin-form-group">
                    <label for="guardian_phone" class="admin-form-label">Guardian Phone</label>
                    <input type="tel" id="guardian_phone" name="guardian_phone" class="admin-form-input"
                           placeholder="Enter guardian's phone"
                           value="<?= htmlspecialchars($_POST['guardian_phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>
            </div>

            <div class="admin-form-group">
                <label for="address" class="admin-form-label">Address</label>
                <textarea id="address" name="address" class="admin-form-textarea" rows="3"
                          placeholder="Enter full address"><?= htmlspecialchars($_POST['address'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
            </div>

            <div class="admin-form-actions">
                <button type="submit" class="admin-btn admin-btn-primary">Add Student</button>
                <a href="<?= $bp ?>/branch/students" class="admin-btn admin-btn-outline">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
// Photo validation — max 50KB
function validatePhoto(input) {
    const errorEl = document.getElementById('photoError');
    const previewWrap = document.getElementById('photoPreviewWrap');
    const previewImg = document.getElementById('photoPreviewImg');

    if (input.files && input.files[0]) {
        const file = input.files[0];

        // Size check — 50KB = 50 * 1024 = 51200 bytes
        if (file.size > 51200) {
            errorEl.style.display = 'block';
            errorEl.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Photo must be under 50KB. Current size: ' + (file.size / 1024).toFixed(1) + 'KB';
            input.value = '';
            previewWrap.style.display = 'none';
            return false;
        }

        // Type check
        if (!file.type.match(/^image\/(jpeg|jpg|png)$/)) {
            errorEl.style.display = 'block';
            errorEl.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Only JPG and PNG images are allowed.';
            input.value = '';
            previewWrap.style.display = 'none';
            return false;
        }

        errorEl.style.display = 'none';

        // Show preview
        const reader = new FileReader();
        reader.onload = function(e) {
            previewImg.src = e.target.result;
            previewWrap.style.display = 'block';
        };
        reader.readAsDataURL(file);
    } else {
        errorEl.style.display = 'none';
        previewWrap.style.display = 'none';
    }
    return true;
}

// Preview admission form in a beautifully designed page with download link
function previewAdmissionForm() {
    const form = document.getElementById('admissionForm');
    if (!form) return;

    // Collect form values
    const name      = document.getElementById('name')?.value || '';
    const email     = document.getElementById('email')?.value || '';
    const phone     = document.getElementById('phone')?.value || '';
    const fatherName= document.getElementById('father_name')?.value || '';
    const dob       = document.getElementById('dob')?.value || '';
    const courseSel = document.getElementById('course_id');
    const course    = courseSel?.options[courseSel.selectedIndex]?.text || '';
    const batchSel  = document.getElementById('batch_id');
    const batch     = batchSel?.options[batchSel.selectedIndex]?.text || '';
    const admissionDate = document.getElementById('admission_date')?.value || '';
    const guardianName  = document.getElementById('guardian_name')?.value || '';
    const guardianPhone = document.getElementById('guardian_phone')?.value || '';
    const address   = document.getElementById('address')?.value || '';

    // Get photo as data URL
    const photoInput = document.getElementById('photo');
    let photoDataUrl = '';
    if (photoInput.files && photoInput.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            photoDataUrl = e.target.result;
            openPreviewWindow();
        };
        reader.readAsDataURL(photoInput.files[0]);
    } else {
        openPreviewWindow();
    }

    function openPreviewWindow() {
        const win = window.open('', '_blank');
        win.document.write(`
<!DOCTYPE html><html><head><title>Admission Form - ${name}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<style>
    body { font-family: 'Segoe UI', Arial, sans-serif; background: #f3f4f6; padding: 20px; color: #2c1e4a; }
    .preview-container { max-width: 800px; margin: 0 auto; background: #fff; border-radius: 12px; box-shadow: 0 4px 24px rgba(0,0,0,0.08); overflow: hidden; }
    .preview-header { background: linear-gradient(135deg, #16a085, #117a65); color: #fff; padding: 24px 32px; text-align: center; }
    .preview-header h1 { margin: 0; font-size: 1.8rem; font-weight: 700; }
    .preview-header p { margin: 6px 0 0; opacity: 0.9; font-size: 0.9rem; }
    .toolbar { background: #f8f4ff; padding: 14px 24px; border-bottom: 1px solid #e9ecef; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
    .toolbar-title { font-weight: 700; color: #6c3fe8; font-size: 1rem; }
    .toolbar-actions { display: flex; gap: 8px; flex-wrap: wrap; }
    .btn-download { background: #dc2626; color: #fff; padding: 8px 18px; border-radius: 6px; text-decoration: none; font-weight: 600; border: none; cursor: pointer; font-size: 0.88rem; }
    .btn-download:hover { background: #b91c1c; color: #fff; }
    .btn-print { background: #2563eb; color: #fff; padding: 8px 18px; border-radius: 6px; text-decoration: none; font-weight: 600; border: none; cursor: pointer; font-size: 0.88rem; }
    .btn-print:hover { background: #1d4ed8; color: #fff; }
    .btn-close { background: #6b7280; color: #fff; padding: 8px 18px; border-radius: 6px; text-decoration: none; font-weight: 600; font-size: 0.88rem; }
    .form-content { padding: 32px; }
    .form-title { text-align: center; background: #f8f4ff; color: #6c3fe8; padding: 12px; border-radius: 6px; margin-bottom: 24px; font-weight: 700; font-size: 1.1rem; letter-spacing: 1px; }
    .photo-section { text-align: center; margin-bottom: 24px; }
    .photo-box { width: 120px; height: 150px; border: 3px solid #16a085; border-radius: 8px; margin: 0 auto 8px; overflow: hidden; background: #f8f9fa; display: flex; align-items: center; justify-content: center; }
    .photo-box img { width: 100%; height: 100%; object-fit: cover; }
    .photo-box i { font-size: 3rem; color: #d0d5dd; }
    .photo-label { font-size: 0.78rem; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; }
    .detail-table { width: 100%; border-collapse: collapse; margin-bottom: 24px; }
    .detail-table td { padding: 12px 16px; border: 1px solid #e5e7eb; font-size: 0.92rem; }
    .detail-table td.label { font-weight: 600; background: #f8f4ff; color: #6c3fe8; width: 35%; text-transform: uppercase; font-size: 0.78rem; letter-spacing: 0.5px; }
    .detail-table td.value { color: #2c1e4a; }
    .terms { background: #fef3c7; padding: 16px 20px; border-left: 4px solid #d97706; margin-top: 24px; border-radius: 6px; }
    .terms h4 { margin: 0 0 10px 0; color: #b45309; font-size: 1rem; }
    .terms ol { margin: 0; padding-left: 20px; color: #92400e; font-size: 0.85rem; line-height: 1.7; }
    .sign-row { display: flex; justify-content: space-between; margin-top: 60px; padding: 0 20px; }
    .sign-box { text-align: center; width: 45%; }
    .sign-line { border-top: 1px solid #2c1e4a; margin-top: 50px; padding-top: 6px; font-size: 0.85rem; color: #6b7280; font-weight: 600; }
    .footer { text-align: center; margin-top: 32px; font-size: 0.78rem; color: #999; border-top: 1px solid #e5e7eb; padding-top: 14px; }
    @media print {
        body { background: #fff; padding: 0; }
        .preview-container { box-shadow: none; max-width: 100%; }
        .toolbar { display: none !important; }
        .form-content { padding: 20px; }
    }
</style></head><body>
    <div class="preview-container">
        <div class="preview-header">
            <h1>GMIND INSTITUTE</h1>
            <p>Student Admission Form</p>
        </div>

        <div class="toolbar">
            <div class="toolbar-title">
                <i class="fas fa-file-pdf"></i> Form Preview — Review the details below
            </div>
            <div class="toolbar-actions">
                <button class="btn-print" onclick="window.print()">
                    <i class="fas fa-print"></i> Print
                </button>
                <button class="btn-download" onclick="downloadAsPDF()">
                    <i class="fas fa-download"></i> Download PDF
                </button>
                <a href="javascript:window.close()" class="btn-close">
                    <i class="fas fa-times"></i> Close
                </a>
            </div>
        </div>

        <div class="form-content">
            <div class="form-title">ADMISSION FORM</div>

            <div class="photo-section">
                <div class="photo-box">
                    ${photoDataUrl ? '<img src="' + photoDataUrl + '" alt="Student Photo">' : '<i class="fas fa-user"></i>'}
                </div>
                <div class="photo-label">Student Photo</div>
            </div>

            <table class="detail-table">
                <tr><td class="label">Full Name</td><td class="value">${name || '—'}</td></tr>
                <tr><td class="label">Email</td><td class="value">${email || '—'}</td></tr>
                <tr><td class="label">Phone</td><td class="value">${phone || '—'}</td></tr>
                <tr><td class="label">Father's Name</td><td class="value">${fatherName || '—'}</td></tr>
                <tr><td class="label">Date of Birth</td><td class="value">${dob || '—'}</td></tr>
                <tr><td class="label">Course</td><td class="value">${course || '—'}</td></tr>
                <tr><td class="label">Batch</td><td class="value">${batch || '—'}</td></tr>
                <tr><td class="label">Admission Date</td><td class="value">${admissionDate || '—'}</td></tr>
                <tr><td class="label">Guardian Name</td><td class="value">${guardianName || '—'}</td></tr>
                <tr><td class="label">Guardian Phone</td><td class="value">${guardianPhone || '—'}</td></tr>
                <tr><td class="label">Address</td><td class="value">${address || '—'}</td></tr>
            </table>

            <div class="terms">
                <h4><i class="fas fa-file-contract"></i> TERMS & CONDITIONS</h4>
                <ol>
                    <li>Fee once paid will <strong>NOT</strong> be refundable under any circumstances.</li>
                    <li>Student must maintain 75% attendance to be eligible for examination.</li>
                    <li>Certificate/Marksheet will be issued only after full fee payment and course completion.</li>
                    <li>The information provided above is true and correct to the best of my knowledge.</li>
                    <li>Institute reserves the right to cancel admission in case of false information.</li>
                </ol>
            </div>

            <div class="sign-row">
                <div class="sign-box">
                    <div class="sign-line">Student / Guardian Signature</div>
                </div>
                <div class="sign-box">
                    <div class="sign-line">Authorized Signatory</div>
                </div>
            </div>

            <div class="footer">
                Generated on <?= date('d M Y, h:i A') ?> • GMIND Institute Management System
            </div>
        </div>
    </div>

    <script>
        function downloadAsPDF() {
            // Use browser's print dialog — user can save as PDF
            window.print();
        }
    </script>
</body></html>
        `);
        win.document.close();
    }
}
</script>
