<?php
/**
 * Result Form — Old Style + New Auto-Date Logic (course-duration based)
 *
 * Features preserved from old form:
 *   - Teal/green gradient theme
 *   - Auto-grade dropdown (A+, A, B+, B, C, D)
 *   - 🎲 Random button
 *   - ✕ Clear button
 *   - Big colored Grade/Division/Status boxes
 *
 * New improvements:
 *   - Completion month: last 2 years (24 months) dropdown
 *   - Session From auto-calculated based on COURSE DURATION (not hardcoded 11 months)
 *     e.g., 3-month course + completion Jan 2026 → From = Nov 2025 (Jan - 2 months)
 *   - Issue Date auto-set to random date in completion month, editable
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$student = $student ?? [];
$subjects = $subjects ?? [];
$csrfToken = $csrfToken ?? '';

// Build months dropdown — last 2 years (24 months), Month Year format
$months = [];
$current = strtotime('first day of this month');
for ($i = 0; $i < 24; $i++) {
    $ts = strtotime("-{$i} months", $current);
    $value = date('Y-m', $ts);
    $label = date('F Y', $ts);
    $months[$value] = $label;
}

// Parse course duration
$courseDuration = $student['duration'] ?? '6 Months';
preg_match('/([\d.]+)\s*month/i', $courseDuration, $m);
$durationMonths = isset($m[1]) ? (int)round((float)$m[1]) : 6;
if ($durationMonths < 1) $durationMonths = 6;
$startOffset = max(0, $durationMonths - 1);  // inclusive: 3 months = 2 months back
?>
<style>
.result-form-2026 { padding: 12px; }
.result-form-2026 input, .result-form-2026 select {
    font-family: inherit;
}
.result-form-2026 .rf-card {
    background:#fff; border-radius:12px; padding:20px;
    margin-bottom:14px; box-shadow:0 2px 8px rgba(0,0,0,0.06);
}
.result-form-2026 .rf-h3 {
    margin:0 0 6px; font-size:1.05rem; color:#0d3b3b;
}
.result-form-2026 .rf-sub {
    margin:0 0 12px; font-size:0.82rem; color:#666;
}
.result-form-2026 .rf-table {
    width:100%; border-collapse:collapse; font-size:0.86rem;
}
.result-form-2026 .rf-table th {
    background:#f8f9fa; padding:10px; text-align:left;
    border-bottom:2px solid #dee2e6;
}
.result-form-2026 .rf-table td {
    padding:10px; border-bottom:1px solid #e9ecef; vertical-align:middle;
}
.result-form-2026 .rf-table input[type=number] {
    width:90px; padding:6px; border:1px solid #ddd; border-radius:4px;
    text-align:center; font-size:0.84rem;
}
.result-form-2026 .rf-totals {
    background:#eafaf1; font-weight:700;
}
.result-form-2026 .rf-summary {
    display:grid; grid-template-columns:repeat(3,1fr); gap:10px; margin-top:14px;
}
.result-form-2026 .rf-sum-box {
    text-align:center; padding:12px; border-radius:8px;
}
.result-form-2026 .rf-sum-box .v {
    font-size:1.3rem; font-weight:700;
}
.result-form-2026 .rf-sum-box .l {
    font-size:0.72rem; color:#999;
}
.result-form-2026 .rf-pay-opt {
    flex:1; padding:12px; border:2px solid #e0e0e0; border-radius:8px;
    cursor:pointer; text-align:center; background:#fff; transition:all 0.2s;
}
.result-form-2026 .rf-pay-opt.active {
    border-color:#16a085; background:#eafaf1;
}
.result-form-2026 .rf-pay-opt.active-offline {
    border-color:#f39c12; background:#fff8e1;
}
.result-form-2026 .rf-btn {
    padding:10px 16px; border:none; border-radius:6px;
    font-size:0.82rem; font-weight:600; cursor:pointer;
}
.result-form-2026 .rf-btn-primary {
    background:#f39c12; color:#fff;
}
.result-form-2026 .rf-btn-danger {
    background:#e84118; color:#fff;
}
.result-form-2026 .rf-btn-success {
    background:#16a085; color:#fff;
}
.result-form-2026 .rf-grade-select {
    padding:8px 12px; border:1px solid #16a085; border-radius:6px;
    font-size:0.82rem; background:#eafaf1; color:#0d3b3b; font-weight:600;
}
@media (max-width: 768px) {
    .result-form-2026 .rf-summary { grid-template-columns:1fr 1fr; }
    .result-form-2026 .rf-table { font-size:0.78rem; }
    .result-form-2026 .rf-table input[type=number] { width:70px; }
}
</style>

<div class="result-form-2026 admin-section">
    <div style="margin-bottom:14px;">
        <a href="<?= $bp ?>/branch/cert-gen" style="color:#16a085;text-decoration:none;font-size:0.85rem;">← Back to Status</a>
    </div>

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

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

        <!-- Step 1: Completion Month -->
        <div class="rf-card">
            <h3 class="rf-h3">Step 1: Completion Month</h3>
            <p class="rf-sub">Select when the student completed the course. "From" date auto-calculates based on course duration (<?= htmlspecialchars($courseDuration) ?> = <?= $durationMonths ?> months).</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)</label>
                    <input type="text" id="fromDateDisplay" readonly placeholder="e.g. NOV 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 style="margin-top:10px;">
                <label style="display:block;font-size:0.82rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Issue Date (auto = random date in completion month)</label>
                <input type="date" name="issue_date" id="issueDate" value="<?= date('Y-m-d') ?>" style="width:200px;padding:8px;border:1px solid #ddd;border-radius:6px;font-size:0.84rem;">
                <small style="color:#999;font-size:0.75rem;">You can change this date.</small>
            </div>
        </div>

        <!-- Step 2: Subject Marks -->
        <div class="rf-card">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:10px;">
                <div>
                    <h3 class="rf-h3">Step 2: Subject-wise Marks</h3>
                    <p class="rf-sub">Subjects auto-loaded from course. Enter marks OR use auto-fill.</p>
                </div>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <select id="targetGrade" onchange="applyGrade()" class="rf-grade-select">
                        <option value="">🎯 Auto-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()" class="rf-btn rf-btn-primary">🎲 Random</button>
                    <button type="button" onclick="clearMarks()" class="rf-btn rf-btn-danger">✕ Clear</button>
                </div>
            </div>

            <?php if (empty($subjects)): ?>
                <div style="text-align:center;padding:30px;color:#999;background:#f9f9f9;border-radius:8px;">No subjects defined for this course.</div>
            <?php else: ?>
                <div style="overflow-x:auto;">
                    <table class="rf-table">
                        <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</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()">
                                </td>
                                <td style="padding:10px;text-align:center;" class="subject-pct">—</td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="rf-totals">
                                <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>
                </div>
                <div class="rf-summary">
                    <div class="rf-sum-box" style="background:#eaf0fb;"><div class="v" style="color:#1a4fa0;" id="resultGrade">—</div><div class="l">Grade</div></div>
                    <div class="rf-sum-box" style="background:#eafaf1;"><div class="v" style="color:#27ae60;" id="resultDivision">—</div><div class="l">Division</div></div>
                    <div class="rf-sum-box" style="background:#fff5e6;"><div class="v" style="color:#f39c12;" id="resultStatus">—</div><div class="l">Status</div></div>
                </div>
            <?php endif; ?>
        </div>

        <?php if (!empty($subjects)): ?>
        <!-- Step 3: Payment -->
        <div class="rf-card">
            <h3 class="rf-h3">Step 3: Payment (₹200 combined)</h3>
            <div style="display:flex;gap:10px;margin-top:12px;">
                <label class="rf-pay-opt active" onclick="selectPayment('online', this)">
                    <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;">Online (₹200 wallet)</div>
                </label>
                <label class="rf-pay-opt" onclick="selectPayment('offline', this)">
                    <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;">Offline (Txn ID)</div>
                </label>
            </div>
            <div id="offlinePaymentBox" style="display:none;margin-top:14px;padding:14px;background:#fff8e1;border:1px solid #f5d68b;border-radius:8px;">
                <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 *</label><input type="text" name="transaction_id" id="transactionId" style="width:100%;padding:9px;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;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 (Cert + Marksheet)</div><div style="font-size:2rem;font-weight:700;">₹200</div>
            </div>
            <input type="hidden" name="total_amount" value="200">
        </div>

        <div style="display:flex;gap:12px;justify-content:flex-end;flex-wrap:wrap;">
            <a href="<?= $bp ?>/branch/cert-gen" 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 for Approval</button>
        </div>
        <?php endif; ?>
    </form>
</div>

<script>
// ─── Auto-calculate From date based on completion month + course duration ──
function updateFromDate(){
    var c = document.getElementById('completionMonth').value;
    if(!c){
        document.getElementById('fromDateDisplay').value = '';
        document.getElementById('fromMonthInput').value = '';
        return;
    }
    var parts = c.split('-');
    var completionDate = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, 1);

    // Subtract (duration - 1) months from completion to get start (inclusive)
    var startOffset = parseInt(document.getElementById('start_offset').value) || 5;
    var fromDate = new Date(completionDate);
    fromDate.setMonth(fromDate.getMonth() - startOffset);

    // Format: "NOV 2025"
    var monthNames = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
    var fromLabel = monthNames[fromDate.getMonth()] + ' ' + fromDate.getFullYear();
    var toLabel = monthNames[completionDate.getMonth()] + ' ' + completionDate.getFullYear();
    document.getElementById('fromDateDisplay').value = fromLabel + '  →  ' + toLabel;
    document.getElementById('fromMonthInput').value = fromDate.getFullYear() + '-' + String(fromDate.getMonth() + 1).padStart(2, '0');

    // ✅ FIX: Issue date = NEXT month after completion (not same month)
    // e.g., completion = Jan 2026 → issue date = Feb 2026 (random day)
    var issueDate = new Date(completionDate);
    issueDate.setMonth(issueDate.getMonth() + 1);  // +1 month
    var lastDay = new Date(issueDate.getFullYear(), issueDate.getMonth() + 1, 0).getDate();
    var randomDay = Math.floor(Math.random() * lastDay) + 1;
    var issueDateStr = issueDate.getFullYear() + '-' +
                       String(issueDate.getMonth() + 1).padStart(2, '0') + '-' +
                       String(randomDay).padStart(2, '0');
    document.getElementById('issueDate').value = issueDateStr;
}

// ─── Calculate totals, grade, division, status ─────────────────────────────
function calcTotal(){
    var o = document.querySelectorAll('.obtained-marks');
    var m = document.querySelectorAll('.max-marks');
    var tO = 0, tM = 0;

    for(var i = 0; i < o.length; i++){
        var x = parseInt(o[i].value) || 0;
        var y = parseInt(m[i].value) || 100;
        tO += x;
        tM += y;
        var p = y > 0 ? ((x / y) * 100).toFixed(1) : 0;
        var c = o[i].closest('tr').querySelector('.subject-pct');
        if(c) c.textContent = p + '%';
    }

    document.getElementById('totalObtained').textContent = tO;
    document.getElementById('totalMax').textContent = tM;
    var pct = tM > 0 ? ((tO / tM) * 100).toFixed(1) : 0;
    document.getElementById('totalPct').textContent = pct + '%';

    var g = 'F';
    if(pct >= 90) g = 'A+';
    else if(pct >= 80) g = 'A';
    else if(pct >= 70) g = 'B+';
    else if(pct >= 60) g = 'B';
    else if(pct >= 45) g = 'C';
    else if(pct >= 33) g = 'D';

    var d = 'Fail';
    if(pct >= 60) d = 'First';
    else if(pct >= 45) d = 'Second';
    else if(pct >= 33) d = 'Third';

    document.getElementById('resultGrade').textContent = g;
    document.getElementById('resultDivision').textContent = d;
    document.getElementById('resultStatus').textContent = pct >= 33 ? 'PASS ✓' : 'FAIL ✗';
    document.getElementById('resultStatus').style.color = pct >= 33 ? '#27ae60' : '#e84118';
}

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

// ─── Apply selected grade to all subjects ─────────────────────────────────
function applyGrade(){
    var g = document.getElementById('targetGrade').value;
    if(!g) 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 r = ranges[g];
    if(!r) return;
    var o = document.querySelectorAll('.obtained-marks');
    var m = document.querySelectorAll('.max-marks');
    for(var i = 0; i < o.length; i++){
        var x = parseInt(m[i].value) || 100;
        o[i].value = Math.round(x * (Math.random() * (r[1] - r[0]) + r[0]));
    }
    calcTotal();
}

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

// ─── Payment mode selection ───────────────────────────────────────────────
function selectPayment(mode, elem){
    document.querySelectorAll('.rf-pay-opt').forEach(function(e){
        e.classList.remove('active', 'active-offline');
    });
    if(mode === 'online'){
        elem.classList.add('active');
        document.getElementById('offlinePaymentBox').style.display = 'none';
    } else {
        elem.classList.add('active-offline');
        document.getElementById('offlinePaymentBox').style.display = 'block';
    }
    elem.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;
    if(!document.getElementById('completionMonth').value){
        alert('Select completion month.');
        e.preventDefault();
        return false;
    }
    if(mode === 'offline' && !document.getElementById('transactionId').value.trim()){
        alert('Enter Transaction ID.');
        e.preventDefault();
        return false;
    }
    if(!confirm('Submit for approval? ₹200 (' + mode + '). Super Admin will approve → PDFs generated.')){
        e.preventDefault();
    }
});

// Initial calculation
calcTotal();
</script>
