<?php
ob_start();
$projectRoot = dirname(__DIR__); 
require_once $projectRoot . '/config/database.php'; 
require_once $projectRoot . '/config/config.php';   
require_once $projectRoot . '/includes/functions.php'; 

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
    header("Location: ../auth/login.php");
    exit();
}

$student_id = $_SESSION['user_id'];

function getSubjectRemark($score) {
    if ($score >= 75) return "Distinction";
    if ($score >= 60) return "Credit";
    if ($score >= 50) return "Merit";
    if ($score >= 40) return "Pass";
    return "Fail";
}

function formatPosition($n) {
    $res = array('th','st','nd','rd');
    return $n . ($res[($n % 100 > 10 && $n % 100 < 20) ? 0 : ($n % 10 < 4 ? $n % 10 : 0)]);
}

try {
    $stmtSet = $pdo->query("SELECT * FROM system_settings LIMIT 1");
    $settings = $stmtSet->fetch(PDO::FETCH_ASSOC);
    
    $current_session = $settings['active_session'] ?? "2025/2026";
    $current_term    = $settings['active_term'] ?? "FIRST TERM";
    $term_ends_date  = $settings['term_ends'] ?? date('Y-m-d');

    $stmtStudent = $pdo->prepare("SELECT s.*, c.class_name FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
    $stmtStudent->execute([$student_id]);
    $student = $stmtStudent->fetch(PDO::FETCH_ASSOC);
    $class_id = $student['class_id'];

    $stmtResults = $pdo->prepare("SELECT r.*, s.subject_name FROM results r JOIN subjects s ON r.subject_id = s.id WHERE r.student_id = :sid AND r.session = :sess AND r.term = :term AND r.is_approved = 1");
    $stmtResults->execute([':sid' => $student_id, ':sess' => $current_session, ':term' => $current_term]);
    $results = $stmtResults->fetchAll(PDO::FETCH_ASSOC);

    $stmtRank = $pdo->prepare("SELECT student_id, SUM(total_score) as aggregate FROM results WHERE session = :sess AND term = :term AND is_approved = 1 AND student_id IN (SELECT id FROM students WHERE class_id = :cid) GROUP BY student_id ORDER BY aggregate DESC");
    $stmtRank->execute([':sess' => $current_session, ':term' => $current_term, ':cid' => $class_id]);
    $rankings = $stmtRank->fetchAll(PDO::FETCH_ASSOC);

    $position = 0;
    foreach ($rankings as $index => $rank) {
        if ($rank['student_id'] == $student_id) { $position = $index + 1; break; }
    }
    $total_students = count($rankings);
} catch (PDOException $e) { die("Database Error"); }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Report - <?php echo $student['reg_number']; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700&family=Playfair+Display:wght@700&family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #003366; --secondary: #c5a059; --dark: #334155; }
        
        @page { size: A4; margin: 0; }
        body { background: #f0f0f0; font-family: 'Roboto', sans-serif; margin: 0; padding: 0; -webkit-print-color-adjust: exact; }

        /* NAVIGATION BAR */
        .no-print { 
            text-align: center; 
            padding: 15px; 
            background: #fff; 
            border-bottom: 1px solid #ddd;
            position: sticky; top: 0; z-index: 100;
            display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;
        }
        .btn {
            padding: 10px 20px; border-radius: 4px; text-decoration: none;
            font-weight: bold; font-size: 14px; display: inline-flex;
            align-items: center; cursor: pointer; border: none;
        }
        .btn-print { background: var(--primary); color: white; }
        .btn-back { background: var(--dark); color: white; }

        /* REPORT CONTAINER */
        .report-card {
            background: #fff;
            width: 210mm;
            min-height: 220mm;
            margin: 20px auto;
            padding: 15mm 20mm;
            box-sizing: border-box;
            position: relative;
            display: flex;
            flex-direction: column;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }

        .watermark {
            position: absolute; top: 40%; left: 50%; transform: translate(-50%, -50%) rotate(-30deg);
            width: 500px; opacity: 0.05; z-index: 0; pointer-events: none;
        }
        .watermark img { width: 100%; }

        header, section, .domains-grid, .footer-grid, .resumption-note { position: relative; z-index: 1; }

        header { 
            display: flex; align-items: center; justify-content: space-between;
            border-bottom: 4px double var(--primary); padding-bottom: 15px; margin-bottom: 25px;
        }
        .logo { width: 90px; height: 90px; object-fit: contain; }
        .school-info { text-align: center; flex: 1; }
        .school-info h1 { font-family: 'Playfair Display', serif; font-size: 28px; color: var(--primary); margin: 0; }
        .motto { font-family: 'Montserrat', sans-serif; color: var(--secondary); font-size: 11px; margin: 5px 0; text-transform: uppercase; letter-spacing: 1px; }
        .contact-block { font-size: 11px; color: #444; line-height: 1.4; }

        .student-header { 
            display: grid; grid-template-columns: 110px 1fr; gap: 20px; 
            background: #f8fafc; padding: 15px; border: 1px solid #ddd; margin-bottom: 25px; 
        }
        .student-photo { width: 110px; height: 120px; border: 3px solid #fff; object-fit: cover; box-shadow: 0 3px 6px rgba(0,0,0,0.1); }
        .meta-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
        .info-bit h4 { font-size: 10px; color: #888; text-transform: uppercase; margin: 0; }
        .info-bit p { font-size: 13px; font-weight: 700; color: #222; margin: 2px 0 0 0; }

        .table-responsive { width: 100%; overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 0; min-width: 600px; }
        th { background: var(--primary); color: #fff; padding: 12px; font-size: 11px; border: 1px solid #000; text-transform: uppercase; }
        td { border: 1px solid #000; padding: 10px; font-size: 13px; text-align: center; }
        .text-left { text-align: left; padding-left: 15px; font-weight: bold; }

        .summary-bar {
            display: grid; grid-template-columns: repeat(4, 1fr);
            background: #f1f5f9; border: 1px solid #000; border-top: none; 
            padding: 15px; font-weight: 800; color: var(--primary); font-size: 14px;
        }

        .domains-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-top: 25px; }
        .domain-table { min-width: 100%; }
        .domain-table th { background: #f8fafc; color: #333; font-size: 11px; padding: 8px; }
        .domain-table td { padding: 8px; font-size: 12px; }

        .footer-grid { display: grid; grid-template-columns: 1.2fr 0.9fr 0.9fr; gap: 25px; margin-top: 30px; }
        .remark-area { border: 1px solid #ccc; padding: 15px; background: #fffcf5; font-size: 12px; line-height: 1.6; border-radius: 4px; }
        .auth-card { border: 1px solid #ccc; padding: 12px; text-align: center; font-size: 11px; border-radius: 4px; }
        .auth-img { max-height: 60px; mix-blend-mode: multiply; margin-bottom: 5px; }
        .sig-date { border-top: 1px solid #333; font-weight: bold; padding-top: 8px; margin-top: 10px; }

        .resumption-note { margin-top: 30px; text-align: center; font-size: 12px; border-top: 1px dashed #ccc; padding-top: 15px; }

        /* RESPONSIVE MEDIA QUERIES */
        @media (max-width: 210mm) {
            .report-card {
                width: 95%;
                padding: 10mm;
                min-height: auto;
            }
        }

        @media (max-width: 768px) {
            .meta-grid { grid-template-columns: repeat(2, 1fr); }
            .summary-bar { grid-template-columns: repeat(2, 1fr); gap: 10px; }
            .domains-grid { grid-template-columns: 1fr; }
            .footer-grid { grid-template-columns: 1fr; }
            .school-info h1 { font-size: 20px; }
            header { flex-direction: column; gap: 10px; }
        }

        @media (max-width: 480px) {
            .student-header { grid-template-columns: 1fr; text-align: center; justify-items: center; }
            .meta-grid { grid-template-columns: 1fr; }
            .summary-bar { grid-template-columns: 1fr; text-align: center; }
        }

        /* PRINT STYLES */
        @media print { 
            body { background: #fff; } 
            .no-print { display: none; } 
            .report-card { 
                margin: 0; 
                border: none; 
                box-shadow: none; 
                width: 210mm; /* Force A4 Width */
                height: 297mm; /* Force A4 Height */
                padding: 15mm 20mm;
            }
            .table-responsive { overflow: visible; }
            table { min-width: 100%; }
            .meta-grid { grid-template-columns: repeat(3, 1fr); }
            .summary-bar { grid-template-columns: repeat(4, 1fr); }
            .domains-grid { grid-template-columns: 1fr 1fr; }
            .footer-grid { grid-template-columns: 1.2fr 0.9fr 0.9fr; }
        }
    </style>
</head>
<body>

<div class="no-print">
    <a href="dashboard.php" class="btn btn-back">← Back</a>
    <button onclick="window.print()" class="btn btn-print">Download Result</button>
</div>

<div class="report-card">
    <div class="watermark"><img src="../assets/img/logo.png" onerror="this.style.display='none'"></div>

    <header>
        <img src="../assets/img/logo.png" class="logo" onerror="this.src='https://via.placeholder.com/90'">
        <div class="school-info">
            <h1><?php echo strtoupper($settings['school_name']); ?></h1>
            <p class="motto"><?php echo $settings['motto']; ?></p>
            <div class="contact-block">
                <?php echo $settings['school_address']; ?><br>
                Tel: <?php echo $settings['school_phone']; ?> | Email: <?php echo $settings['school_email']; ?>
            </div>
        </div>
        <div style="width:90px;" class="hide-mobile"></div>
    </header>

    <section class="student-header">
        <img src="../uploads/students/<?php echo $student['photo']; ?>" class="student-photo" onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($student['fullname']); ?>&background=003366&color=fff'">
        <div class="meta-grid">
            <div class="info-bit"><h4>Full Name</h4><p><?php echo strtoupper($student['fullname']); ?></p></div>
            <div class="info-bit"><h4>Admission No.</h4><p><?php echo $student['reg_number']; ?></p></div>
            <div class="info-bit"><h4>Class Level</h4><p><?php echo $student['class_name']; ?></p></div>
            <div class="info-bit"><h4>Academic Session</h4><p><?php echo $current_session; ?></p></div>
            <div class="info-bit"><h4>Current Term</h4><p><?php echo $current_term; ?></p></div>
            <div class="info-bit"><h4>Class Size</h4><p><?php echo $total_students; ?></p></div>
        </div>
    </section>

    <section>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th width="40%">Subject Description</th>
                        <th>C.A</th>
                        <th>Exam</th>
                        <th>Total</th>
                        <th>Grade</th>
                        <th>Remark</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $grand_total = 0; foreach ($results as $row): $total = $row['total_score']; $grand_total += $total; ?>
                    <tr>
                        <td class="text-left"><?php echo strtoupper($row['subject_name']); ?></td>
                        <td><?php echo $row['ca_score']; ?></td>
                        <td><?php echo $row['exam_score']; ?></td>
                        <td><strong><?php echo $total; ?></strong></td>
                        <td><strong><?php echo calculateGrade($total); ?></strong></td>
                        <td style="font-size:11px;"><?php echo getSubjectRemark($total); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div class="summary-bar">
            <div>AGGREGATE: <?php echo $grand_total; ?></div>
            <div>AVG: <?php echo count($results) > 0 ? round($grand_total / count($results), 2) : 0; ?>%</div>
            <div style="color:#d35400">POS: <?php echo formatPosition($position); ?></div>
            <div>OUT OF: <?php echo $total_students; ?></div>
        </div>
    </section>

    <div class="domains-grid">
        <div class="table-responsive">
            <table class="domain-table">
                <thead><tr><th colspan="2">Affective Domain (Behaviour)</th></tr></thead>
                <tbody>
                    <tr><td class="text-left">Punctuality</td><td>A</td></tr>
                    <tr><td class="text-left">Neatness</td><td>A</td></tr>
                    <tr><td class="text-left">Relationship with Peers</td><td>A</td></tr>
                </tbody>
            </table>
        </div>
        <div class="table-responsive">
            <table class="domain-table">
                <thead><tr><th colspan="2">Psychomotor Domain (Skills)</th></tr></thead>
                <tbody>
                    <tr><td class="text-left">Handwriting</td><td>B</td></tr>
                    <tr><td class="text-left">Sports & Games</td><td>A</td></tr>
                    <tr><td class="text-left">Creativity</td><td>A</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <div class="footer-grid">
        <div class="remark-area">
            <strong>Principal's Final Remark:</strong><br>
            <p style="margin-top:10px; font-style:italic;">"<?php echo $student['principal_remark'] ?? 'A very consistent and commendable performance. Keep it up.'; ?>"</p>
        </div>
        <div class="auth-card">
            <h5>Official Stamp</h5>
            <img src="../assets/img/stamp.png" class="auth-img" onerror="this.style.opacity='0'">
            <div class="sig-date" style="border:none; color:#888;">STAMP AREA</div>
        </div>
        <div class="auth-card">
            <h5>Principal Signature</h5>
            <img src="../assets/img/signature.png" class="auth-img" onerror="this.style.opacity='0'">
            <div class="sig-date">DATE: <?php echo date('d M, Y', strtotime($term_ends_date)); ?></div>
        </div>
    </div>

    <div class="resumption-note">
        Next Term Resumption: <strong><?php echo isset($settings['next_term_begins']) ? date('d M, Y', strtotime($settings['next_term_begins'])) : 'TBA'; ?></strong>
    </div>
</div>

</body>
</html>