<?php
/** @var array $student */
/** @var array $subjects */
/** @var array $months */
/** @var string $csrfToken */

$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';

// Parse course duration to calculate months for auto-date calc
$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;

// Build months dropdown — last 2 years only (24 months), Month Year format
$monthsDropdown = [];
$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);  // e.g., "January 2026"
    $monthsDropdown[$value] = $label;
}
?>
<style>
.subject-row { background: #f8f9fa; }
.subject-row:hover { background: #e9ecef; }
.calc-preview {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    border-left: 4px solid #2196f3;
    padding: 12px 16px;
    border-radius: 6px;
    margin: 10px 0;
}
.calc-preview strong { color: #0d47a1; }
</style>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2><i class="fas fa-clipboard-check"></i> Create Result</h2>
            <p class="text-muted mb-0">
                <strong><?= htmlspecialchars($student['name'] ?? '') ?></strong>
                — <?= htmlspecialchars($student['course_name'] ?? '') ?>
                (Duration: <?= htmlspecialchars($courseDuration) ?>)
            </p>
        </div>
        <a href="<?= $bp ?>/branch/cert-gen" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Back
        </a>
    </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 ?? '') ?>">
        <input type="hidden" name="course_duration" id="course_duration" value="<?= htmlspecialchars($courseDuration) ?>">
        <input type="hidden" name="duration_months" id="duration_months" value="<?= $durationMonths ?>">

        <div class="card mb-3">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-calendar-alt"></i> Session Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Completion Month <span class="text-danger">*</span></label>
                        <select name="completion_month" id="completion_month" class="form-select form-select-lg" required>
                            <option value="">— Select Completion Month —</option>
                            <?php foreach ($monthsDropdown as $val => $lbl): ?>
                                <option value="<?= $val ?>"><?= htmlspecialchars($lbl) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-muted">Showing last 2 years (24 months). Format: Month Year</small>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Issue Date <span class="text-danger">*</span></label>
                        <input type="date" name="issue_date" id="issue_date" class="form-control form-control-lg"
                               value="<?= date('Y-m-d') ?>">
                        <small class="text-muted">Default: random date in completion month. You can change it.</small>
                    </div>
                </div>

                <div class="calc-preview" id="session_preview" style="display:none;">
                    <i class="fas fa-info-circle"></i>
                    <strong>Auto-calculated Session:</strong>
                    <span id="session_text">—</span>
                    <br><small class="text-muted">Based on course duration (<?= htmlspecialchars($courseDuration) ?>)</small>
                </div>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="fas fa-book"></i> Subjects & Marks</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered" id="subjectsTable">
                        <thead class="table-light">
                            <tr>
                                <th width="50">#</th>
                                <th>Subject Name</th>
                                <th width="120">Max Marks</th>
                                <th width="140">Obtained Marks</th>
                                <th width="80">%</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($subjects as $i => $s): ?>
                            <tr class="subject-row">
                                <td><?= $i + 1 ?></td>
                                <td>
                                    <input type="text" name="subject_name[]" class="form-control"
                                           value="<?= htmlspecialchars($s['name'] ?? 'Subject ' . ($i+1)) ?>" required>
                                </td>
                                <td>
                                    <input type="number" name="max_marks[]" class="form-control max-marks"
                                           value="<?= htmlspecialchars($s['max_marks'] ?? 100) ?>" min="1" required>
                                </td>
                                <td>
                                    <input type="number" name="obtained_marks[]" class="form-control obt-marks"
                                           value="0" min="0" required>
                                </td>
                                <td class="percent-cell">—</td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot class="table-light">
                            <tr>
                                <th colspan="2" class="text-end">TOTAL</th>
                                <th id="total_max">0</th>
                                <th id="total_obt">0</th>
                                <th id="total_pct">0%</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="row mt-3">
                    <div class="col-md-4">
                        <label class="form-label">Calculated Percentage</label>
                        <input type="text" id="calc_percentage" class="form-control form-control-lg" readonly>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Grade (auto)</label>
                        <input type="text" id="calc_grade" class="form-control form-control-lg" readonly>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Division (auto)</label>
                        <input type="text" id="calc_division" class="form-control form-control-lg" readonly>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-header bg-warning">
                <h5 class="mb-0"><i class="fas fa-credit-card"></i> Payment Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <label class="form-label">Payment Mode</label>
                        <select name="payment_mode" id="payment_mode" class="form-select">
                            <option value="offline">Offline (Cash)</option>
                            <option value="online">Online</option>
                            <option value="upi">UPI</option>
                            <option value="wallet">Wallet</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Transaction ID <small class="text-muted">(if offline)</small></label>
                        <input type="text" name="transaction_id" class="form-control" placeholder="Optional for offline">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Amount (₹)</label>
                        <input type="number" name="total_amount" class="form-control" value="200" min="0" step="0.01">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Payment Date</label>
                        <input type="date" name="payment_date" class="form-control" value="<?= date('Y-m-d') ?>">
                    </div>
                </div>
            </div>
        </div>

        <div class="d-flex justify-content-between">
            <a href="<?= $bp ?>/branch/cert-gen" class="btn btn-secondary btn-lg">
                <i class="fas fa-times"></i> Cancel
            </a>
            <button type="submit" class="btn btn-primary btn-lg" id="submitBtn">
                <i class="fas fa-paper-plane"></i> Submit for Approval
            </button>
        </div>
    </form>
</div>

<script>
const DURATION_MONTHS = <?= $durationMonths ?>;

// ─── Auto-calculate session dates when completion month changes ─────────
document.getElementById('completion_month').addEventListener('change', function() {
    const completionValue = this.value;  // "2026-01"
    if (!completionValue) {
        document.getElementById('session_preview').style.display = 'none';
        return;
    }

    // Parse completion month
    const [year, month] = completionValue.split('-').map(Number);
    const completionDate = new Date(year, month - 1, 1);

    // Calculate start month = completion - (duration - 1) months
    const startDate = new Date(completionDate);
    startDate.setMonth(startDate.getMonth() - (DURATION_MONTHS - 1));

    // Format labels
    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const fromLabel = monthNames[startDate.getMonth()] + ' ' + startDate.getFullYear();
    const toLabel = monthNames[completionDate.getMonth()] + ' ' + completionDate.getFullYear();

    // Show preview
    document.getElementById('session_preview').style.display = 'block';
    document.getElementById('session_text').textContent = fromLabel + ' to ' + toLabel + ' (' + DURATION_MONTHS + ' months)';

    // Set default issue_date = random date in completion month
    const lastDay = new Date(completionDate.getFullYear(), completionDate.getMonth() + 1, 0).getDate();
    const randomDay = Math.floor(Math.random() * lastDay) + 1;
    const issueDate = completionDate.getFullYear() + '-' +
                      String(completionDate.getMonth() + 1).padStart(2, '0') + '-' +
                      String(randomDay).padStart(2, '0');
    document.getElementById('issue_date').value = issueDate;
});

// ─── Auto-calculate totals, percentage, grade ───────────────────────────
function calculateTotals() {
    let totalMax = 0, totalObt = 0;
    const rows = document.querySelectorAll('#subjectsTable tbody tr');

    rows.forEach(row => {
        const max = parseFloat(row.querySelector('.max-marks').value) || 0;
        const obt = parseFloat(row.querySelector('.obt-marks').value) || 0;
        const pct = max > 0 ? ((obt / max) * 100).toFixed(1) : 0;
        row.querySelector('.percent-cell').textContent = pct + '%';
        totalMax += max;
        totalObt += obt;
    });

    const percentage = totalMax > 0 ? ((totalObt / totalMax) * 100).toFixed(2) : 0;
    document.getElementById('total_max').textContent = totalMax;
    document.getElementById('total_obt').textContent = totalObt;
    document.getElementById('total_pct').textContent = percentage + '%';
    document.getElementById('calc_percentage').value = percentage + '%';

    // Calculate grade
    const pct = parseFloat(percentage);
    let grade = 'F';
    if (pct >= 90) grade = 'A+';
    else if (pct >= 80) grade = 'A';
    else if (pct >= 70) grade = 'B+';
    else if (pct >= 60) grade = 'B';
    else if (pct >= 45) grade = 'C';
    else if (pct >= 33) grade = 'D';
    document.getElementById('calc_grade').value = grade;

    // Calculate division
    let division = 'Fail';
    if (pct >= 60) division = 'First Division';
    else if (pct >= 45) division = 'Second Division';
    else if (pct >= 33) division = 'Third Division';
    document.getElementById('calc_division').value = division;
}

document.querySelectorAll('.max-marks, .obt-marks').forEach(input => {
    input.addEventListener('input', calculateTotals);
});

// Initial calculation
calculateTotals();

// ─── Form submit confirmation ───────────────────────────────────────────
document.getElementById('resultForm').addEventListener('submit', function(e) {
    const completionMonth = document.getElementById('completion_month').value;
    if (!completionMonth) {
        e.preventDefault();
        alert('Please select completion month!');
        return;
    }
    if (!confirm('Submit this result for Super Admin approval?')) {
        e.preventDefault();
    }
});
</script>
