<?php
// attendance/attendance_report_print.php
declare(strict_types=1);

require_once __DIR__ . '/../library/auth.php';

$school_id = (int) $_SESSION['school_id'];
$current_session_id = (int) get_current_session_id($pdo);
allow_roles(['admin', 'teacher']);

$date = trim($_GET['date'] ?? date('Y-m-d'));

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    die('Invalid date format');
}

$class_id = (int)($_GET['class_id'] ?? 0);

// Fetch All Classes for names
$stmt = $pdo->prepare("
    SELECT id, class_name, section
    FROM classes
    WHERE school_id = ?
    ORDER BY class_name, section
");
$stmt->execute([$school_id]);
$classes = $stmt->fetchAll(PDO::FETCH_ASSOC);

$students = [];
$attendance = [];
$current_class_name = 'Unknown';

if ($class_id > 0) {
    // Find current class name
    foreach ($classes as $c) {
        if ((int)$c['id'] === $class_id) {
            $current_class_name = $c['class_name'] . ($c['section'] ? ' - ' . $c['section'] : '');
            break;
        }
    }

    // Corrected: Fetch active students from student_sessions to match report.php
    $stmt = $pdo->prepare("
        SELECT ss.id AS student_session_id, ss.roll_no, s.name 
        FROM student_sessions ss
        INNER JOIN students s ON s.id = ss.student_id
        WHERE ss.class_id = ? AND ss.school_id = ? AND ss.session_id = ? AND ss.status = 'Active'
        ORDER BY CAST(ss.roll_no AS UNSIGNED) ASC, s.name ASC
    ");
    $stmt->execute([$class_id, $school_id, $current_session_id]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Corrected: Fetch using student_session_id instead of student_id
    $stmt = $pdo->prepare("
        SELECT student_session_id, status
        FROM attendance
        WHERE school_id = ? AND session_id = ? AND attendance_date = ?
    ");
    $stmt->execute([$school_id, $current_session_id, $date]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as $row) {
        $attendance[$row['student_session_id']] = $row['status'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Attendance Report - <?= htmlspecialchars($date) ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <style>
        body { font-size: 14px; padding: 20px; }
        .table { border-collapse: collapse; width: 100%; }
        .table td, .table th { border: 1px solid #ddd; padding: 8px; text-align: center; }
        .bg-success { background-color: #28a745 !important; color: #fff !important; }
        .bg-warning { background-color: #ffc107 !important; color: #000 !important; }
        .bg-info { background-color: #17a2b8 !important; color: #fff !important; }
        .bg-danger { background-color: #dc3545 !important; color: #fff !important; }
        @media print {
            .no-print { display: none; }
            body { padding: 0; }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-3">
            <div>
                <h3>Attendance Report</h3>
                <h5>Class: <?= htmlspecialchars($current_class_name) ?> | Date: <?= htmlspecialchars($date) ?></h5>
            </div>
            <button onclick="window.print()" class="btn btn-primary no-print"><i class="fas fa-print"></i> Print Report</button>
        </div>

        <?php if ($class_id > 0 && count($students) > 0): ?>
            <div class="table-responsive">
                <table class="table table-bordered table-sm">
                    <thead class="bg-light">
                        <tr>
                            <th width="100">Roll No</th>
                            <th class="text-left">Student Name</th>
                            <th width="150">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($students as $s): ?>
                            <tr>
                                <td><?= htmlspecialchars($s['roll_no'] ?? '-') ?></td>
                                <td class="text-left"><strong><?= htmlspecialchars($s['name']) ?></strong></td>
                                <?php
                                $status = $attendance[$s['student_session_id']] ?? 'Absent';
                                switch ($status) {
                                    case 'Present':
                                        echo '<td class="bg-success text-white">Present</td>';
                                        break;
                                    case 'Late':
                                        echo '<td class="bg-warning text-dark">Late</td>';
                                        break;
                                    case 'Leave':
                                        echo '<td class="bg-info text-white">Leave</td>';
                                        break;
                                    case 'Absent':
                                    default:
                                        echo '<td class="bg-danger text-white">Absent</td>';
                                        break;
                                }
                                ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-warning">No active students found or no class selected.</div>
        <?php endif; ?>
    </div>
    <script>
        window.onload = function() { 
            // Optional: Auto-trigger print on load if required
            // window.print(); 
        }
    </script>
</body>
</html>