<?php
/**
 * Branch — Generate Document (Certificate + Marksheet together)
 *
 * Form fields:
 *   1. Select student (auto-fills name, enrollment, course, etc.)
 *   2. Select template(s) — can generate certificate AND marksheet together
 *   3. Enter subject-wise marks (add subjects, max marks per subject, obtained marks)
 *   4. Auto-calculate: total marks, percentage, grade, division
 *   5. Session period: from date → to date (auto-filled based on completion date)
 *   6. Date of issue (default = 1 month after completion date, customizable)
 *   7. Student photo upload
 *   8. Payment mode (Online = instant, Offline = pending approval)
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$students = $students ?? [];
$templates = $templates ?? [];
$pricing = $pricing ?? [];
$typeLabels = ['certificate'=>'Certificate','marksheet'=>'Marksheet','id_card'=>'ID Card','admit_card'=>'Admit Card','affiliation'=>'Affiliation','authorization'=>'Authorization','renewal'=>'Renewal','franchise_agreement'=>'Franchise Agreement'];
?>
<div class="admin-section">
    <div style="margin-bottom:20px;"><a href="<?= $bp ?>/branch/documents" style="color:#16a085;text-decoration:none;font-size:0.85rem;">← Back to Documents</a></div>

    <?php
    // Phase 5: Pre-select document type from ?type= query param
    // (so the "Generate Certificate" / "Generate Marksheet" buttons can deep-link here)
    $preselectType = trim($_GET['type'] ?? '');
    if (!in_array($preselectType, ['certificate', 'marksheet'], true)) $preselectType = '';
    ?>

    <form method="POST" action="<?= $bp ?>/branch/documents" enctype="multipart/form-data" id="docGenForm" style="max-width:800px;">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="generate_both" value="1">

        <?php if ($preselectType): ?>
        <!-- Phase 5: Pre-select notice -->
        <div style="background:#eaf0fb;border-left:4px solid #1a4fa0;padding:12px 16px;border-radius:8px;margin-bottom:16px;font-size:0.84rem;color:#1a4fa0;">
            <strong>📌 Pre-selected:</strong> Generating <?= ucfirst($preselectType) ?> only. The <?= $preselectType === 'certificate' ? 'Marksheet' : 'Certificate' ?> option is hidden. <a href="<?= $bp ?>/branch/documents/create" style="color:#1a4fa0;text-decoration:underline;">Show all document types →</a>
        </div>
        <?php endif; ?>

        <!-- Step 1: Select Student -->
        <div class="admin-card" 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 data will auto-fill below.</p>
            <select name="student_id" id="studentSelect" required style="width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:6px;font-size:0.88rem;">
                <option value="">— Select Student —</option>
                <?php foreach ($students as $s): ?>
                <option value="<?= (int)$s['id'] ?>"
                        data-name="<?= htmlspecialchars($s['name'] ?? '', ENT_QUOTES) ?>"
                        data-enrollment="<?= htmlspecialchars($s['enrollment_no'] ?? '', ENT_QUOTES) ?>"
                        data-course="<?= htmlspecialchars($s['course_name'] ?? '', ENT_QUOTES) ?>"
                        data-course-id="<?= (int)($s['course_id'] ?? 0) ?>"
                        data-father="<?= htmlspecialchars($s['father_name'] ?? $s['guardian_name'] ?? '', ENT_QUOTES) ?>"
                        data-mother="<?= htmlspecialchars($s['mother_name'] ?? '', ENT_QUOTES) ?>"
                        data-dob="<?= htmlspecialchars($s['dob'] ?? '', ENT_QUOTES) ?>"
                        data-admission="<?= htmlspecialchars($s['admission_date'] ?? '', ENT_QUOTES) ?>"
                        data-phone="<?= htmlspecialchars($s['phone'] ?? '', ENT_QUOTES) ?>">
                    <?= htmlspecialchars($s['name'] ?? '', ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($s['enrollment_no'] ?? '', ENT_QUOTES, 'UTF-8') ?>) — <?= htmlspecialchars($s['course_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                </option>
                <?php endforeach; ?>
            </select>

            <!-- Auto-filled student data preview -->
            <div id="studentPreview" style="display:none; margin-top:12px; padding:12px; background:#eafaf1; border-radius:8px; font-size:0.82rem;">
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:6px;">
                    <div><strong>Name:</strong> <span id="prevName">—</span></div>
                    <div><strong>Enrollment:</strong> <span id="prevEnrollment">—</span></div>
                    <div><strong>Course:</strong> <span id="prevCourse">—</span></div>
                    <div><strong>Father:</strong> <span id="prevFather">—</span></div>
                    <div><strong>DOB:</strong> <span id="prevDob">—</span></div>
                    <div><strong>Admission:</strong> <span id="prevAdmission">—</span></div>
                </div>
            </div>
        </div>

        <!-- Step 2: Select Document Type -->
        <div class="admin-card" 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: Select Document(s) to Generate</h2>
            <p style="margin:0 0 14px;font-size:0.82rem;color:#666;">Choose which documents to generate. You can generate both certificate AND marksheet at once.</p>

            <div style="display:flex; gap:10px; flex-wrap:wrap;">
                <?php
                // Group templates by type
                $templatesByType = [];
                foreach ($templates as $t) {
                    $templatesByType[$t['type']][] = $t;
                }
                $docTypes = ['certificate' => '📜 Certificate', 'marksheet' => '📋 Marksheet'];
                foreach ($docTypes as $type => $label):
                    // Phase 5: If ?type= is set, only show that type
                    if ($preselectType && $preselectType !== $type) continue;
                    $hasTemplates = !empty($templatesByType[$type]);
                ?>
                <label style="flex:1; min-width:200px; padding:14px; border:2px solid <?= $hasTemplates ? '#e0e0e0' : '#f0f0f0' ?>; border-radius:10px; cursor:<?= $hasTemplates ? 'pointer' : 'not-allowed' ?>; opacity:<?= $hasTemplates ? '1' : '0.5' ?>;" onclick="document.querySelectorAll('.doc-type-card').forEach(e=>e.classList.remove('selected'));this.classList.add('selected')">
                    <div class="doc-type-card" style="font-size:1rem; font-weight:600; color:#0d3b3b;"><?= $label ?></div>
                    <?php if ($hasTemplates): ?>
                    <select name="template_ids[]" id="template_<?= $type ?>" style="width:100%; margin-top:8px; padding:6px; border:1px solid #ddd; border-radius:4px; font-size:0.8rem;">
                        <option value="">— Skip —</option>
                        <?php foreach ($templatesByType[$type] as $t): ?>
                        <option value="<?= (int)$t['id'] ?>" data-cost="<?= (float)($pricing[$type] ?? 0) ?>" <?= ($preselectType === $type) ? 'selected' : '' ?>><?= htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8') ?> (₹<?= number_format((float)($pricing[$type] ?? 0), 0) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                    <?php else: ?>
                    <div style="font-size:0.76rem; color:#e84118; margin-top:6px;">No template available</div>
                    <?php endif; ?>
                </label>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Step 3: Marks Entry (for marksheet) -->
        <div class="admin-card" 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 3: Subject-wise Marks Entry</h2>
            <p style="margin:0 0 14px;font-size:0.82rem;color:#666;">Add subjects, enter max marks and obtained marks. Percentage, grade, and division auto-calculate.</p>

            <!-- Subjects table -->
            <div style="overflow-x:auto;">
                <table style="width:100%; font-size:0.82rem; border-collapse:collapse;">
                    <thead>
                        <tr style="background:#f8f9fa;">
                            <th style="padding:8px; text-align:left; border:1px solid #ddd;">Subject Name</th>
                            <th style="padding:8px; width:100px; text-align:center; border:1px solid #ddd;">Max Marks</th>
                            <th style="padding:8px; width:100px; text-align:center; border:1px solid #ddd;">Obtained</th>
                            <th style="padding:8px; width:60px; text-align:center; border:1px solid #ddd;">%</th>
                            <th style="padding:8px; width:40px; border:1px solid #ddd;">✕</th>
                        </tr>
                    </thead>
                    <tbody id="subjectsBody">
                        <!-- Default: 8 subjects, each max 100 -->
                        <tr class="subject-row">
                            <td style="padding:6px; border:1px solid #ddd;"><input type="text" name="subjects[]" placeholder="e.g. Computer Fundamentals" style="width:100%; padding:4px 6px; border:1px solid #ddd; border-radius:4px; font-size:0.8rem;"></td>
                            <td style="padding:6px; border:1px solid #ddd;"><input type="number" name="max_marks[]" value="100" min="1" class="max-marks" style="width:80px; padding:4px 6px; border:1px solid #ddd; border-radius:4px; font-size:0.8rem; text-align:center;"></td>
                            <td style="padding:6px; border:1px solid #ddd;"><input type="number" name="obtained_marks[]" value="" placeholder="0" min="0" class="obtained-marks" style="width:80px; padding:4px 6px; border:1px solid #ddd; border-radius:4px; font-size:0.8rem; text-align:center;"></td>
                            <td style="padding:6px; border:1px solid #ddd; text-align:center;" class="subject-pct">—</td>
                            <td style="padding:6px; border:1px solid #ddd; text-align:center;"><button type="button" onclick="this.closest('tr').remove(); calculateTotal()" style="background:none; border:none; color:#e84118; cursor:pointer; font-size:1rem;">✕</button></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Add subject + Random fill buttons -->
            <div style="display:flex; gap:8px; margin-top:10px;">
                <button type="button" onclick="addSubject()" style="padding:6px 14px; background:#16a085; color:#fff; border:none; border-radius:6px; font-size:0.8rem; cursor:pointer;">+ Add Subject</button>
                <button type="button" onclick="randomFillMarks()" style="padding:6px 14px; background:#f39c12; color:#fff; border:none; border-radius:6px; font-size:0.8rem; cursor:pointer;">🎲 Random Fill</button>
                <button type="button" onclick="clearMarks()" style="padding:6px 14px; background:#e84118; color:#fff; border:none; border-radius:6px; font-size:0.8rem; cursor:pointer;">Clear All</button>
            </div>

            <!-- Auto-calculated totals -->
            <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.3rem; font-weight:700; color:#0d3b3b;" id="totalObtained">0</div>
                    <div style="font-size:0.72rem; color:#999;">Obtained</div>
                </div>
                <div style="text-align:center; padding:10px; background:#f9f9f9; border-radius:8px;">
                    <div style="font-size:1.3rem; font-weight:700; color:#0d3b3b;" id="totalMax">0</div>
                    <div style="font-size:0.72rem; color:#999;">Total Max</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="totalPercentage">0%</div>
                    <div style="font-size:0.72rem; color:#999;">Percentage</div>
                </div>
                <div style="text-align:center; padding:10px; background:#eaf0fb; border-radius:8px;">
                    <div style="font-size:1.3rem; font-weight:700; color:#1a4fa0;" id="totalGrade">—</div>
                    <div style="font-size:0.72rem; color:#999;">Grade / Division</div>
                </div>
            </div>
            <div style="text-align:center; margin-top:6px; font-size:0.78rem; color:#666;">
                Division: <strong id="totalDivision">—</strong>
            </div>
        </div>

        <!-- Step 4: Dates & Photo -->
        <div class="admin-card" 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 4: Session Dates & Photo</h2>

            <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-bottom:12px;">
                <div>
                    <label style="display:block; font-size:0.82rem; font-weight:600; color:#0d3b3b; margin-bottom:4px;">Session From Date <span style="color:#999;">(auto from admission date)</span></label>
                    <input type="date" name="session_from" id="sessionFrom" style="width:100%; padding:8px 10px; border:1px solid #ddd; border-radius:6px; font-size:0.84rem;">
                </div>
                <div>
                    <label style="display:block; font-size:0.82rem; font-weight:600; color:#0d3b3b; margin-bottom:4px;">Session To Date <span style="color:#999;">(completion date)</span></label>
                    <input type="date" name="session_to" id="sessionTo" onchange="updateIssueDate()" style="width:100%; padding:8px 10px; border:1px solid #ddd; border-radius:6px; font-size:0.84rem;">
                </div>
            </div>

            <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-bottom:12px;">
                <div>
                    <label style="display:block; font-size:0.82rem; font-weight:600; color:#0d3b3b; margin-bottom:4px;">Date of Issue <span style="color:#999;">(default: 1 month after completion)</span></label>
                    <input type="date" name="issue_date" id="issueDate" style="width:100%; padding:8px 10px; border:1px solid #ddd; border-radius:6px; font-size:0.84rem;">
                </div>
                <div>
                    <label style="display:block; font-size:0.82rem; font-weight:600; color:#0d3b3b; margin-bottom:4px;">Student Photo (optional)</label>
                    <input type="file" name="student_photo" accept="image/jpeg,image/png" style="width:100%; font-size:0.8rem; padding:6px; border:1px solid #ddd; border-radius:6px;">
                </div>
            </div>
        </div>

        <!-- Step 5: Payment -->
        <div class="admin-card" 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 5: Payment Mode</h2>
            <p style="margin:0 0 12px;font-size:0.82rem;color:#666;">
                <strong>Online</strong> = instant PDF generation (cost deducted from branch wallet).
                <strong>Offline</strong> = submit transaction ID → Super Admin verifies → approves → PDF unlocked for download.
            </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)</div>
                    <div style="font-size:0.72rem; color:#27ae60; margin-top:2px;">Instant PDF</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;">Super Admin approves</div>
                </label>
            </div>

            <!-- Transaction ID field (only for offline payment) -->
            <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>
                <p style="margin:0 0 10px;font-size:0.78rem;color:#666;">Pay ₹<strong id="offlineCostDisplay">200</strong> via UPI/Bank transfer to your branch's account, then enter the transaction ID below. Super Admin will verify and approve your request.</p>
                <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" id="paymentDate" 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 style="margin-top:10px;">
                    <label style="display:block;font-size:0.78rem;font-weight:600;color:#0d3b3b;margin-bottom:4px;">Payment Notes (optional)</label>
                    <input type="text" name="payment_notes" placeholder="e.g. Paid via GPay to branch@okbank" style="width:100%;padding:9px 12px;border:1px solid #ddd;border-radius:6px;font-size:0.86rem;">
                </div>
            </div>

            <!-- Combined cost display -->
            <div id="costSummary" 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; margin-bottom:4px;">Total Cost (Certificate + Marksheet combined)</div>
                <div style="font-size:2rem; font-weight:700; letter-spacing:1px;">₹<span id="totalCost">200</span></div>
                <div style="font-size:0.72rem; opacity:0.7; margin-top:4px;" id="costBreakdown">₹100 Certificate + ₹100 Marksheet = ₹200 (combined discount)</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/documents" 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;">Generate Document(s)</button>
        </div>
    </form>
</div>

<style>.doc-type-card.selected { color:#16a085 !important; }</style>

<script>
// ─── Payment mode selection ────────────────────────────────
function selectPayment(mode) {
    document.querySelectorAll('.pay-opt').forEach(function(e) {
        e.classList.remove('selected');
        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.classList.add('selected');
    // Update radio
    selected.querySelector('input[type=radio]').checked = true;
}

// ─── Form submit validation ────────────────────────────────
document.getElementById('docGenForm').addEventListener('submit', function(e) {
    var mode = document.querySelector('input[name=payment_mode]:checked').value;
    if (mode === 'offline') {
        var txnId = document.getElementById('transactionId').value.trim();
        if (!txnId) {
            alert('Please enter the Transaction ID / UTR No. for offline payment.');
            e.preventDefault();
            return false;
        }
        if (!confirm('Submit document request with Transaction ID: ' + txnId + '?\n\nTotal cost: ₹200 (Certificate + Marksheet combined).\nSuper Admin will verify your payment and approve within 24 hours.')) {
            e.preventDefault();
            return false;
        }
    } else {
        if (!confirm('Generate Certificate + Marksheet (combined ₹200)?\n\nAmount will be deducted from your branch wallet. PDFs will be generated instantly.')) {
            e.preventDefault();
            return false;
        }
    }
});

// ─── Student auto-fill ─────────────────────────────────────
document.getElementById('studentSelect').addEventListener('change', function() {
    var opt = this.options[this.selectedIndex];
    if (!opt.value) { document.getElementById('studentPreview').style.display = 'none'; return; }

    document.getElementById('prevName').textContent = opt.dataset.name || '—';
    document.getElementById('prevEnrollment').textContent = opt.dataset.enrollment || '—';
    document.getElementById('prevCourse').textContent = opt.dataset.course || '—';
    document.getElementById('prevFather').textContent = opt.dataset.father || '—';
    document.getElementById('prevDob').textContent = opt.dataset.dob || '—';
    document.getElementById('prevAdmission').textContent = opt.dataset.admission || '—';
    document.getElementById('studentPreview').style.display = 'block';

    // Auto-fill session from date = admission date
    if (opt.dataset.admission) {
        document.getElementById('sessionFrom').value = opt.dataset.admission;
        // Session to = 12 months later (or 6 months, depending on course)
        var d = new Date(opt.dataset.admission);
        d.setFullYear(d.getFullYear() + 1);
        d.setDate(d.getDate() - 1);
        document.getElementById('sessionTo').value = d.toISOString().split('T')[0];
        updateIssueDate();
    }
});

// ─── Update issue date = session_to + 1 month ──────────────
function updateIssueDate() {
    var to = document.getElementById('sessionTo').value;
    if (to) {
        var d = new Date(to);
        d.setMonth(d.getMonth() + 1);
        document.getElementById('issueDate').value = d.toISOString().split('T')[0];
    }
}

// ─── Subject management ────────────────────────────────────
function addSubject() {
    var tbody = document.getElementById('subjectsBody');
    var tr = document.createElement('tr');
    tr.className = 'subject-row';
    tr.innerHTML = '<td style="padding:6px; border:1px solid #ddd;"><input type="text" name="subjects[]" placeholder="Subject name" style="width:100%; padding:4px 6px; border:1px solid #ddd; border-radius:4px; font-size:0.8rem;"></td>' +
        '<td style="padding:6px; border:1px solid #ddd;"><input type="number" name="max_marks[]" value="100" min="1" class="max-marks" style="width:80px; padding:4px 6px; border:1px solid #ddd; border-radius:4px; font-size:0.8rem; text-align:center;"></td>' +
        '<td style="padding:6px; border:1px solid #ddd;"><input type="number" name="obtained_marks[]" value="" placeholder="0" min="0" class="obtained-marks" style="width:80px; padding:4px 6px; border:1px solid #ddd; border-radius:4px; font-size:0.8rem; text-align:center;"></td>' +
        '<td style="padding:6px; border:1px solid #ddd; text-align:center;" class="subject-pct">—</td>' +
        '<td style="padding:6px; border:1px solid #ddd; text-align:center;"><button type="button" onclick="this.closest(\'tr\').remove(); calculateTotal()" style="background:none; border:none; color:#e84118; cursor:pointer; font-size:1rem;">✕</button></td>';
    tbody.appendChild(tr);
    tr.querySelector('.obtained-marks').addEventListener('input', calculateTotal);
    tr.querySelector('.max-marks').addEventListener('input', calculateTotal);
}

// ─── Calculate totals ──────────────────────────────────────
function calculateTotal() {
    var rows = document.querySelectorAll('.subject-row');
    var totalObtained = 0, totalMax = 0;

    rows.forEach(function(row) {
        var max = parseFloat(row.querySelector('.max-marks')?.value) || 0;
        var obt = parseFloat(row.querySelector('.obtained-marks')?.value) || 0;
        totalObtained += obt;
        totalMax += max;
        var pct = max > 0 ? ((obt / max) * 100).toFixed(0) : 0;
        row.querySelector('.subject-pct').textContent = pct + '%';
    });

    document.getElementById('totalObtained').textContent = totalObtained;
    document.getElementById('totalMax').textContent = totalMax;

    var percentage = totalMax > 0 ? ((totalObtained / totalMax) * 100).toFixed(1) : 0;
    document.getElementById('totalPercentage').textContent = percentage + '%';

    // Grade
    var grade = 'F', division = 'Fail';
    if (percentage >= 90) { grade = 'A+'; division = 'First'; }
    else if (percentage >= 80) { grade = 'A'; division = 'First'; }
    else if (percentage >= 70) { grade = 'B+'; division = 'First'; }
    else if (percentage >= 60) { grade = 'B'; division = 'First'; }
    else if (percentage >= 45) { grade = 'C'; division = 'Second'; }
    else if (percentage >= 33) { grade = 'D'; division = 'Third'; }
    document.getElementById('totalGrade').textContent = grade;
    document.getElementById('totalDivision').textContent = division;

    // Update total cost
    updateCost();
}

// ─── Random fill marks ─────────────────────────────────────
function randomFillMarks() {
    document.querySelectorAll('.subject-row').forEach(function(row) {
        var max = parseFloat(row.querySelector('.max-marks')?.value) || 100;
        // Random between 60% and 95% of max marks
        var randomPct = 60 + Math.random() * 35;
        var obt = Math.round((randomPct / 100) * max);
        row.querySelector('.obtained-marks').value = obt;
    });
    calculateTotal();
}

function clearMarks() {
    document.querySelectorAll('.obtained-marks').forEach(function(el) { el.value = ''; });
    calculateTotal();
}

// ─── Calculate total cost ──────────────────────────────────
function updateCost() {
    var cost = 0;
    var certSel = document.getElementById('template_certificate');
    var msSel = document.getElementById('template_marksheet');
    if (certSel && certSel.value) {
        var opt = certSel.options[certSel.selectedIndex];
        cost += parseFloat(opt.dataset.cost) || 0;
    }
    if (msSel && msSel.value) {
        var opt = msSel.options[msSel.selectedIndex];
        cost += parseFloat(opt.dataset.cost) || 0;
    }
    document.getElementById('totalCost').textContent = '₹' + cost;
}

// ─── Attach listeners ──────────────────────────────────────
document.addEventListener('input', function(e) {
    if (e.target.classList.contains('obtained-marks') || e.target.classList.contains('max-marks')) {
        calculateTotal();
    }
});
document.getElementById('template_certificate')?.addEventListener('change', updateCost);
document.getElementById('template_marksheet')?.addEventListener('change', updateCost);

// Init
calculateTotal();
</script>
