<?php
session_start();
date_default_timezone_set('Asia/Manila');
$today = date('Y-m-d');

$conn = new mysqli("localhost", "root", "", "school_checkin");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Delete handler
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM checkins WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    $stmt->execute();
    header("Location: absent.php");
    exit;
}

$grade = $_GET['grade'] ?? '';
$from = $_GET['from'] ?? '';
$to = $_GET['to'] ?? '';
$session = $_GET['session'] ?? 'All';

$check_date = (!empty($from) && !empty($to)) ? $from : $today;
$holidayCheck = $conn->query("SELECT * FROM holidays WHERE date = '$check_date'");
if ($holidayCheck && $holidayCheck->num_rows > 0) {
    $holiday = $holidayCheck->fetch_assoc();
    echo "<!DOCTYPE html><html><head><title>🇵🇭 No Classes - SDAESI</title><style>
    body { background: #121212; color: white; font-family: Arial; text-align: center; padding: 40px; }
    .flag { width: 60px; }
    .btn-back { margin-top: 20px; padding: 10px 20px; background-color: #6c757d; color: white; border: none; border-radius: 5px; text-decoration: none; }
    .btn-back:hover { background-color: #5a6268; }
    </style></head><body class='dark'>
    <img src='school_logo.png' class='flag'><br>
    <h2>SIOCON DISTRICT ADVENTIST ELEMENTARY SCHOOL INC</h2>
    <h3>🇵🇭 No classes on <strong>" . date('F d, Y', strtotime($check_date)) . "</strong><br><em>({$holiday['description']})</em></h3>
    <a href='dashboard.php' class='btn-back'>← Back to Dashboard</a>
    </body></html>";
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Absent Students - SDAESI</title>
    <style>
        body {
            font-family: Arial;
            background: #121212;
            color: #ffffff;
            padding: 30px;
            text-align: center;
        }
        .header-logo { width: 60px; }
        h1, h2 { margin: 0; }
        table {
            margin: 0 auto;
            border-collapse: collapse;
            width: 90%;
            background-color: #1e1e1e;
        }
        th, td {
            padding: 12px;
            border: 1px solid #444;
        }
        th {
            background-color: #bb2d3b;
            color: white;
        }
        .btn-back {
            display: inline-block;
            margin-bottom: 15px;
            padding: 8px 16px;
            background-color: #495057;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }
        .btn-back:hover { background-color: #343a40; }
        select, input[type="date"], button {
            padding: 6px;
            margin: 5px;
            border-radius: 4px;
            border: none;
        }
        button {
            background-color: #198754;
            color: white;
            cursor: pointer;
        }
        button:hover { background-color: #157347; }
        .delete-link {
            color: red;
            text-decoration: none;
            font-weight: bold;
        }
    </style>
</head>
<body class="dark">
    <img src="school_logo.png" class="header-logo" alt="School Logo">
    <h1>SIOCON DISTRICT ADVENTIST ELEMENTARY SCHOOL INC</h1>
    <h2>❌ Absent Students</h2>

    <a href="dashboard.php" class="btn-back">← Back to Dashboard</a>

    <form method="get">
        <label>Grade:</label>
        <select name="grade">
            <option value="">-- All Grades --</option>
            <option value="Nursery" <?= $grade == 'Nursery' ? 'selected' : '' ?>>Nursery</option>
            <option value="Kinder 1" <?= $grade == 'Kinder 1' ? 'selected' : '' ?>>Kinder 1</option>
            <option value="Kinder 2" <?= $grade == 'Kinder 2' ? 'selected' : '' ?>>Kinder 2</option>
            <?php for ($g = 1; $g <= 6; $g++) {
                $gLabel = "Grade $g";
                echo "<option value='$gLabel'" . ($grade == $gLabel ? ' selected' : '') . ">$gLabel</option>";
            } ?>
        </select>
        <label>From:</label>
        <input type="date" name="from" value="<?= $from ?>">
        <label>To:</label>
        <input type="date" name="to" value="<?= $to ?>">
        <label>Session:</label>
        <select name="session">
            <option value="All" <?= $session == 'All' ? 'selected' : '' ?>>All</option>
            <option value="AM" <?= $session == 'AM' ? 'selected' : '' ?>>AM</option>
            <option value="PM" <?= $session == 'PM' ? 'selected' : '' ?>>PM</option>
        </select>

        <button type="submit">Filter</button>
    </form>

    <h4>
        <?php 
        if (!empty($from) && !empty($to)) {
            echo "Showing absents from <strong>" . date('F d, Y', strtotime($from)) . "</strong> to <strong>" . date('F d, Y', strtotime($to)) . "</strong>";
        } else {
            echo "Showing absents for today: <strong>" . date('F d, Y') . "</strong>";
        }
        ?>
    </h4>

    <table>
        <tr>
            <th>LRN</th>
            <th>Name</th>
            <th>Grade</th>
            <th>AM OUT</th>
            <th>PM OUT</th>
            <th>Action</th>
        </tr>
        <?php
        $studentSQL = "SELECT * FROM students" . (!empty($grade) ? " WHERE grade = '$grade'" : "");
        $students = $conn->query($studentSQL);

        $whereClause = "WHERE 1";
        if (!empty($grade)) $whereClause .= " AND grade = '$grade'";
        if (!empty($from) && !empty($to)) {
            $whereClause .= " AND scan_date BETWEEN '$from' AND '$to'";
        } else {
            $whereClause .= " AND scan_date = '$today'";
        }

        $checkins = $conn->query("SELECT id, lrn, am_out, pm_out FROM checkins $whereClause");
        $logs = [];
        while ($row = $checkins->fetch_assoc()) {
            $logs[$row['lrn']] = $row;
        }

        $hasAbsent = false;
        while ($row = $students->fetch_assoc()) {
            $lrn = $row['lrn'];
            $am_out = $logs[$lrn]['am_out'] ?? '';
            $pm_out = $logs[$lrn]['pm_out'] ?? '';

            $show = false;
            if ($session == 'AM' && empty($am_out)) $show = true;
            elseif ($session == 'PM' && empty($pm_out)) $show = true;
            elseif ($session == 'All' && (empty($am_out) || empty($pm_out))) $show = true;

            if ($show) {
                $hasAbsent = true;
                $id = $logs[$lrn]['id'] ?? '';
                echo "<tr><td>$lrn</td><td>{$row['name']}</td><td>{$row['grade']}</td><td>" . ($am_out ? '✅' : '❌') . "</td><td>" . ($pm_out ? '✅' : '❌') . "</td><td><a class='delete-link' href='?delete_id=$id' onclick=\"return confirm('Delete this entry?');\">🗑️ Delete</a></td></tr>";
            }
        }

        if (!$hasAbsent) {
            echo "<tr><td colspan='6'>🎉 All students are present!</td></tr>";
        }

        $conn->close();
        ?>
    </table>
</body>
</html>
