<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) && !isset($_GET['public'])) { header('Location: ../index.php'); exit(); }
if (file_exists(__DIR__ . '/../../db.php')) {
    require_once __DIR__ . '/../../db.php';
} elseif (file_exists(__DIR__ . '/../db.php')) {
    require_once __DIR__ . '/../db.php';
}

if (file_exists(__DIR__ . '/../../result_db_setup.php')) {
    require_once __DIR__ . '/../../result_db_setup.php';
} elseif (file_exists(__DIR__ . '/../result_db_setup.php')) {
    require_once __DIR__ . '/../result_db_setup.php';
} elseif (file_exists(__DIR__ . '/result_db_setup.php')) {
    require_once __DIR__ . '/result_db_setup.php';
}
setupResultTables($conn);

$student_id = intval($_GET['student_id'] ?? 0);
$term_id    = intval($_GET['term_id'] ?? 0);
$print_mode = isset($_GET['print']);

// If no student, show selector
if (!$student_id || !$term_id) {
    $classes = $conn->query("SELECT rc.*, rs.session_name FROM result_classes rc JOIN result_sessions rs ON rc.session_id=rs.id ORDER BY rs.is_active DESC, rc.numeric_level, rc.section");
    $terms   = $conn->query("SELECT rt.*, rs.session_name FROM result_terms rt JOIN result_sessions rs ON rt.session_id=rs.id ORDER BY rs.is_active DESC, rt.display_order");
    $selected_class = intval($_GET['class_id'] ?? 0);
    $students_list = [];
    if ($selected_class) {
        $sr = $conn->query("SELECT id,first_name,last_name,admission_no,roll_no FROM result_students WHERE class_id=$selected_class AND is_active=1 ORDER BY roll_no");
        while($s=$sr->fetch_assoc()) $students_list[] = $s;
    }
    // Show selector UI
    include_once('_report_selector.php');
    exit;
}

// ---- FETCH STUDENT DATA ----
$student = $conn->query("SELECT rs.*, rc.class_name, rc.section, rc.numeric_level, sess.session_name
    FROM result_students rs
    JOIN result_classes rc ON rs.class_id=rc.id
    JOIN result_sessions sess ON rc.session_id=sess.id
    WHERE rs.id=$student_id")->fetch_assoc();

if (!$student) { echo "<div class='alert alert-danger m-4'>Student not found.</div>"; exit; }

$term = $conn->query("SELECT * FROM result_terms WHERE id=$term_id")->fetch_assoc();

// Marks
$marks_res = $conn->query("
    SELECT m.marks_obtained, m.status, es.max_marks, es.pass_marks, es.component_name, es.weightage,
           s.subject_name, s.subject_code, s.grading_type, s.is_scholastic
    FROM result_marks m
    JOIN result_exam_structure es ON m.exam_structure_id=es.id
    JOIN result_subjects s ON es.subject_id=s.id
    WHERE m.student_id=$student_id AND es.term_id=$term_id AND s.is_scholastic=1
    ORDER BY s.subject_name, es.component_name
");

$subjects_data = [];
$totalObt = 0; $totalMax = 0; $failSubjects = 0;
while($m=$marks_res->fetch_assoc()) {
    $sname = $m['subject_name'];
    if (!isset($subjects_data[$sname])) $subjects_data[$sname] = ['components'=>[],'grading_type'=>$m['grading_type'],'total_obt'=>0,'total_max'=>0,'status'=>'pass'];
    $subjects_data[$sname]['components'][] = $m;
    if ($m['grading_type']=='NUMERIC' && $m['status']=='present' && $m['marks_obtained']!==null) {
        $subjects_data[$sname]['total_obt'] += floatval($m['marks_obtained']);
        $subjects_data[$sname]['total_max'] += floatval($m['max_marks']);
        $totalObt += floatval($m['marks_obtained']);
        $totalMax += floatval($m['max_marks']);
    } elseif (!isset($subjects_data[$sname]['total_max_counted'])) {
        $subjects_data[$sname]['total_max'] += floatval($m['max_marks']);
        $totalMax += floatval($m['max_marks']);
        $subjects_data[$sname]['total_max_counted'] = true;
    }
}
// Calculate per-subject grade
foreach($subjects_data as $sn=>&$sd) {
    if ($sd['grading_type']=='NUMERIC' && $sd['total_max']>0) {
        $pct = ($sd['total_obt']/$sd['total_max'])*100;
        $g = getGrade($conn, $pct, $student['numeric_level']<=2?'PREPRIMARY':'PRIMARY');
        $sd['percentage'] = round($pct,1);
        $sd['grade'] = $g['grade_letter'];
        $sd['grade_point'] = $g['grade_point'];
        $sd['description'] = $g['description'];
        if ($sd['total_obt'] < ($sd['total_max'] * 0.33)) { $sd['status']='fail'; $failSubjects++; }
    }
}

$overallPct = $totalMax>0 ? round(($totalObt/$totalMax)*100,2) : 0;
$overallGrade = getGrade($conn, $overallPct, $student['numeric_level']<=2?'PREPRIMARY':'PRIMARY');
$result_status = ($failSubjects==0 && count($subjects_data)>0) ? 'PASS' : 'FAIL';

// Attendance
$att = $conn->query("SELECT * FROM result_attendance WHERE student_id=$student_id AND term_id=$term_id")->fetch_assoc();

// Co-scholastic
$coscho = $conn->query("SELECT * FROM result_coscholastic WHERE student_id=$student_id AND term_id=$term_id");

// Remarks
$remarks = $conn->query("SELECT * FROM result_remarks WHERE student_id=$student_id AND term_id=$term_id")->fetch_assoc();

// Rank in class
$rank_res = $conn->query("
    SELECT s2.student_id, SUM(m2.marks_obtained) as total
    FROM result_marks m2
    JOIN result_exam_structure es2 ON m2.exam_structure_id=es2.id
    JOIN result_students s2 ON m2.student_id=s2.id
    WHERE s2.class_id={$student['class_id']} AND es2.term_id=$term_id AND m2.status='present' AND m2.marks_obtained IS NOT NULL
    GROUP BY s2.student_id ORDER BY total DESC
");
$rank = 1; $rankFound = false;
while($r=$rank_res->fetch_assoc()) {
    if ($r['student_id']==$student_id) { $rankFound=true; break; }
    $rank++;
}
if (!$rankFound) $rank = '--';

$is_preprimary = $student['numeric_level'] <= 2;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Report Card - <?= htmlspecialchars($student['first_name'].' '.$student['last_name']) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
    <style>
        /* ===== SCREEN STYLES ===== */
        body { background:#e2e8f0; font-family:'Inter',sans-serif; margin:0; padding:20px; }
        .screen-controls { max-width:900px; margin:0 auto 16px; display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
        .screen-controls .btn { padding:8px 18px; border-radius:8px; font-size:13px; font-weight:600; cursor:pointer; border:none; }
        .btn-print { background:#0b3b60; color:#fff; }
        .btn-back { background:#fff; color:#374151; border:1.5px solid #e2e8f0; }
        .btn-print:hover { background:#1a6ba0; }

        /* ===== REPORT CARD ===== */
        .report-card {
            max-width:900px; margin:0 auto; background:#fff;
            box-shadow:0 10px 50px rgba(0,0,0,0.15); border-radius:4px;
            overflow:hidden;
        }

        /* HEADER */
        .rc-header {
            background:linear-gradient(135deg, #0b3b60 0%, #1a6ba0 60%, #0b3b60 100%);
            color:#fff; padding:24px 30px; display:flex; align-items:center; gap:20px;
        }
        .rc-logo { width:80px; height:80px; border-radius:50%; background:#fff; display:flex; align-items:center; justify-content:center; overflow:hidden; flex-shrink:0; }
        .rc-logo img { width:100%;height:100%;object-fit:contain; }
        .rc-logo-text { font-size:24px; font-weight:800; color:#0b3b60; }
        .rc-school-info { flex:1; text-align:center; }
        .rc-school-info h2 { font-family:'Playfair Display',serif; font-size:24px; margin:0 0 4px; letter-spacing:0.5px; }
        .rc-school-info p { margin:0; font-size:11.5px; opacity:0.85; }
        .rc-session-badge { background:rgba(255,255,255,0.15); padding:4px 12px; border-radius:20px; font-size:11px; font-weight:600; margin-top:6px; display:inline-block; }
        .rc-term-label { background: #f5a623; color:#1e293b; padding:3px 12px; border-radius:20px; font-size:11px; font-weight:700; }

        /* TITLE BAR */
        .rc-title-bar { background:#f5a623; color:#1e293b; text-align:center; padding:8px; font-weight:700; font-size:14px; letter-spacing:1px; text-transform:uppercase; }

        /* STUDENT INFO */
        .rc-student-info { padding:16px 30px; display:grid; grid-template-columns:1fr auto; gap:20px; border-bottom:2px solid #e2e8f0; }
        .info-grid { display:grid; grid-template-columns:1fr 1fr; gap:6px 30px; }
        .info-row { display:flex; gap:6px; font-size:12.5px; }
        .info-label { color:#64748b; font-weight:600; min-width:110px; white-space:nowrap; }
        .info-value { color:#1e293b; font-weight:500; }
        .rc-photo { width:80px; height:96px; border:2px solid #e2e8f0; border-radius:6px; background:#f8fafc; display:flex; align-items:center; justify-content:center; flex-shrink:0; }
        .rc-photo img { width:100%;height:100%;object-fit:cover;border-radius:4px; }

        /* MARKS TABLE */
        .rc-section-title {
            background:#0b3b60; color:#fff; padding:7px 20px;
            font-size:12px; font-weight:700; text-transform:uppercase; letter-spacing:0.8px;
        }
        .marks-table { width:100%; border-collapse:collapse; font-size:12px; }
        .marks-table th { background:#1e293b; color:#fff; padding:8px 12px; text-align:center; font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:0.5px; }
        .marks-table th:first-child { text-align:left; }
        .marks-table td { padding:7px 12px; border:1px solid #e2e8f0; text-align:center; }
        .marks-table td:first-child { text-align:left; font-weight:500; }
        .marks-table tr:nth-child(even) { background:#f8fafc; }
        .marks-table tr.total-row { background:#dbeafe; font-weight:700; }
        .marks-table tr.fail-row { background:#fee2e2; }
        .grade-badge { display:inline-block; padding:2px 8px; border-radius:12px; font-weight:700; font-size:11px; }
        .grade-A1,.grade-A2 { background:#dcfce7;color:#166534; }
        .grade-B1,.grade-B2 { background:#dbeafe;color:#1e40af; }
        .grade-C1,.grade-C2 { background:#fef3c7;color:#92400e; }
        .grade-D { background:#fed7aa;color:#9a3412; }
        .grade-E,.grade-Fail { background:#fee2e2;color:#991b1b; }
        .grade-Ap { background:#dcfce7;color:#166534; }
        .grade-A { background:#d1fae5;color:#065f46; }
        .grade-B { background:#dbeafe;color:#1e40af; }
        .grade-C { background:#fef3c7;color:#92400e; }

        /* ATTENDANCE & CO-SCHOLASTIC */
        .rc-two-col { display:grid; grid-template-columns:1fr 1fr; gap:0; }
        .att-table,.coscho-table { width:100%; border-collapse:collapse; font-size:12px; }
        .att-table td,.coscho-table td { padding:7px 14px; border:1px solid #e2e8f0; }
        .att-table td:first-child { font-weight:600; color:#374151; }
        .coscho-table td:first-child { font-weight:500; }

        /* RESULT SUMMARY */
        .rc-summary { display:grid; grid-template-columns:repeat(4,1fr); border-top:2px solid #0b3b60; }
        .summary-box { padding:14px; text-align:center; border-right:1px solid #e2e8f0; }
        .summary-box:last-child { border-right:none; }
        .summary-box .label { font-size:10px; text-transform:uppercase; letter-spacing:0.5px; color:#64748b; font-weight:600; }
        .summary-box .value { font-size:22px; font-weight:800; color:#0b3b60; margin-top:4px; }
        .summary-box.pass .value { color:#059669; }
        .summary-box.fail .value { color:#ef4444; }

        /* REMARKS */
        .remarks-row { display:grid; grid-template-columns:1fr 1fr; border-top:1px solid #e2e8f0; }
        .remark-box { padding:14px 20px; border-right:1px solid #e2e8f0; }
        .remark-box:last-child { border-right:none; }
        .remark-label { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:0.5px; color:#64748b; margin-bottom:4px; }
        .remark-text { font-size:12px; color:#374151; min-height:32px; }
        .sig-line { border-top:1.5px solid #374151; margin-top:30px; width:140px; padding-top:4px; font-size:10px; color:#64748b; text-align:center; }

        /* FOOTER */
        .rc-footer { background:#f8fafc; border-top:1px solid #e2e8f0; padding:10px 24px; display:flex; justify-content:space-between; align-items:center; font-size:10.5px; color:#64748b; }

        /* ===== PRINT STYLES ===== */
        @media print {
            body { background:#fff; padding:0; margin:0; }
            .screen-controls { display:none; }
            .report-card { box-shadow:none; max-width:100%; border-radius:0; }
            .marks-table { page-break-inside:avoid; }
        }
    </style>
</head>
<body>

<!-- SCREEN CONTROLS -->
<div class="screen-controls">
    <button class="btn btn-back" onclick="history.back()">← Back</button>
    <button class="btn btn-print" onclick="window.print()">🖨️ Print Report Card</button>
    <a href="?student_id=<?= $student_id ?>&term_id=<?= $term_id ?>&print=1" class="btn btn-print" style="background:#059669">📄 PDF View</a>
    <?php
    // Previous/Next student in same class
    $prev_next = $conn->query("SELECT id,first_name,last_name FROM result_students WHERE class_id={$student['class_id']} AND is_active=1 ORDER BY roll_no,first_name");
    $allStu=[]; while($x=$prev_next->fetch_assoc()) $allStu[]=$x;
    $myIdx = array_search($student_id, array_column($allStu,'id'));
    if ($myIdx!==false && $myIdx>0): $prev=$allStu[$myIdx-1]; ?>
    <a href="?student_id=<?= $prev['id'] ?>&term_id=<?= $term_id ?>" class="btn btn-back">← <?= htmlspecialchars($prev['first_name']) ?></a>
    <?php endif; if ($myIdx!==false && $myIdx<count($allStu)-1): $next=$allStu[$myIdx+1]; ?>
    <a href="?student_id=<?= $next['id'] ?>&term_id=<?= $term_id ?>" class="btn btn-back"><?= htmlspecialchars($next['first_name']) ?> →</a>
    <?php endif; ?>
</div>

<!-- REPORT CARD -->
<div class="report-card">
    <!-- HEADER -->
    <div class="rc-header">
        <div class="rc-logo">
            <div class="rc-logo-text">BS</div>
        </div>
        <div class="rc-school-info">
            <h2>B.S. Public School</h2>
            <p>Affiliated to CBSE | Nursery to Class 8</p>
            <p>bspspublicschool.in | Excellence in Education Since 2005</p>
            <div class="mt-2">
                <span class="rc-session-badge">Session: <?= htmlspecialchars($student['session_name']) ?></span>
                &nbsp;
                <span class="rc-term-label"><?= htmlspecialchars($term['term_name'] ?? '') ?></span>
            </div>
        </div>
        <div class="rc-logo">
            <div class="rc-logo-text">🏫</div>
        </div>
    </div>

    <div class="rc-title-bar">STUDENT REPORT CARD / PROGRESS REPORT</div>

    <!-- STUDENT INFO -->
    <div class="rc-student-info">
        <div class="info-grid">
            <div class="info-row"><span class="info-label">Student Name</span><span class="info-value fw-bold"><?= htmlspecialchars($student['first_name'].' '.$student['last_name']) ?></span></div>
            <div class="info-row"><span class="info-label">Admission No</span><span class="info-value"><?= htmlspecialchars($student['admission_no']) ?></span></div>
            <div class="info-row"><span class="info-label">Class & Section</span><span class="info-value"><?= htmlspecialchars($student['class_name'].' - '.$student['section']) ?></span></div>
            <div class="info-row"><span class="info-label">Roll Number</span><span class="info-value"><?= $student['roll_no'] ?: '--' ?></span></div>
            <div class="info-row"><span class="info-label">Father's Name</span><span class="info-value"><?= htmlspecialchars($student['father_name'] ?: '--') ?></span></div>
            <div class="info-row"><span class="info-label">Mother's Name</span><span class="info-value"><?= htmlspecialchars($student['mother_name'] ?: '--') ?></span></div>
            <div class="info-row"><span class="info-label">Date of Birth</span><span class="info-value"><?= $student['dob'] ? date('d/m/Y',strtotime($student['dob'])) : '--' ?></span></div>
            <div class="info-row"><span class="info-label">Gender</span><span class="info-value"><?= $student['gender'] ?></span></div>
        </div>
        <div class="rc-photo">
            <?php if($student['photo']): ?>
            <img src="../../uploads/students/<?= htmlspecialchars($student['photo']) ?>" alt="Photo">
            <?php else: ?>
            <div style="text-align:center;font-size:10px;color:#94a3b8"><div style="font-size:28px">👤</div>Photo</div>
            <?php endif; ?>
        </div>
    </div>

    <!-- SCHOLASTIC MARKS -->
    <div class="rc-section-title">📚 Scholastic Assessment</div>
    <table class="marks-table">
        <thead>
            <tr>
                <th style="width:28%">Subject</th>
                <?php
                // Get unique components
                $components = [];
                foreach($subjects_data as $sd) {
                    foreach($sd['components'] as $c) {
                        $comp = $c['component_name'] ?: 'Marks';
                        if (!in_array($comp,$components)) $components[] = $comp;
                    }
                }
                foreach($components as $comp): ?>
                <th><?= htmlspecialchars($comp) ?></th>
                <?php endforeach; ?>
                <th>Total</th>
                <th>Max</th>
                <th>%</th>
                <th>Grade</th>
                <th>Remarks</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($subjects_data as $sname=>$sd):
                $rowClass = ($sd['status']??'pass')=='fail' ? 'fail-row' : '';
                $gradeClass = 'grade-'.str_replace(['+','-'],['p','m'], ($sd['grade'] ?? ''));
            ?>
            <tr class="<?= $rowClass ?>">
                <td><?= htmlspecialchars($sname) ?></td>
                <?php foreach($components as $comp):
                    $found = null;
                    foreach($sd['components'] as $c) {
                        if (($c['component_name']?:'Marks') == $comp) { $found=$c; break; }
                    }
                    if ($found):
                        if ($found['status']=='absent') echo '<td><span style="color:#dc2626;font-weight:700">AB</span></td>';
                        elseif ($found['status']=='medical') echo '<td><span style="color:#d97706">ML</span></td>';
                        elseif ($found['status']=='exempted') echo '<td><span style="color:#7c3aed">EX</span></td>';
                        else echo '<td>'.($found['marks_obtained']!==null ? ($found['marks_obtained']+0) : '--').'</td>';
                    else: ?>
                    <td style="color:#94a3b8">--</td>
                    <?php endif; endforeach; ?>
                <td><strong><?= $sd['total_obt'] ?? '--' ?></strong></td>
                <td><?= $sd['total_max'] ?? '--' ?></td>
                <td><?= isset($sd['percentage']) ? $sd['percentage'].'%' : '--' ?></td>
                <td><span class="grade-badge <?= $gradeClass ?>"><?= $sd['grade'] ?? '--' ?></span></td>
                <td style="font-size:11px;color:#64748b"><?= $sd['description'] ?? '' ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- RESULT SUMMARY -->
    <div class="rc-summary">
        <div class="summary-box">
            <div class="label">Total Marks</div>
            <div class="value"><?= $totalObt.'/'.$totalMax ?></div>
        </div>
        <div class="summary-box">
            <div class="label">Percentage</div>
            <div class="value"><?= $overallPct ?>%</div>
        </div>
        <div class="summary-box">
            <div class="label">Overall Grade</div>
            <div class="value" style="color:#7c3aed"><?= $overallGrade['grade_letter'] ?></div>
        </div>
        <div class="summary-box <?= $result_status=='PASS'?'pass':'fail' ?>">
            <div class="label">Result</div>
            <div class="value"><?= $result_status ?></div>
        </div>
    </div>

    <!-- ATTENDANCE + CO-SCHOLASTIC -->
    <div class="rc-two-col">
        <div>
            <div class="rc-section-title" style="font-size:11px">📅 Attendance</div>
            <table class="att-table">
                <tr><td>Total Working Days</td><td style="text-align:center"><?= $att['total_days'] ?? '--' ?></td></tr>
                <tr><td>Days Present</td><td style="text-align:center"><?= $att['attended_days'] ?? '--' ?></td></tr>
                <tr><td>Days Absent</td><td style="text-align:center"><?= isset($att['total_days'],$att['attended_days']) ? ($att['total_days']-$att['attended_days']) : '--' ?></td></tr>
                <tr><td>Attendance %</td><td style="text-align:center;font-weight:700">
                    <?= (isset($att['total_days'],$att['attended_days']) && $att['total_days']>0) ? round($att['attended_days']/$att['total_days']*100,1).'%' : '--' ?>
                </td></tr>
            </table>
        </div>
        <div>
            <div class="rc-section-title" style="font-size:11px">🎨 Co-Scholastic Assessment</div>
            <table class="coscho-table">
                <?php if ($coscho && $coscho->num_rows>0): while($c=$coscho->fetch_assoc()): ?>
                <tr>
                    <td><?= htmlspecialchars($c['activity_name']) ?></td>
                    <td style="text-align:center"><span class="grade-badge grade-<?= $c['grade'] ?>"><?= $c['grade'] ?></span></td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="2" style="color:#94a3b8;text-align:center;padding:20px">Not yet entered</td></tr>
                <?php endif; ?>
            </table>
        </div>
    </div>

    <!-- GRADING SCALE LEGEND -->
    <div style="padding:10px 20px;background:#f8fafc;border-top:1px solid #e2e8f0;border-bottom:1px solid #e2e8f0">
        <div style="font-size:10px;font-weight:700;text-transform:uppercase;color:#64748b;margin-bottom:4px">Grading Scale:</div>
        <div style="display:flex;flex-wrap:wrap;gap:8px;font-size:10.5px">
            <?php if(!$is_preprimary): ?>
            <span>A1 (91-100)</span><span>A2 (81-90)</span><span>B1 (71-80)</span><span>B2 (61-70)</span>
            <span>C1 (51-60)</span><span>C2 (41-50)</span><span>D (33-40)</span><span>E (&lt;33 Fail)</span>
            <?php else: ?>
            <span>A+ (Outstanding)</span><span>A (Very Good)</span><span>B (Good)</span><span>C (Satisfactory)</span><span>D (Needs Improvement)</span>
            <?php endif; ?>
        </div>
    </div>

    <!-- REMARKS -->
    <div class="remarks-row">
        <div class="remark-box">
            <div class="remark-label">Class Teacher's Remarks</div>
            <div class="remark-text"><?= htmlspecialchars($remarks['class_teacher_remarks'] ?? 'Good performance. Keep it up.') ?></div>
            <div class="sig-line">Class Teacher's Signature</div>
        </div>
        <div class="remark-box">
            <div class="remark-label">Principal's Remarks</div>
            <div class="remark-text"><?= htmlspecialchars($remarks['principal_remarks'] ?? 'Promoted to next class. Best wishes!') ?></div>
            <div class="sig-line">Principal's Signature</div>
        </div>
    </div>

    <!-- FOOTER -->
    <div class="rc-footer">
        <div><strong>Rank in Class:</strong> <?= $rank ?></div>
        <div>This is a computer-generated report card.</div>
        <div><strong>Date:</strong> <?= date('d/m/Y') ?></div>
    </div>
</div>

<script>
// Auto-print if ?print is set
<?php if($print_mode): ?>window.addEventListener('load',()=>window.print());<?php endif; ?>
</script>
</body>
</html>
