<?php
/**
 * Super Admin — Create Result Form (Single Page, Auto-Approve)
 *
 * Upload to: /gmind/super-admin/Views/cert_gen/create.php
 *
 * Combines student details + result entry + payment in ONE form.
 * On submit, status is set to 'generated' (auto-approved) and both
 * certificate + marksheet PDFs are generated immediately using the
 * Pattern System.
 *
 * Institute Name: GMIND INSTITUTE SULTANPUR (hardcoded)
 * Branch Code:    GMBR01 (hardcoded)
 */

$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$csrf = htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8');

// Default subjects (if course has no subjects defined)
$defaultSubjects = [
    ['name' => 'Theory',   'max_marks' => 100],
    ['name' => 'Practical','max_marks' => 100],
];

// Next month as default issue date
$nextMonth = date('Y-m-d', strtotime('first day of next month'));
?>
<style>
    .sa-create-form { background:#fff; border-radius:12px; padding:28px; box-shadow:0 2px 12px rgba(0,0,0,0.04); margin-bottom:24px; }
    .sa-create-form .form-section { margin-bottom:28px; padding-bottom:24px; border-bottom:1px solid #e9ecef; }
    .sa-create-form .form-section:last-child { border-bottom:none; margin-bottom:0; padding-bottom:0; }
    .sa-section-title { color:#6c3fe8; font-weight:700; font-size:1.05rem; margin-bottom:18px; display:flex; align-items:center; gap:8px; }
    .sa-section-title i { color:#6c3fe8; }
    .sa-info-banner { background:linear-gradient(135deg, rgba(108,63,232,0.08), rgba(74,45,184,0.04)); border-left:4px solid #6c3fe8; padding:14px 18px; border-radius:8px; margin-bottom:24px; display:flex; align-items:center; gap:14px; }
    .sa-info-banner i { color:#6c3fe8; font-size:1.5rem; }
    .sa-info-banner-text { font-size:0.9rem; color:#2c1e4a; }
    .sa-info-banner-text strong { color:#6c3fe8; }
    .subject-row { display:grid; grid-template-columns: 2fr 1fr 1fr auto; gap:10px; align-items:end; margin-bottom:12px; }
    .subject-row .remove-btn { background:#e84118; color:#fff; border:none; border-radius:8px; padding:10px 14px; cursor:pointer; font-weight:600; }
    .subject-row .remove-btn:hover { background:#c3271a; }
    .btn-add-subject { background:rgba(108,63,232,0.1); color:#6c3fe8; border:1px dashed #6c3fe8; padding:10px 16px; border-radius:8px; cursor:pointer; font-weight:600; }
    .btn-add-subject:hover { background:rgba(108,63,232,0.2); }
    .btn-submit { background:#6c3fe8; color:#fff; padding:14px 32px; border:none; border-radius:8px; font-weight:700; font-size:1rem; cursor:pointer; }
    .btn-submit:hover { background:#4a2db8; }
    .form-label { font-weight:600; color:#2c1e4a; font-size:0.9rem; margin-bottom:6px; }
    .form-control, .form-select { border-radius:8px; padding:10px 12px; border:1px solid #d0d5dd; }
    .form-control:focus, .form-select:focus { border-color:#6c3fe8; box-shadow:0 0 0 3px rgba(108,63,232,0.1); }
    .required-mark { color:#e84118; margin-left:2px; }
    .stats-card { background:#fff; border-radius:12px; padding:18px; text-align:center; box-shadow:0 2px 8px rgba(0,0,0,0.04); }
    .stats-card .stats-num { font-size:1.6rem; font-weight:700; color:#6c3fe8; }
    .stats-card .stats-label { font-size:0.85rem; color:#667085; }
</style>

<div class="container-fluid">
    <!-- Hero Banner -->
    <div class="sa-info-banner">
        <i class="fas fa-bolt"></i>
        <div class="sa-info-banner-text">
            <strong>Auto-Approve Mode:</strong> Submitting this form will immediately generate <strong>both Certificate + Marksheet PDFs</strong> with status = <strong>Generated</strong>. No approval workflow needed.<br>
            Institute Name on PDF: <strong>GMIND INSTITUTE SULTANPUR</strong> &nbsp;|&nbsp; Branch Code: <strong>GMBR01</strong>
        </div>
    </div>

    <!-- Quick Stats -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-num"><?= htmlspecialchars($stats['total'] ?? 0, ENT_QUOTES) ?></div>
                <div class="stats-label">Total Generated</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-num"><?= htmlspecialchars($stats['generated'] ?? 0, ENT_QUOTES) ?></div>
                <div class="stats-label">Auto-Approved</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-num"><?= htmlspecialchars($stats['pending'] ?? 0, ENT_QUOTES) ?></div>
                <div class="stats-label">Pending (should be 0)</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="stats-num">GMBR01</div>
                <div class="stats-label">Default Branch Code</div>
            </div>
        </div>
    </div>

    <form method="POST" action="<?= $bp ?>/super-admin/cert-gen/store" class="sa-create-form" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">

        <!-- ─── Section 1: Student Details ─────────────────────────────── -->
        <div class="form-section">
            <h3 class="sa-section-title"><i class="fas fa-user-graduate"></i> Student Details</h3>
            <div class="row">
                <!-- Photo Upload (right column on top) -->
                <div class="col-md-3 mb-3 text-center">
                    <label class="form-label">Student Photo</label>
                    <div id="photoPreviewWrap" style="width:100%; max-width:160px; margin:0 auto 10px; aspect-ratio:3/4; border:2px dashed #d0d5dd; border-radius:8px; overflow:hidden; display:flex; align-items:center; justify-content:center; background:#f8f9fa;">
                        <img id="photoPreview" src="" style="display:none; width:100%; height:100%; object-fit:cover;">
                        <i class="fas fa-user" style="font-size:3rem; color:#d0d5dd;" id="photoPlaceholder"></i>
                    </div>
                    <input type="file" name="photo" id="photoInput" accept="image/jpeg,image/png,image/gif,image/webp" class="form-control form-control-sm">
                    <small class="text-muted d-block mt-1">JPG/PNG, max 5MB. Will appear on certificate.</small>
                </div>

                <div class="col-md-9">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Student Name <span class="required-mark">*</span></label>
                            <input type="text" name="name" class="form-control" required value="<?= htmlspecialchars($_POST['name'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Father's Name <span class="required-mark">*</span></label>
                            <input type="text" name="father_name" class="form-control" required value="<?= htmlspecialchars($_POST['father_name'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Mother's Name</label>
                            <input type="text" name="mother_name" class="form-control" value="<?= htmlspecialchars($_POST['mother_name'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Date of Birth <span class="required-mark">*</span></label>
                            <input type="date" name="dob" class="form-control" required value="<?= htmlspecialchars($_POST['dob'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Email <span class="required-mark">*</span></label>
                            <input type="email" name="email" class="form-control" required value="<?= htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Mobile Number <span class="required-mark">*</span></label>
                            <input type="tel" name="phone" class="form-control" required pattern="[0-9+\-\s]{10,15}" value="<?= htmlspecialchars($_POST['phone'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-12 mb-3">
                            <label class="form-label">Address</label>
                            <input type="text" name="address" class="form-control" value="<?= htmlspecialchars($_POST['address'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">City</label>
                            <input type="text" name="city" class="form-control" value="<?= htmlspecialchars($_POST['city'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">State</label>
                            <input type="text" name="state" class="form-control" value="<?= htmlspecialchars($_POST['state'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">PIN Code</label>
                            <input type="text" name="pin_code" class="form-control" value="<?= htmlspecialchars($_POST['pin_code'] ?? '', ENT_QUOTES) ?>">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ─── Section 2: Course & Session ─────────────────────────────── -->
        <div class="form-section">
            <h3 class="sa-section-title"><i class="fas fa-book"></i> Course & Session</h3>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Course <span class="required-mark">*</span></label>
                    <select name="course_id" id="courseSelect" class="form-select" required>
                        <option value="">— Select Course —</option>
                        <?php foreach ($courses as $c): ?>
                            <option value="<?= (int)$c['id'] ?>"
                                data-duration="<?= htmlspecialchars($c['duration'] ?? '6 Months', ENT_QUOTES) ?>"
                                data-subjects="<?= htmlspecialchars($c['subjects'] ?? '[]', ENT_QUOTES) ?>"
                                <?= ((int)($_POST['course_id'] ?? 0) === (int)$c['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($c['name'] ?? '', ENT_QUOTES) ?>
                                (<?= htmlspecialchars($c['duration'] ?? '', ENT_QUOTES) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-muted">Subjects will auto-load based on course selection.</small>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Completion Month <span class="required-mark">*</span></label>
                    <select name="completion_month" class="form-select" required>
                        <option value="">— Select Month —</option>
                        <?php foreach ($months as $val => $lbl): ?>
                            <option value="<?= htmlspecialchars($val, ENT_QUOTES) ?>" <?= (($_POST['completion_month'] ?? '') === $val) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($lbl, ENT_QUOTES) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-muted">From-Month is auto-calculated from Completion Month − (Duration − 1) months (inclusive).</small>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Issue Date</label>
                    <input type="date" name="issue_date" class="form-control" value="<?= htmlspecialchars($_POST['issue_date'] ?? $nextMonth, ENT_QUOTES) ?>">
                </div>
            </div>
        </div>

        <!-- ─── Section 3: Subjects & Marks ─────────────────────────────── -->
        <div class="form-section">
            <h3 class="sa-section-title"><i class="fas fa-list-ol"></i> Subjects & Marks</h3>
            <div id="subjectsContainer">
                <?php
                $displaySubjects = $defaultSubjects;
                if (!empty($_POST['subject_name'])) {
                    $displaySubjects = [];
                    for ($i = 0; $i < count($_POST['subject_name']); $i++) {
                        $displaySubjects[] = [
                            'name' => $_POST['subject_name'][$i],
                            'max_marks' => $_POST['max_marks'][$i] ?? 100,
                        ];
                    }
                }
                foreach ($displaySubjects as $i => $subj):
                ?>
                <div class="subject-row">
                    <div>
                        <label class="form-label">Subject <?= $i + 1 ?></label>
                        <input type="text" name="subject_name[]" class="form-control" required
                               value="<?= htmlspecialchars($subj['name'] ?? '', ENT_QUOTES) ?>">
                    </div>
                    <div>
                        <label class="form-label">Max Marks</label>
                        <input type="number" name="max_marks[]" class="form-control" min="1" max="100" required
                               value="<?= htmlspecialchars($subj['max_marks'] ?? 100, ENT_QUOTES) ?>">
                    </div>
                    <div>
                        <label class="form-label">Obtained Marks</label>
                        <input type="number" name="obtained_marks[]" class="form-control" min="0" max="100" required
                               value="<?= htmlspecialchars($_POST['obtained_marks'][$i] ?? '', ENT_QUOTES) ?>"
                               oninput="autoCap(this)">
                    </div>
                    <div>
                        <button type="button" class="remove-btn" onclick="removeSubject(this)"><i class="fas fa-times"></i></button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <button type="button" class="btn-add-subject" onclick="addSubject()">
                <i class="fas fa-plus"></i> Add Subject
            </button>
            <div class="mt-3 p-3" style="background:#f8f9fa;border-radius:8px;">
                <div class="row">
                    <div class="col-md-4">
                        <strong>Total Marks:</strong> <span id="totalMax">0</span>
                    </div>
                    <div class="col-md-4">
                        <strong>Obtained:</strong> <span id="totalObt">0</span>
                    </div>
                    <div class="col-md-4">
                        <strong>Percentage:</strong> <span id="percentage">0%</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- ─── Section 4: Payment ──────────────────────────────────────── -->
        <div class="form-section">
            <h3 class="sa-section-title"><i class="fas fa-money-bill-wave"></i> Payment Details</h3>
            <p class="text-muted small"><i class="fas fa-info-circle"></i> Super Admin-generated results do NOT deduct from any wallet. The payment info below is for record-keeping only.</p>
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">Payment Mode</label>
                    <select name="payment_mode" id="paymentMode" class="form-select">
                        <option value="offline" <?= (($_POST['payment_mode'] ?? '') === 'offline') ? 'selected' : '' ?>>Offline (Cash)</option>
                        <option value="online"  <?= (($_POST['payment_mode'] ?? '') === 'online')  ? 'selected' : '' ?>>Online (UPI)</option>
                        <option value="upi"     <?= (($_POST['payment_mode'] ?? '') === 'upi')     ? 'selected' : '' ?>>UPI Direct</option>
                        <option value="wallet"  <?= (($_POST['payment_mode'] ?? '') === 'wallet')  ? 'selected' : '' ?>>Wallet</option>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Total Amount (₹)</label>
                    <input type="number" name="total_amount" class="form-control" min="0" step="0.01"
                           value="<?= htmlspecialchars($_POST['total_amount'] ?? '200', ENT_QUOTES) ?>">
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Transaction ID</label>
                    <input type="text" name="transaction_id" class="form-control"
                           value="<?= htmlspecialchars($_POST['transaction_id'] ?? '', ENT_QUOTES) ?>">
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Payment Date</label>
                    <input type="date" name="payment_date" class="form-control"
                           value="<?= htmlspecialchars($_POST['payment_date'] ?? date('Y-m-d'), ENT_QUOTES) ?>">
                </div>
            </div>
        </div>

        <!-- ─── Submit ──────────────────────────────────────────────────── -->
        <div class="text-end">
            <a href="<?= $bp ?>/super-admin/cert-gen" class="btn btn-secondary me-2">Cancel</a>
            <button type="submit" class="btn-submit">
                <i class="fas fa-bolt"></i> Submit & Auto-Generate PDFs
            </button>
        </div>
    </form>
</div>

<script>
// Auto-load subjects from course selection
document.getElementById('courseSelect')?.addEventListener('change', function() {
    const opt = this.options[this.selectedIndex];
    if (!opt || !opt.dataset.subjects) return;
    try {
        const subjects = JSON.parse(opt.dataset.subjects || '[]');
        if (!Array.isArray(subjects) || subjects.length === 0) return;
        if (!confirm('Load ' + subjects.length + ' subjects from this course? This will replace current subjects.')) return;
        const container = document.getElementById('subjectsContainer');
        container.innerHTML = '';
        subjects.forEach((s, i) => {
            addSubject(s.name || ('Subject ' + (i+1)), s.max_marks || 100);
        });
        recalcTotals();
    } catch (e) {
        console.error('Failed to parse subjects:', e);
    }
});

function addSubject(name, max) {
    name = name || '';
    max  = max  || 100;
    const container = document.getElementById('subjectsContainer');
    const idx = container.children.length;
    const div = document.createElement('div');
    div.className = 'subject-row';
    div.innerHTML = `
        <div>
            <label class="form-label">Subject ${idx + 1}</label>
            <input type="text" name="subject_name[]" class="form-control" required value="${name}">
        </div>
        <div>
            <label class="form-label">Max Marks</label>
            <input type="number" name="max_marks[]" class="form-control" min="1" max="100" required value="${max}" oninput="recalcTotals()">
        </div>
        <div>
            <label class="form-label">Obtained Marks</label>
            <input type="number" name="obtained_marks[]" class="form-control" min="0" max="100" required value="" oninput="autoCap(this); recalcTotals()">
        </div>
        <div>
            <button type="button" class="remove-btn" onclick="removeSubject(this)"><i class="fas fa-times"></i></button>
        </div>
    `;
    container.appendChild(div);
    recalcTotals();
}

function removeSubject(btn) {
    const container = document.getElementById('subjectsContainer');
    if (container.children.length <= 1) {
        alert('At least one subject is required.');
        return;
    }
    btn.closest('.subject-row').remove();
    recalcTotals();
}

function autoCap(input) {
    const max = parseFloat(input.closest('.subject-row').querySelector('input[name="max_marks[]"]').value) || 100;
    let val = parseFloat(input.value) || 0;
    if (val > max) {
        input.value = max;
        val = max;
    }
    if (val < 0) {
        input.value = 0;
        val = 0;
    }
    recalcTotals();
}

function recalcTotals() {
    const maxInputs = document.querySelectorAll('input[name="max_marks[]"]');
    const obtInputs = document.querySelectorAll('input[name="obtained_marks[]"]');
    let totalMax = 0, totalObt = 0;
    maxInputs.forEach((m, i) => {
        const mv = parseFloat(m.value) || 0;
        const ov = parseFloat(obtInputs[i]?.value || 0) || 0;
        totalMax += mv;
        totalObt += ov;
    });
    document.getElementById('totalMax').textContent = totalMax;
    document.getElementById('totalObt').textContent  = totalObt;
    const pct = totalMax > 0 ? ((totalObt / totalMax) * 100).toFixed(2) : 0;
    document.getElementById('percentage').textContent = pct + '%';
}

document.addEventListener('DOMContentLoaded', recalcTotals);

// Photo preview
document.getElementById('photoInput')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) {
        alert('Please select an image file.');
        e.target.value = '';
        return;
    }
    if (file.size > 5 * 1024 * 1024) {
        alert('Image size must be less than 5MB.');
        e.target.value = '';
        return;
    }
    const reader = new FileReader();
    reader.onload = function(ev) {
        const img = document.getElementById('photoPreview');
        const placeholder = document.getElementById('photoPlaceholder');
        img.src = ev.target.result;
        img.style.display = 'block';
        if (placeholder) placeholder.style.display = 'none';
    };
    reader.readAsDataURL(file);
});
</script>
