<?php
// 1. Core Security Check: Prevent direct access without form submission
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: index.php");
    exit();
}

// 2. Database connection configuration
$host    = 'localhost';
$db      = 'oscotech_cbt_gse';
$user    = 'oscotech_oscopt';
$pass    = 'oscopt';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// 3. Capture and Sanitize the User Inputs
$searchDepartment = filter_input(INPUT_POST, 'department', FILTER_SANITIZE_SPECIAL_CHARS);
$searchLevel      = filter_input(INPUT_POST, 'level', FILTER_SANITIZE_SPECIAL_CHARS);

// 4. Handle CSV Export Action (Triggers BEFORE any HTML prints)
if (isset($_POST['export_csv'])) {
    $sql = "SELECT id, full_name, matric_number, department, student_level, password
            FROM students 
            WHERE department = :department AND student_level = :level ORDER BY matric_number";
            
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['department' => $searchDepartment, 'level' => $searchLevel]);
    $exportData = $stmt->fetchAll();

    if ($exportData) {
        $filename = "students_" . strtolower(str_replace(' ', '_', $searchDepartment)) . "_level" . $searchLevel . "_" . date('Y-m-d') . ".csv";
        
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        fputcsv($output, ['ID', 'Full Name', 'Matric Number', 'Department', 'Level', 'Password']);
        
        foreach ($exportData as $row) {
            fputcsv($output, $row);
        }
        
        fclose($output);
        exit();
    }
}

// 5. Normal Request: Query data to display on screen
$sql = "SELECT id, full_name, matric_number, department, student_level, password 
        FROM students 
        WHERE department = :department AND student_level = :level ORDER BY matric_number";
        
$stmt = $pdo->prepare($sql);
$stmt->execute(['department' => $searchDepartment, 'level' => $searchLevel]);
$students = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Results</title>
    <style>
        /* Shared Modern Theme Variables */
        :root {
            --primary-color: #2563eb;
            --primary-hover: #1d4ed8;
            --success-color: #16a34a;
            --success-hover: #15803d;
            --print-color: #4b5563;
            --print-hover: #374151;
            --bg-color: #f8fafc;
            --card-bg: #ffffff;
            --text-color: #1e293b;
            --border-color: #e2e8f0;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background-color: var(--bg-color);
            color: var(--text-color);
            margin: 0;
            padding: 40px 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* Results Display Card */
        .results-container {
            width: 100%;
            max-width: 1000px;
            background: var(--card-bg);
            padding: 35px;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        }

        h2 {
            margin-top: 0;
            color: #0f172a;
        }

        .meta-info {
            font-size: 15px;
            color: #475569;
            margin-bottom: 25px;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 15px;
        }

        /* Action Buttons */
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            transition: background 0.2s ease-in-out;
            margin-bottom: 20px;
        }

        .btn-success {
            background-color: var(--success-color);
            color: white;
        }

        .btn-success:hover {
            background-color: var(--success-hover);
        }

        .btn-print {
            background-color: var(--print-color);
            color: white;
            margin-left: 10px;
        }

        .btn-print:hover {
            background-color: var(--print-hover);
        }

        .btn-back {
            background-color: transparent;
            color: var(--primary-color);
            border: 1px solid var(--primary-color);
            margin-top: 20px;
            margin-bottom: 0;
        }

        .btn-back:hover {
            background-color: rgba(37, 99, 235, 0.05);
        }

        /* Responsive Mobile-Friendly Table Wrapper */
        .table-responsive {
            width: 100%;
            overflow-x: auto;
            border: 1px solid var(--border-color);
            border-radius: 8px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            text-align: left;
            font-size: 14px;
            min-width: 600px;
        }

        th {
            background-color: #f1f5f9;
            color: #475569;
            font-weight: 600;
            padding: 14px 16px;
            border-bottom: 2px solid var(--border-color);
        }

        td {
            padding: 14px 16px;
            border-bottom: 1px solid var(--border-color);
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover {
            background-color: #f8fafc;
        }

        code {
            background-color: #f1f5f9;
            padding: 3px 6px;
            border-radius: 4px;
            font-family: Consolas, monospace;
            font-size: 13px;
        }

        .alert-error {
            color: #b91c1c;
            background-color: #fef2f2;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #fee2e2;
            margin-bottom: 20px;
        }

        /* 🖨️ Optimization Rules for Paper/PDF Printing */
        @media print {
            body {
                background-color: #ffffff;
                padding: 0;
                margin: 0;
            }
            .results-container {
                box-shadow: none;
                padding: 0;
                max-width: 100%;
            }
            .btn, form {
                display: none !important; /* Hides print, export, and back buttons on paper */
            }
            .table-responsive {
                border: none;
                overflow: visible;
            }
            table {
                min-width: 100%;
            }
            th {
                background-color: #e2e8f0 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
    </style>
</head>
<body>

    <div class="results-container">
         <h2 align='center'>OSUN STATE COLLEGE OF TECHNOLOGY, ESA OKE.</h2>
        <h2 align='center'>Attendance Sheet</h2>
        <div class="meta-info" align='center'>
            Department:  <strong><?php echo htmlspecialchars($searchDepartment); ?></strong> | 
            Level: <strong><?php echo htmlspecialchars($searchLevel); ?></strong>
        </div>
        
        <?php if (!empty($students)): ?>
            <!-- CSV Export Request Form -->
            <form action="results.php" method="POST" style="display: inline;">
                <input type="hidden" name="department" value="<?php echo htmlspecialchars($searchDepartment); ?>">
                <input type="hidden" name="level" value="<?php echo htmlspecialchars($searchLevel); ?>">
                <button type="submit" name="export_csv" class="btn btn-success">📊 Export to CSV / Excel</button>
            </form>

            <!-- Browser Native Print Button -->
            <button onclick="window.print()" class="btn btn-print">🖨️ Print Report</button>

            <!-- Styled Data Output Table -->
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                             <th>Matric Number</th>
                            <th>Full Name</th>
                           
                         <!--   <th>Department</th>
                            <th>Level</th>  
                            <th>Password</th>-->
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($students as $student): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($student['id']); ?></td>
                                <td><?php echo htmlspecialchars($student['matric_number']); ?></td>
                                <td><strong><?php echo htmlspecialchars($student['full_name']); ?></strong></td>
                                
                             
                                
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert-error">No student records found matching this criteria.</div>
        <?php endif; ?>
        
        <br>
        <a href="index.php" class="btn btn-back">⬅️ Go Back to Search</a>
