<?php
/**
 * Branch Admin — Create Result for Student
 *
 * Phase 5 flow:
 *   1. Branch selects completion month from a dropdown (last 2 years of months)
 *   2. Subject list auto-loads from the student's course
 *   3. Branch can:
 *      - Enter marks manually per subject, OR
 *      - Click "🎲 Random Marks" to auto-fill random marks, OR
 *      - Select a target grade (A+/A/B+/B/C/D) → system auto-calculates marks to fit that grade
 *   4. Branch selects payment mode (Online ₹200 from wallet / Offline with transaction ID)
 *   5. Submit → request goes to Super Admin → Super Admin verifies → approves →
 *      PDFs generated for both Certificate + Marksheet → Branch can download
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$student = $student ?? [];
$course = $course ?? [];
$subjects = $subjects ?? [];
$csrfToken = $csrfToken ?? [];

// Build month dropdown — last 2 years (24 months) ending current month
$months = [];
$current = strtotime('first day of this month');
for ($i = 0; $i < 24; $i++) {
    $ts = strtotime("-{$i} months", $current);
    $value = date('Y-m', $ts);          // e.g. "2026-06"
    $label = date('F Y', $ts);          // e.g. "June 2026"
    $months[$value] = $label;
}
?>
<div class="admin-section">
    <div style="margin-bottom:14px;">
        <a href="<?= $bp ?>/branch/students/<?= (int)$student['id'] ?>" style="color:#16a085;text-decoration:none;font-size:0.85rem;">← Back to Student</a>
    </div>

    <!-- Student info banner -->
    <div style="background:linear-gradient(135deg,#0d3b3b,#16a085);color:#fff;border-radius:12px;padding:18px;margin-bottom:18px;">
        <h2 style="margin:0;font-size:1.1rem;">🎓 Create Result & Generate Certificate + Marksheet</h2>
        <p style="margin:6px 0 0;opacity:0.9;font-size:0.84rem;">
            Student: <strong><?= htmlspecialchars($student['name'] ?? '', ENT_QUOTES, 'UTF-8') ?></strong> ·
            Enrollment: <strong><?= htmlspecialchars($student['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?></strong> ·
            Course: <strong><?= htmlspecialchars($course['name'] ?? '', ENT_QUOTES, 'UTF-8') ?></strong>
        </p>
    </div>

    <form method="POST" action="<?= $bp ?>/branch/students/<?= (int)$student['id'] ?>/create-result" id="resultForm">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">

        <!-- Step 1: Completion Month -->
        <div style="background:#fff;border-radius:12px;padding:24px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <h3 style="margin:0 0 6px;font-size:1.05rem;color:#0d3b3b;">Step 1: Completion Month</h3>
            <p style="margin:0 0 14px;font-size:0.82rem;color:#666;">Select the month when the student completed the course. This will appear on the certificate as "TO: Month Year".</p>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div>
                    <label style="display:block;font-size:0.82rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Completion Month *</label>
                    <select name="completion_month" id="completionMonth" required onchange="updateFromDate()" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.88rem;">
                        <option value="">— Select Month —</option>
                        <?php foreach ($months as $val => $lbl): ?>
                            <option value="<?= htmlspecialchars($val, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($lbl, ENT_QUOTES, 'UTF-8') ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label style="display:block;font-size:0.82rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Session From (auto-calculated)</label>
                    <input type="text" id="fromDateDisplay" readonly placeholder="e.g. JAN 2025" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.88rem;background:#f9f9f9;color:#666;">
                    <input type="hidden" name="from_month" id="fromMonthInput">
                </div>
            </div>
        </div>

        <!-- Step 2: Subject Marks -->
        <div style="background:#fff;border-radius:12px;padding:24px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px;">
                <div>
                    <h3 style="margin:0;font-size:1.05rem;color:#0d3b3b;">Step 2: Subject-wise Marks</h3>
                    <p style="margin:4px 0 0;font-size:0.82rem;color:#666;">Enter marks per subject, OR use the quick-fill options below.</p>
                </div>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <!-- Target Grade selector -->
                    <select id="targetGrade" onchange="applyGrade()" style="padding:8px 12px;border:1px solid #16a085;border-radius:6px;font-size:0.82rem;background:#eafaf1;color:#0d3b3b;font-weight:600;">
                        <option value="">🎯 Auto-grade: pick grade</option>
                        <option value="A+">A+ (≥90%)</option>
                        <option value="A">A (80-89%)</option>
                        <option value="B+">B+ (70-79%)</option>
                        <option value="B">B (60-69%)</option>
                        <option value="C">C (45-59%)</option>
                        <option value="D">D (33-44%)</option>
                    </select>
                    <button type="button" onclick="randomMarks()" style="padding:8px 14px;background:#f39c12;color:#fff;border:none;border-radius:6px;font-size:0.82rem;font-weight:600;cursor:pointer;">🎲 Random Marks</button>
                    <button type="button" onclick="clearMarks()" style="padding:8px 14px;background:#e84118;color:#fff;border:none;border-radius:6px;font-size:0.82rem;font-weight:600;cursor:pointer;">✕ Clear</button>
                </div>
            </div>

            <?php if (empty($subjects)): ?>
                <div style="text-align:center;padding:30px;color:#999;background:#f9f9f9;border-radius:8px;">
                    <p style="margin:0;">No subjects defined for this course. Please ask the Super Admin to add subjects to the course.</p>
                </div>
            <?php else: ?>
                <table style="width:100%;border-collapse:collapse;font-size:0.86rem;">
                    <thead><tr style="background:#f8f9fa;border-bottom:2px solid #dee2e6;">
                        <th style="padding:10px;text-align:left;">Subject</th>
                        <th style="padding:10px;text-align:center;width:100px;">Max Marks</th>
                        <th style="padding:10px;text-align:center;width:120px;">Obtained Marks</th>
                        <th style="padding:10px;text-align:center;width:80px;">%</th>
                    </tr></thead>
                    <tbody id="subjectsBody">
                        <?php foreach ($subjects as $i => $sub):
                            $max = (int)($sub['max_marks'] ?? 100);
                        ?>
                        <tr>
                            <td style="padding:10px;">
                                <input type="hidden" name="subject_name[]" value="<?= htmlspecialchars($sub['name'] ?? 'Subject '.($i+1), ENT_QUOTES, 'UTF-8') ?>">
                                <?= htmlspecialchars($sub['name'] ?? 'Subject '.($i+1), ENT_QUOTES, 'UTF-8') ?>
                            </td>
                            <td style="padding:10px;text-align:center;">
                                <input type="hidden" name="max_marks[]" value="<?= $max ?>" class="max-marks">
                                <strong><?= $max ?></strong>
                            </td>
                            <td style="padding:10px;text-align:center;">
                                <input type="number" name="obtained_marks[]" value="" placeholder="0" min="0" max="<?= $max ?>" class="obtained-marks" oninput="calcTotal()" style="width:90px;padding:6px;border:1px solid #ddd;border-radius:4px;text-align:center;font-size:0.84rem;">
                            </td>
                            <td style="padding:10px;text-align:center;" class="subject-pct">—</td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr style="background:#eafaf1;font-weight:700;">
                            <td style="padding:10px;text-align:right;">TOTAL</td>
                            <td style="padding:10px;text-align:center;" id="totalMax">0</td>
                            <td style="padding:10px;text-align:center;color:#16a085;" id="totalObtained">0</td>
                            <td style="padding:10px;text-align:center;color:#27ae60;" id="totalPct">0%</td>
                        </tr>
                    </tfoot>
                </table>

                <!-- Auto-calculated grade/division display -->
                <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:14px;">
                    <div style="text-align:center;padding:10px;background:#eaf0fb;border-radius:8px;">
                        <div style="font-size:1.3rem;font-weight:700;color:#1a4fa0;" id="resultGrade">—</div>
                        <div style="font-size:0.72rem;color:#999;">Grade</div>
                    </div>
                    <div style="text-align:center;padding:10px;background:#eafaf1;border-radius:8px;">
                        <div style="font-size:1.3rem;font-weight:700;color:#27ae60;" id="resultDivision">—</div>
                        <div style="font-size:0.72rem;color:#999;">Division</div>
                    </div>
                    <div style="text-align:center;padding:10px;background:#fff5e6;border-radius:8px;">
                        <div style="font-size:1.3rem;font-weight:700;color:#f39c12;" id="resultStatus">—</div>
                        <div style="font-size:0.72rem;color:#999;">Status</div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <?php if (!empty($subjects)): ?>
        <!-- Step 3: Payment -->
        <div style="background:#fff;border-radius:12px;padding:24px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <h3 style="margin:0 0 6px;font-size:1.05rem;color:#0d3b3b;">Step 3: Payment (₹200 for Certificate + Marksheet combined)</h3>
            <p style="margin:0 0 14px;font-size:0.82rem;color:#666;">
                <strong>Online</strong> = ₹200 deducted from wallet → request sent to Super Admin → approved → PDFs generated.
                <strong>Offline</strong> = enter transaction ID → Super Admin verifies → approves → PDFs generated.
            </p>
            <div style="display:flex;gap:10px;">
                <label class="pay-opt" style="flex:1;padding:12px;border:2px solid #16a085;border-radius:8px;cursor:pointer;text-align:center;background:#eafaf1;" onclick="selectPayment('online')">
                    <input type="radio" name="payment_mode" value="online" checked style="display:none;">
                    <div style="font-size:1.3rem;">💳</div>
                    <div style="font-weight:600;font-size:0.85rem;color:#333;">Online (Wallet ₹200)</div>
                    <div style="font-size:0.72rem;color:#27ae60;margin-top:2px;">Auto-deduct + request</div>
                </label>
                <label class="pay-opt" style="flex:1;padding:12px;border:2px solid #e0e0e0;border-radius:8px;cursor:pointer;text-align:center;" onclick="selectPayment('offline')">
                    <input type="radio" name="payment_mode" value="offline" style="display:none;">
                    <div style="font-size:1.3rem;">🏦</div>
                    <div style="font-weight:600;font-size:0.85rem;color:#333;">Offline (UPI/Bank)</div>
                    <div style="font-size:0.72rem;color:#f39c12;margin-top:2px;">Enter Txn ID</div>
                </label>
            </div>

            <!-- Offline payment details -->
            <div id="offlinePaymentBox" style="display:none;margin-top:14px;padding:14px;background:#fff8e1;border:1px solid #f5d68b;border-radius:8px;">
                <h4 style="margin:0 0 8px;font-size:0.88rem;color:#b8731a;">📋 Offline Payment Details</h4>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div>
                        <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Transaction ID / UTR No. *</label>
                        <input type="text" name="transaction_id" id="transactionId" placeholder="e.g. 9876543210" style="width:100%;padding:9px 12px;border:1px solid #ddd;border-radius:6px;font-size:0.86rem;font-family:monospace;">
                    </div>
                    <div>
                        <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Payment Date</label>
                        <input type="date" name="payment_date" value="<?= date('Y-m-d') ?>" style="width:100%;padding:9px 12px;border:1px solid #ddd;border-radius:6px;font-size:0.86rem;">
                    </div>
                </div>
            </div>

            <div style="text-align:center;margin-top:14px;padding:14px;background:linear-gradient(135deg,#0d3b3b,#16a085);color:#fff;border-radius:8px;">
                <div style="font-size:0.82rem;opacity:0.85;">Total Cost (Certificate + Marksheet combined)</div>
                <div style="font-size:2rem;font-weight:700;">₹200</div>
            </div>
            <input type="hidden" name="total_amount" value="200">
        </div>

        <!-- Submit -->
        <div style="display:flex;gap:12px;justify-content:flex-end;">
            <a href="<?= $bp ?>/branch/students/<?= (int)$student['id'] ?>" style="padding:12px 24px;border:1px solid #ddd;border-radius:8px;text-decoration:none;color:#666;font-weight:600;font-size:0.9rem;">Cancel</a>
            <button type="submit" style="padding:12px 32px;background:linear-gradient(135deg,#16a085,#117a65);color:#fff;border:none;border-radius:8px;font-weight:600;font-size:0.9rem;cursor:pointer;">
                📤 Submit Result for Approval
            </button>
        </div>
        <?php endif; ?>
    </form>
</div>

<script>
// ─── Update "From" date when completion month changes ────────
function updateFromDate() {
    var completion = document.getElementById('completionMonth').value;
    if (!completion) {
        document.getElementById('fromDateDisplay').value = '';
        document.getElementById('fromMonthInput').value = '';
        return;
    }
    // From = 12 months before completion (1-year course default)
    var parts = completion.split('-');
    var year = parseInt(parts[0]);
    var month = parseInt(parts[1]);
    // Subtract 11 months (so Jan 2025 → Dec 2025 = 12 months span)
    var fromDate = new Date(year, month - 1 - 11, 1);
    var fromLabel = fromDate.toLocaleString('en-US', {month: 'short', year: 'numeric'}).toUpperCase();
    var fromValue = fromDate.getFullYear() + '-' + String(fromDate.getMonth() + 1).padStart(2, '0');
    document.getElementById('fromDateDisplay').value = fromLabel;
    document.getElementById('fromMonthInput').value = fromValue;
}

// ─── Calculate totals ─────────────────────────────────────────
function calcTotal() {
    var obt = document.querySelectorAll('.obtained-marks');
    var max = document.querySelectorAll('.max-marks');
    var tObt = 0, tMax = 0;
    for (var i = 0; i < obt.length; i++) {
        var o = parseInt(obt[i].value) || 0;
        var m = parseInt(max[i].value) || 100;
        tObt += o;
        tMax += m;
        // Update per-subject %
        var pct = m > 0 ? ((o / m) * 100).toFixed(1) : 0;
        var pctCell = obt[i].closest('tr').querySelector('.subject-pct');
        if (pctCell) pctCell.textContent = pct + '%';
    }
    document.getElementById('totalObtained').textContent = tObt;
    document.getElementById('totalMax').textContent = tMax;
    var totalPct = tMax > 0 ? ((tObt / tMax) * 100).toFixed(1) : 0;
    document.getElementById('totalPct').textContent = totalPct + '%';
    // Grade + division
    var g = 'F';
    if (totalPct >= 90) g = 'A+';
    else if (totalPct >= 80) g = 'A';
    else if (totalPct >= 70) g = 'B+';
    else if (totalPct >= 60) g = 'B';
    else if (totalPct >= 45) g = 'C';
    else if (totalPct >= 33) g = 'D';
    var d = 'Fail';
    if (totalPct >= 60) d = 'First';
    else if (totalPct >= 45) d = 'Second';
    else if (totalPct >= 33) d = 'Third';
    var st = totalPct >= 33 ? 'PASS ✓' : 'FAIL ✗';
    document.getElementById('resultGrade').textContent = g;
    document.getElementById('resultDivision').textContent = d;
    document.getElementById('resultStatus').textContent = st;
    document.getElementById('resultStatus').style.color = totalPct >= 33 ? '#27ae60' : '#e84118';
}

// ─── Random marks ─────────────────────────────────────────────
function randomMarks() {
    var obt = document.querySelectorAll('.obtained-marks');
    var max = document.querySelectorAll('.max-marks');
    for (var i = 0; i < obt.length; i++) {
        var m = parseInt(max[i].value) || 100;
        // Random between 50% and 95% of max
        var r = Math.random() * 0.45 + 0.50;
        obt[i].value = Math.round(m * r);
    }
    calcTotal();
}

// ─── Apply target grade ───────────────────────────────────────
function applyGrade() {
    var grade = document.getElementById('targetGrade').value;
    if (!grade) return;
    var ranges = {
        'A+': [0.90, 0.99],
        'A':  [0.80, 0.89],
        'B+': [0.70, 0.79],
        'B':  [0.60, 0.69],
        'C':  [0.45, 0.59],
        'D':  [0.33, 0.44]
    };
    var range = ranges[grade];
    if (!range) return;
    var obt = document.querySelectorAll('.obtained-marks');
    var max = document.querySelectorAll('.max-marks');
    for (var i = 0; i < obt.length; i++) {
        var m = parseInt(max[i].value) || 100;
        // Random within the grade's percentage range
        var r = Math.random() * (range[1] - range[0]) + range[0];
        obt[i].value = Math.round(m * r);
    }
    calcTotal();
}

// ─── Clear marks ──────────────────────────────────────────────
function clearMarks() {
    document.querySelectorAll('.obtained-marks').forEach(function(el) { el.value = ''; });
    calcTotal();
}

// ─── Payment mode selection ───────────────────────────────────
function selectPayment(mode) {
    document.querySelectorAll('.pay-opt').forEach(function(e) {
        e.style.background = '#fff';
        e.style.borderColor = '#e0e0e0';
    });
    var selected = event.currentTarget;
    if (mode === 'online') {
        selected.style.background = '#eafaf1';
        selected.style.borderColor = '#16a085';
        document.getElementById('offlinePaymentBox').style.display = 'none';
    } else {
        selected.style.background = '#fff8e1';
        selected.style.borderColor = '#f39c12';
        document.getElementById('offlinePaymentBox').style.display = 'block';
    }
    selected.querySelector('input[type=radio]').checked = true;
}

// ─── Form submit validation ───────────────────────────────────
document.getElementById('resultForm').addEventListener('submit', function(e) {
    var mode = document.querySelector('input[name=payment_mode]:checked').value;
    var completionMonth = document.getElementById('completionMonth').value;
    if (!completionMonth) {
        alert('Please select the completion month.');
        e.preventDefault();
        return false;
    }
    // Check at least one subject has marks
    var anyMarks = false;
    document.querySelectorAll('.obtained-marks').forEach(function(el) {
        if (el.value !== '') anyMarks = true;
    });
    if (!anyMarks) {
        alert('Please enter marks for at least one subject. Use 🎲 Random Marks or pick a grade to auto-fill.');
        e.preventDefault();
        return false;
    }
    if (mode === 'offline') {
        var txnId = document.getElementById('transactionId').value.trim();
        if (!txnId) {
            alert('Please enter the Transaction ID for offline payment.');
            e.preventDefault();
            return false;
        }
    }
    if (!confirm('Submit result for Super Admin approval?\n\nTotal: ₹200 (Certificate + Marksheet combined)\nPayment: ' + mode.toUpperCase() + (mode === 'offline' ? ' (Txn: ' + document.getElementById('transactionId').value.trim() + ')' : ' (₹200 from wallet)') + '\n\nAfter Super Admin approves, both PDFs will be generated and downloadable.')) {
        e.preventDefault();
    }
});

calcTotal();
</script>
