<?php $bp = defined('BASE_PATH') ? BASE_PATH : '/gmind'; $students = $students ?? []; ?>
<div class="admin-section">
    <div style="margin-bottom:14px;"><a href="<?= $bp ?>/branch/results" style="color:#16a085;text-decoration:none;font-size:0.85rem;">← Back to Results</a></div>
    <form method="POST" action="<?= $bp ?>/branch/results" id="resultForm" style="max-width:800px;">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">
        <div style="background:#fff;border-radius:12px;padding:24px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <h2 style="margin:0 0 6px;font-size:1.05rem;color:#0d3b3b;">Step 1: Select Student</h2>
            <p style="margin:0 0 14px;font-size:0.82rem;color:#666;">Select a student — their course subjects will auto-load below.</p>
            <select name="student_id" id="studentSelect" required style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.88rem;">
                <option value="">— Select Student —</option>
                <?php foreach ($students as $s): $subs = []; if (!empty($s['subjects'])) { $d = json_decode($s['subjects'], true); if (is_array($d)) $subs = $d; } ?>
                <option value="<?= (int)$s['id'] ?>" data-course-id="<?= (int)($s['course_id']??0) ?>" data-subjects='<?= json_encode($subs) ?>' data-fee-due="<?= (float)($s['fee_due']??0) ?>"><?= htmlspecialchars($s['name'] ?? '', ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($s['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?>) — <?= htmlspecialchars($s['course_name'] ?? '', ENT_QUOTES, 'UTF-8') ?><?= (float)($s['fee_due']??0)>0?' ⚠ Fee Due':'' ?></option>
                <?php endforeach; ?>
            </select>
            <input type="hidden" name="course_id" id="courseIdInput">
        </div>
        <div style="background:#fff;border-radius:12px;padding:24px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
            <h2 style="margin:0 0 6px;font-size:1.05rem;color:#0d3b3b;">Step 2: Subject-wise Marks</h2>
            <p style="margin:0 0 14px;font-size:0.82rem;color:#666;">Enter obtained marks per subject, OR toggle "Auto-distribute" and enter only total obtained — the system will randomly distribute it across subjects. Total, percentage, grade, and division auto-calculate.</p>

            <div style="display:flex;gap:18px;margin-bottom:14px;padding:10px;background:#f9f9f9;border-radius:8px;flex-wrap:wrap;align-items:center;">
                <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:0.84rem;font-weight:600;color:#0d3b3b;">
                    <input type="radio" name="auto_distribute" value="0" checked id="modeManual" style="cursor:pointer;"> ✍ Manual mode (enter per-subject)
                </label>
                <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:0.84rem;font-weight:600;color:#16a085;">
                    <input type="radio" name="auto_distribute" value="1" id="modeAuto" style="cursor:pointer;"> 🎲 Auto-distribute (enter total only)
                </label>
                <div id="autoTotalWrap" style="display:none;align-items:center;gap:8px;font-size:0.84rem;color:#666;">
                    <label for="autoTotal" style="font-weight:600;color:#0d3b3b;">Total obtained marks:</label>
                    <input type="number" id="autoTotal" name="total_obtained" value="" min="0" placeholder="e.g. 500" style="width:110px;padding:7px;border:1px solid #ddd;border-radius:6px;font-size:0.84rem;text-align:center;">
                    <span style="font-size:0.74rem;color:#999;">(will be distributed randomly across subjects)</span>
                </div>
            </div>

            <div id="subjectsContainer" style="display:none;">
                <table style="width:100%;font-size:0.84rem;border-collapse:collapse;">
                    <thead><tr style="background:#f8f9fa;"><th style="padding:8px;text-align:left;border:1px solid #ddd;">Subject</th><th style="padding:8px;width:80px;text-align:center;border:1px solid #ddd;">Max</th><th style="padding:8px;width:100px;text-align:center;border:1px solid #ddd;">Obtained</th></tr></thead>
                    <tbody id="subjectsBody"></tbody>
                </table>
            </div>
            <div id="noSubjects" style="display:none;text-align:center;padding:20px;color:#999;">This course has no predefined subjects. Add subjects from Super Admin → Courses.</div>
            <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-top:14px;">
                <div style="text-align:center;padding:10px;background:#f9f9f9;border-radius:8px;"><div style="font-size:1.2rem;font-weight:700;color:#0d3b3b;" id="totalObtained">0</div><div style="font-size:0.7rem;color:#999;">Obtained</div></div>
                <div style="text-align:center;padding:10px;background:#f9f9f9;border-radius:8px;"><div style="font-size:1.2rem;font-weight:700;color:#0d3b3b;" id="totalMax">0</div><div style="font-size:0.7rem;color:#999;">Total</div></div>
                <div style="text-align:center;padding:10px;background:#eafaf1;border-radius:8px;"><div style="font-size:1.2rem;font-weight:700;color:#27ae60;" id="totalPct">0%</div><div style="font-size:0.7rem;color:#999;">Percentage</div></div>
                <div style="text-align:center;padding:10px;background:#eaf0fb;border-radius:8px;"><div style="font-size:1.2rem;font-weight:700;color:#1a4fa0;" id="totalGrade">—</div><div style="font-size:0.7rem;color:#999;">Grade</div></div>
            </div>
        </div>
        <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="margin-bottom:12px;"><label style="display:block;font-size:0.84rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Remarks (optional)</label><input type="text" name="remarks" placeholder="e.g. Good performance" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:0.88rem;"></div>
            <div id="feeWarning" style="display:none;background:#fff5f5;border:1px solid #e84118;border-radius:8px;padding:12px;font-size:0.82rem;color:#e84118;margin-bottom:10px;">⚠ This student has pending fee dues. Result will be created as DRAFT and require Super Admin approval to publish.</div>
        </div>
        <div style="display:flex;gap:12px;justify-content:flex-end;">
            <a href="<?= $bp ?>/branch/results" 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 28px;background:linear-gradient(135deg,#16a085,#117a65);color:#fff;border:none;border-radius:8px;font-weight:600;font-size:0.9rem;cursor:pointer;">Create Result</button>
        </div>
    </form>
</div>
<script>
var subjectsGlobal = [];
document.getElementById('studentSelect').addEventListener('change', function() {
    var opt = this.options[this.selectedIndex];
    if (!opt.value) { document.getElementById('subjectsContainer').style.display='none'; document.getElementById('noSubjects').style.display='none'; return; }
    subjectsGlobal = JSON.parse(opt.dataset.subjects || '[]');
    var courseId = opt.dataset.courseId || 0;
    var feeDue = parseFloat(opt.dataset.feeDue || 0);
    document.getElementById('courseIdInput').value = courseId;
    document.getElementById('feeWarning').style.display = feeDue > 0 ? 'block' : 'none';
    renderSubjects();
});

function renderSubjects() {
    var tbody = document.getElementById('subjectsBody');
    tbody.innerHTML = '';
    if (subjectsGlobal.length === 0) { document.getElementById('subjectsContainer').style.display='none'; document.getElementById('noSubjects').style.display='block'; return; }
    document.getElementById('noSubjects').style.display='none';
    document.getElementById('subjectsContainer').style.display='block';
    var isAuto = document.getElementById('modeAuto').checked;
    subjectsGlobal.forEach(function(s) {
        var tr = document.createElement('tr');
        var obtCell;
        if (isAuto) {
            // Auto mode — show read-only "auto" placeholder, will be filled server-side
            obtCell = '<td style="padding:6px;border:1px solid #ddd;text-align:center;color:#999;font-style:italic;font-size:0.78rem;">random</td>';
        } else {
            obtCell = '<td style="padding:6px;border:1px solid #ddd;text-align:center;"><input type="number" name="obtained_marks[]" value="" placeholder="0" min="0" max="'+s.max_marks+'" style="width:80px;padding:4px;border:1px solid #ddd;border-radius:4px;text-align:center;" oninput="calcTotal()"></td>';
        }
        tr.innerHTML = '<td style="padding:6px;border:1px solid #ddd;"><input type="hidden" name="subject_name[]" value="'+s.name+'">'+s.name+'</td><td style="padding:6px;border:1px solid #ddd;text-align:center;"><input type="hidden" name="max_marks[]" value="'+s.max_marks+'">'+s.max_marks+'</td>' + obtCell;
        tbody.appendChild(tr);
    });
    if (isAuto) {
        // Show total max + 0 obtained (will be set on server)
        var tMax = subjectsGlobal.reduce(function(a,s){return a+parseInt(s.max_marks);},0);
        document.getElementById('totalObtained').textContent = document.getElementById('autoTotal').value || 0;
        document.getElementById('totalMax').textContent = tMax;
        var obt = parseInt(document.getElementById('autoTotal').value) || 0;
        var pct = tMax>0?((obt/tMax)*100).toFixed(1):0;
        document.getElementById('totalPct').textContent = pct + '%';
        updateGrade(parseFloat(pct));
    } else {
        calcTotal();
    }
}

function updateGrade(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';
    document.getElementById('totalGrade').textContent=g;
}

function calcTotal() {
    var obt = document.querySelectorAll('input[name="obtained_marks[]"]');
    var max = document.querySelectorAll('input[name="max_marks[]"]');
    var tObt=0,tMax=0;
    for (var i=0;i<obt.length;i++){ tObt+=parseInt(obt[i].value)||0; tMax+=parseInt(max[i].value)||0; }
    document.getElementById('totalObtained').textContent=tObt;
    document.getElementById('totalMax').textContent=tMax;
    var pct = tMax>0?((tObt/tMax)*100).toFixed(1):0;
    document.getElementById('totalPct').textContent=pct+'%';
    updateGrade(parseFloat(pct));
}

// Mode toggle
document.querySelectorAll('input[name="auto_distribute"]').forEach(function(r) {
    r.addEventListener('change', function() {
        var isAuto = document.getElementById('modeAuto').checked;
        document.getElementById('autoTotalWrap').style.display = isAuto ? 'flex' : 'none';
        renderSubjects();
    });
});

// Auto-total input — update display
document.getElementById('autoTotal').addEventListener('input', function() {
    if (document.getElementById('modeAuto').checked) {
        document.getElementById('totalObtained').textContent = this.value || 0;
        var tMax = subjectsGlobal.reduce(function(a,s){return a+parseInt(s.max_marks);},0);
        var obt = parseInt(this.value) || 0;
        var pct = tMax>0?((obt/tMax)*100).toFixed(1):0;
        document.getElementById('totalPct').textContent = pct + '%';
        updateGrade(parseFloat(pct));
    }
});

// Form submit — validate
document.getElementById('resultForm').addEventListener('submit', function(e) {
    if (document.getElementById('modeAuto').checked) {
        var total = parseInt(document.getElementById('autoTotal').value) || 0;
        var tMax = subjectsGlobal.reduce(function(a,s){return a+parseInt(s.max_marks);},0);
        if (total > tMax) {
            alert('Total obtained (' + total + ') cannot exceed maximum total (' + tMax + ').');
            e.preventDefault();
        } else if (total <= 0) {
            alert('Please enter total obtained marks greater than 0 for auto-distribute mode.');
            e.preventDefault();
        } else if (!confirm('Auto-distribute ' + total + ' marks randomly across ' + subjectsGlobal.length + ' subjects? The marks will be assigned on form submission.')) {
            e.preventDefault();
        }
    }
});
</script>
