<?php
// admin/results/bulk_view.php
session_start();
$projectRoot = dirname(dirname(__DIR__)); 
require_once $projectRoot . "/config/database.php";

// 1. SECURITY CHECK (Admin & Sub-Admin)
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../../auth/login.php"); 
    exit(); 
}

$class_id = $_GET['class_id'] ?? null;
$session = $_GET['session'] ?? '';
$term = $_GET['term'] ?? '';

if (!$class_id || !$session || !$term) {
    die("Error: Please select class parameters.");
}

try {
    // 2. FETCH SYSTEM SETTINGS
    $stmtSet = $pdo->query("SELECT * FROM system_settings WHERE id = 1");
    $settings = $stmtSet->fetch(PDO::FETCH_ASSOC);

    // 3. FETCH ALL STUDENTS IN THE CLASS
    $stmtStud = $pdo->prepare("SELECT s.*, c.class_name 
                               FROM students s 
                               JOIN classes c ON s.class_id = c.id 
                               WHERE s.class_id = ? 
                               ORDER BY s.fullname ASC");
    $stmtStud->execute([$class_id]);
    $students = $stmtStud->fetchAll(PDO::FETCH_ASSOC);

    $displayClassName = (count($students) > 0) ? $students[0]['class_name'] : "Selected Class";

} catch (PDOException $e) { 
    die("Database Error: " . $e->getMessage()); 
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bulk Results - <?= htmlspecialchars($displayClassName) ?></title>
    <style>
        /* Shared Report Card Styles */
        body { font-family: 'Segoe UI', Arial, sans-serif; background: #555; padding: 0; margin: 0; }
        
        /* Mobile Wrapper to allow scrolling of the fixed-width report */
        .report-wrapper { width: 100%; overflow-x: auto; padding: 20px 0; }

        .report-card { 
            background: white; width: 850px; margin: 0 auto 30px auto; padding: 40px; 
            border: 10px double #2c3e50; position: relative; box-shadow: 0 0 20px rgba(0,0,0,0.5); 
            page-break-after: always;
            box-sizing: border-box;
        }
        
        .header-box { display: flex; align-items: center; justify-content: space-between; border-bottom: 3px solid #000; padding-bottom: 15px; margin-bottom: 20px; }
        .school-info { flex: 1; text-align: center; }
        .school-info h1 { margin: 0; font-size: 26px; color: #2c3e50; }
        .logo { width: 80px; height: 80px; object-fit: contain; }
        .passport { width: 100px; height: 100px; border: 2px solid #000; object-fit: cover; }
        
        .info-table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
        .info-table td { padding: 5px; font-size: 14px; }
        
        .main-results { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
        .main-results th { background: #2c3e50; color: white; padding: 10px; border: 1px solid #000; font-size: 12px; }
        .main-results td { border: 1px solid #000; padding: 8px; text-align: center; font-size: 13px; }
        
        .assessment-grid { display: grid; grid-template-columns: 1fr 1.5fr; gap: 15px; margin-bottom: 20px; }
        .mini-box { border: 1px solid #000; padding: 10px; font-size: 12px; min-height: 100px; }
        .mini-box h4 { margin: 0 0 5px 0; background: #eee; padding: 3px; font-size: 13px; text-align: center; border-bottom: 1px solid #000; text-transform: uppercase; }
        
        .official-section { border: 2px solid #000; padding: 20px; text-align: center; position: relative; margin-top: 10px; }
        .stamp-img { position: absolute; top: 15px; right: 50px; width: 110px; opacity: 0.5; z-index: 5; pointer-events: none; }
        .signature-center { display: flex; flex-direction: column; align-items: center; margin-top: 20px; }
        .sig-line { border-top: 1px solid #000; width: 200px; margin-top: 5px; padding-top: 8px; font-weight: bold; font-size: 13px; }

        .term-dates-bar { background: #f2f2f2; border: 1px solid #000; padding: 8px; margin-top: 15px; font-size: 12px; text-align: center; font-weight: bold; }

        .no-print { position: sticky; top: 0; left: 0; width: 100%; z-index: 9999; background: #222; padding: 15px; display: flex; justify-content: center; gap: 10px; }
        .btn { padding: 10px 20px; cursor: pointer; border-radius: 5px; font-weight: bold; text-decoration: none; border: none; color: white; font-size: 14px; }
        .btn-print { background: #27ae60; }
        .btn-back { background: #e74c3c; }

        @media print {
            .no-print { display: none; }
            body { background: white; }
            .report-wrapper { padding: 0; }
            .report-card { margin: 0; box-shadow: none; border: 6px double #000; width: 100%; height: 100vh; }
        }

        @media (max-width: 880px) {
            .no-print { flex-direction: column; align-items: center; }
            .btn { width: 90%; text-align: center; }
        }
    </style>
</head>
<body>

<div class="no-print">
    <button onclick="window.print()" class="btn btn-print">🖨 Print <?= count($students) ?> Reports</button>
    <a href="index.php" class="btn btn-back">⬅ Exit Bulk View</a>
</div>

<div class="report-wrapper">
<?php if(empty($students)): ?>
    <div style="text-align:center; color:white; padding: 50px;">
        <h3>No students found in this class.</h3>
    </div>
<?php endif; ?>

<?php foreach ($students as $student): 
    // Fetch individual results for this specific student
    $stmtRes = $pdo->prepare("SELECT r.*, sub.subject_name 
                              FROM results r 
                              JOIN subjects sub ON r.subject_id = sub.id 
                              WHERE r.student_id = ? AND r.session = ? AND r.term = ? AND r.is_approved = 1
                              ORDER BY sub.subject_name ASC");
    $stmtRes->execute([$student['id'], $session, $term]);
    $results = $stmtRes->fetchAll(PDO::FETCH_ASSOC);

    $grand_total = 0;
    $count = count($results);
    foreach($results as $r) { $grand_total += $r['total_score']; }
    $avg = ($count > 0) ? ($grand_total / $count) : 0;
?>

    <div class="report-card">
        <div class="header-box">
            <img src="../../assets/img/logo.png" class="logo" onerror="this.src='https://via.placeholder.com/80'">
            <div class="school-info">
                <h1><?= strtoupper(htmlspecialchars($settings['school_name'] ?? 'School Name')) ?></h1>
                <p style="font-size:12px;"><?= htmlspecialchars($settings['school_address'] ?? '') ?></p>
                <p style="font-size:11px;">Email: <?= htmlspecialchars($settings['school_email'] ?? '') ?> | Phone: <?= htmlspecialchars($settings['school_phone'] ?? '') ?></p>
                <div style="background:#2c3e50; color:white; padding:4px 15px; display:inline-block; font-weight:bold; margin-top:8px; font-size:12px;">PROGRESS REPORT SHEET</div>
            </div>
            <img src="<?= !empty($student['photo']) ? "../../uploads/students/".$student['photo'] : "https://via.placeholder.com/100" ?>" class="passport">
        </div>

        <table class="info-table">
            <tr>
                <td width="60%"><strong>NAME:</strong> <?= strtoupper(htmlspecialchars($student['fullname'])) ?></td>
                <td width="40%"><strong>REG NO:</strong> <?= htmlspecialchars($student['reg_number']) ?></td>
            </tr>
            <tr>
                <td><strong>CLASS:</strong> <?= htmlspecialchars($student['class_name']) ?></td>
                <td><strong>ACADEMIC YEAR:</strong> <?= htmlspecialchars($term) ?> | <?= htmlspecialchars($session) ?></td>
            </tr>
        </table>

        <table class="main-results">
            <thead>
                <tr>
                    <th width="35%">SUBJECT</th>
                    <th width="10%">CA (40)</th>
                    <th width="10%">EXAM (60)</th>
                    <th width="15%">TOTAL (100)</th>
                    <th width="10%">GRADE</th>
                    <th width="20%">REMARK</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($results as $res): ?>
                <tr>
                    <td style="text-align:left; padding-left:15px; font-weight:bold;"><?= htmlspecialchars($res['subject_name']) ?></td>
                    <td><?= $res['ca_score'] ?></td>
                    <td><?= $res['exam_score'] ?></td>
                    <td><strong><?= $res['total_score'] ?></strong></td>
                    <td>
                        <?php 
                        $t = $res['total_score']; 
                        if($t >= 75) echo "A"; elseif($t >= 65) echo "B"; elseif($t >= 50) echo "C"; elseif($t >= 40) echo "D"; else echo "F"; 
                        ?>
                    </td>
                    <td><small><?php if($t >= 75) echo "EXCELLENT"; elseif($t >= 65) echo "VERY GOOD"; elseif($t >= 50) echo "CREDIT"; elseif($t >= 40) echo "PASS"; else echo "FAIL"; ?></small></td>
                </tr>
                <?php endforeach; ?>
                <?php if($count == 0): ?>
                    <tr><td colspan="6">No approved results found for this student.</td></tr>
                <?php endif; ?>
                <tr style="background:#eee; font-weight:bold;">
                    <td colspan="3" style="text-align:right;">AVERAGE SCORE:</td>
                    <td colspan="3" style="text-align:left; padding-left:15px;"><?= number_format($avg, 2) ?>%</td>
                </tr>
            </tbody>
        </table>

        <div class="assessment-grid">
            <div class="mini-box">
                <h4>Skill Assessment</h4>
                Punctuality: ★★★★★ | Neatness: ★★★★☆<br>
                Honesty: ★★★★★ | Self Control: ★★★★☆
            </div>
            <div class="mini-box">
                <h4>Teacher's Remark</h4>
                <?php if($avg >= 70) echo "Exceptional student. Consistent and focused."; elseif($avg >= 50) echo "Good effort, but needs to focus more."; else echo "More effort is needed in subsequent terms."; ?>
            </div>
        </div>

        <div class="official-section">
            <h4 style="margin: 0; text-decoration: underline; font-size:13px;">PRINCIPAL'S OVERALL REMARK</h4>
            <img src="../../assets/img/stamp.png" class="stamp-img" onerror="this.style.display='none'">
            <p style="font-style:italic; margin: 12px 0; font-size: 13px;">
                <?php if($avg >= 70) echo "An outstanding result. You have a very bright future ahead."; elseif($avg >= 50) echo "A satisfactory performance. Aim higher next term."; else echo "A fair result. Please improve your study habits."; ?>
            </p>
            <div class="signature-center">
                <div class="sig-line">PRINCIPAL'S SIGNATURE / DATE</div>
                <div style="font-size:11px; margin-top:5px;"><strong>DATE:</strong> <?= !empty($settings['term_ends']) ? date('d M, Y', strtotime($settings['term_ends'])) : date('d M, Y') ?></div>
            </div>
        </div>

        <div class="term-dates-bar">
            TERM ENDED: <?= !empty($settings['term_ends']) ? date('d M, Y', strtotime($settings['term_ends'])) : 'N/A' ?> 
            &nbsp; | &nbsp; 
            NEXT TERM BEGINS: <?= !empty($settings['next_term_begins']) ? date('d M, Y', strtotime($settings['next_term_begins'])) : 'N/A' ?>
        </div>
    </div>
<?php endforeach; ?>