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

// --- UPDATED AUTH CHECK ---
// Allow both admin and subadmin to view result summaries
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Capture context from GET
$class_id = $_GET['class_id'] ?? '';
$session  = $_GET['session'] ?? '';
$term     = $_GET['term'] ?? '';

// Query remains the same (logic is sound)
$query = "SELECT s.id as student_id, s.fullname, s.reg_number, r.session, r.term, 
          COUNT(r.id) as subjects_entered, 
          AVG(r.total_score) as average_score
          FROM students s
          JOIN results r ON s.id = r.student_id
          WHERE r.session = ? AND r.term = ? AND s.class_id = ?
          GROUP BY s.id 
          ORDER BY average_score DESC";

$stmt = $pdo->prepare($query);
$stmt->execute([$session, $term, $class_id]);
$summary = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --success: #27ae60; --warning: #f39c12; --danger: #e74c3c; }
        
        body { font-family: 'Inter', 'Segoe UI', sans-serif; margin: 0; padding: 10px; background: #f4f7f6; }

        .result-table { width: 100%; border-collapse: collapse; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
        .result-table th { background: var(--primary); color: white; padding: 15px; text-align: left; font-size: 13px; text-transform: uppercase; }
        .result-table td { padding: 15px; border-bottom: 1px solid #eee; font-size: 14px; vertical-align: middle; }
        
        /* Progress Bar Styles */
        .avg-container { display: flex; align-items: center; gap: 10px; }
        .avg-bar-bg { background: #eee; width: 60px; height: 8px; border-radius: 4px; overflow: hidden; flex-shrink: 0; }
        .avg-bar-fill { height: 100%; border-radius: 4px; transition: width 0.5s ease-in-out; }
        
        .btn-report { background: #3498db; color: white; text-decoration: none; padding: 8px 16px; border-radius: 4px; font-size: 12px; font-weight: bold; display: inline-flex; align-items: center; gap: 5px; }
        .btn-report:hover { background: #2980b9; }
        
        .empty-state { padding: 40px; text-align: center; color: #7f8c8d; }

        /* --- RESPONSIVE TABLE (STACKING MODE) --- */
        @media screen and (max-width: 768px) {
            .result-table, .result-table thead, .result-table tbody, .result-table th, .result-table td, .result-table tr { 
                display: block; 
            }
            
            /* Hide table headers on mobile */
            .result-table thead tr { 
                position: absolute; 
                top: -9999px; 
                left: -9999px; 
            }
            
            .result-table tr { 
                border: 1px solid #ddd; 
                margin-bottom: 15px; 
                border-radius: 10px;
                background: #fff;
            }
            
            .result-table td { 
                border: none;
                border-bottom: 1px solid #eee; 
                position: relative;
                padding-left: 50%; 
                text-align: right;
                min-height: 45px;
            }
            
            .result-table td:last-child { border-bottom: none; }

            /* Label data before the value */
            .result-table td:before { 
                position: absolute;
                left: 15px;
                width: 45%; 
                padding-right: 10px; 
                white-space: nowrap;
                text-align: left;
                font-weight: bold;
                color: var(--primary);
                content: attr(data-label);
            }

            .avg-container { justify-content: flex-end; }
            .btn-report { width: 100%; justify-content: center; padding: 12px; }
        }
    </style>
</head>
<body>

<table class="result-table">
    <thead>
        <tr>
            <th>Student Name</th>
            <th>Reg No</th>
            <th style="text-align: center;">Subjects</th>
            <th>Performance Average</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php if (count($summary) > 0): ?>
            <?php foreach ($summary as $row): ?>
            <?php 
                $avg = $row['average_score'];
                $color = ($avg >= 70) ? 'var(--success)' : (($avg >= 50) ? 'var(--warning)' : 'var(--danger)');
            ?>
            <tr>
                <td data-label="Student Name"><strong><?= htmlspecialchars($row['fullname']) ?></strong></td>
                <td data-label="Reg No"><code><?= htmlspecialchars($row['reg_number']) ?></code></td>
                <td data-label="Subjects" style="text-align: center;">
                    <span style="background:#f1f2f6; padding: 4px 10px; border-radius: 20px; font-weight: bold;">
                        <?= $row['subjects_entered'] ?>
                    </span>
                </td>
                <td data-label="Performance">
                    <div class="avg-container">
                        <div class="avg-bar-bg">
                            <div class="avg-bar-fill" style="width: <?= $avg ?>%; background: <?= $color ?>;"></div>
                        </div>
                        <span style="font-weight: bold; color: <?= $color ?>;">
                            <?= number_format($avg, 1) ?>%
                        </span>
                    </div>
                </td>
                <td data-label="Action">
                    <a href="../student/view_final_results.php?id=<?= $row['student_id'] ?>&session=<?= urlencode($session) ?>&term=<?= urlencode($term) ?>" 
                       class="btn-report" target="_blank">
                        <i class="fa fa-file-pdf"></i> View Report
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
        <?php else: ?>
            <tr>
                <td colspan="5" class="empty-state">
                    <i class="fa fa-info-circle fa-2x"></i><br><br>
                    No results found for this selection. Ensure scores are approved.
                </td>
            </tr>
        <?php endif; ?>
    </tbody>
</table>

</body>
</html>