<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once 'db.php';

// 1. CAPTURE ACTIVE FILTER PARAMETERS FROM THE DROP-DOWNS
$filter_dept    = isset($_GET['filter_dept']) ? trim($_GET['filter_dept']) : '';
$filter_level   = isset($_GET['filter_level']) ? trim($_GET['filter_level']) : '';
$filter_session = isset($_GET['filter_session']) ? trim($_GET['filter_session']) : '';
$filter_program = isset($_GET['filter_program']) ? trim($_GET['filter_program']) : '';
$filter_course  = isset($_GET['filter_course']) ? trim($_GET['filter_course']) : '';

// 2. DYNAMICALLY BUILD THE SQL QUERY BASED ON SELECTIONS
$sql = "SELECT * FROM results WHERE 1=1 "; 
$params = [];

if (!empty($filter_dept)) { $sql .= " AND UPPER(department) = UPPER(?)"; $params[] = $filter_dept; }
if (!empty($filter_level)) { $sql .= " AND UPPER(level) = UPPER(?)"; $params[] = $filter_level; }
if (!empty($filter_session)) { $sql .= " AND UPPER(session) = UPPER(?)"; $params[] = $filter_session; }
if (!empty($filter_program)) { $sql .= " AND UPPER(program) = UPPER(?)"; $params[] = $filter_program; }
if (!empty($filter_course)) { $sql .= " AND UPPER(course_code) = UPPER(?)"; $params[] = $filter_course; }

$sql .= " ORDER BY matric_number ASC";

try {
    $stmt = $pdo->prepare($sql); 
    $stmt->execute($params); 
    $results = $stmt->fetchAll();
    
    // Fetch unique options directly from the results log to prevent manual code binding errors
    $distinct_depts    = $pdo->query("SELECT DISTINCT department FROM results ORDER BY department ASC")->fetchAll(PDO::FETCH_COLUMN);
    $distinct_levels   = $pdo->query("SELECT DISTINCT level FROM results ORDER BY level ASC")->fetchAll(PDO::FETCH_COLUMN);
    $distinct_sessions = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session ASC")->fetchAll(PDO::FETCH_COLUMN);
    $distinct_programs = $pdo->query("SELECT DISTINCT program FROM results ORDER BY program ASC")->fetchAll(PDO::FETCH_COLUMN);
    $distinct_courses  = $pdo->query("SELECT DISTINCT course_code FROM results ORDER BY course_code ASC")->fetchAll(PDO::FETCH_COLUMN);
} catch (\PDOException $e) { 
    $results = []; $distinct_depts = []; $distinct_levels = []; $distinct_sessions = []; $distinct_programs = []; $distinct_courses = []; 
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Score Sheets Ledger</title>
    <style>
        body { font-family: Arial, sans-serif; background: #fff; padding: 15px; color: #333; margin: 0; }
        .filter-card { background: #fdfdfd; padding: 20px; border: 1px solid #dee2e6; border-radius: 6px; margin-bottom: 25px; border-top: 4px solid #17a2b8; }
        select { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; background: #fff; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; background: white; }
        th, td { border: 1px solid #dee2e6; padding: 10px; text-align: left; font-size: 13px; } th { background: #e9ecef; }
        .btn { padding: 10px 20px; background: #17a2b8; color: white; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 14px; }
        .print-banner { display: none; text-align: center; border-bottom: 2px double #000; padding-bottom: 10px; margin-bottom: 20px; }
        
        /* Logo design parameters */
        .logo-container { text-align: center; margin-bottom: 12px; }
        .report-logo { height: 90px; width: auto; object-fit: contain; }
        .screen-logo { height: 40px; width: auto; object-fit: contain; }

        @media print {
            .no-print, .btn, form { display: none !important; }
            th, td { border: 1px solid #000 !important; padding: 8px; }
            .print-banner { display: block !important; }
            body { background: white; color: black; }
        }
    </style>
</head>
<body>

    <!-- Printable Header Section for Hardcopy Sheets -->
    <div class="print-banner">
        <div class="logo-container">
            <!-- Ensure 'logo.png' matches your actual file name and folder path -->
            <img src="images/logo.jpg" alt="OSCOTECH Logo" class="report-logo">
        </div>
        <h2>OSUN STATE COLLEGE OF TECHNOLOGY, ESA OKE</h2>
        <p><strong>GENERAL STUDIES CBT EXAMINATION</strong></p>
        <p>
            <strong>DEPARTMENT:</strong> <?php echo !empty($filter_dept) ? htmlspecialchars($filter_dept) : 'ALL'; ?> |
            <strong>COURSE CODE:</strong> <?php echo !empty($filter_course) ? htmlspecialchars($filter_course) : 'ALL'; ?> 
        </p>
        <p>
            <strong>Level:</strong> <?php echo !empty($filter_level) ? htmlspecialchars($filter_level) : 'ALL'; ?> | 
            <strong>Session:</strong> <?php echo !empty($filter_session) ? htmlspecialchars($filter_session) : 'ALL'; ?> | 
            <strong>SEMESTER:</strong> Second
        </p>
        <p><small>Printed on: <?php echo date("Y-m-d H:i:s"); ?></small></p>
    </div>

    <!-- 🔍 UPGRADED SELECTION FILTERS MATRIX -->
    <div class="filter-card no-print">
        <h4 style="margin:0 0 12px 0; color:#17a2b8; font-size:15px;">🔍 Filter Selections Log Matrix</h4>
        <form method="GET" action="">
            <div style="display:grid; grid-template-columns: 1fr 1fr 1fr 1fr 1fr 110px; gap:10px; align-items:center;">
                
                <select name="filter_course">
                    <option value="">-- All Courses --</option>
                    <?php foreach ($distinct_courses as $c) { ?>
                        <option value="<?php echo htmlspecialchars($c); ?>" <?php echo ($filter_course === $c) ? 'selected' : ''; ?>><?php echo htmlspecialchars($c); ?></option>
                    <?php } ?>
                </select>

                <select name="filter_dept">
                    <option value="">-- All Departments --</option>
                    <?php foreach ($distinct_depts as $d) { echo "<option value='".htmlspecialchars($d)."' ".($filter_dept===$d?'selected':'').">".htmlspecialchars($d)."</option>"; } ?>
                </select>

                <select name="filter_level">
                    <option value="">-- All Levels --</option>
                    <?php foreach ($distinct_levels as $l) { echo "<option value='".htmlspecialchars($l)."' ".($filter_level===$l?'selected':'').">".htmlspecialchars($l)."</option>"; } ?>
                </select>

                <select name="filter_session">
                    <option value="">-- All Sessions --</option>
                    <?php foreach ($distinct_sessions as $s) { echo "<option value='".htmlspecialchars($s)."' ".($filter_session===$s?'selected':'').">".htmlspecialchars($s)."</option>"; } ?>
                </select>

                <select name="filter_program">
                    <option value="">-- All Programs --</option>
                    <?php foreach ($distinct_programs as $p) { echo "<option value='".htmlspecialchars($p)."' ".($filter_program===$p?'selected':'').">".htmlspecialchars($p)."</option>"; } ?>
                </select>

                <button type="submit" class="btn" style="height:38px; width:110px;">Filter Table</button>
            </div>
        </form>
    </div>

    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px;" class="no-print">
        <div style="display:flex; align-items:center; gap:12px;">
            <img src="logo.png" alt="OSCOTECH" class="screen-logo">
            <h3 style="margin:0; font-size:16px; color:#444;">Examination Records Score Sheet</h3>
        </div>
        <?php if(!empty($results)) { ?>
            <button onclick="window.print();" class="btn" style="background:#28a745;">🖨️ Print Filtered Sheet</button>
        <?php } ?>
    </div>

    <?php if(empty($results)) { ?>
        <p style="color:#666; font-style:italic; margin-top:15px;">No grading record columns currently match your active search selections inside the repository logs.</p>
    <?php } else { ?>
        <table>
            <thead>
                <tr>
                <!--    <th>Matric ID</th><th>Name</th><th>Sex</th><th>Department</th><th>Level</th><th>Program</th><th>Session</th><th>Course</th><th>Total No of Questions</th><th>Score</th><th>Percentage</th><th>Status</th> -->
                 <th>SN</th><th>Matric ID</th><th>Name</th> <th>Total No of Questions</th><th>Score (60)</th><th>Percentage</th><th>Status</th>
                </tr>
            </thead>
            
            
            <tbody>
                   
                <?php 
                $sn = 1;
                
                foreach ($results as $r) { ?>
                 
                <tr>
                      <td><strong><?php echo $sn++; ?></strong></td>
                    <td><strong><?php echo htmlspecialchars($r['matric_number']); ?></strong></td>
                    <td><?php echo htmlspecialchars($r['student_name']); ?></td>
                
                    <td><?php echo htmlspecialchars($r['total_questions'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($r['score'])*2; ?></td>
                    <td><?php echo htmlspecialchars($r['percentage'] ?? '-'); ?>%</td>
                    <td><?php echo htmlspecialchars($r['status'] ?? '-'); ?></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
    <?php } ?>

</body>
</html>
