<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Connect to database
$conn = new mysqli("localhost", "root", "", "school_checkin");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
date_default_timezone_set('Asia/Manila');

// Get selected date from GET param, default to today
$today = date('Y-m-d');
$date = isset($_GET['date']) && $_GET['date'] ? $_GET['date'] : $today;

// Clear all logs for the selected date
if (isset($_POST['clear_logs']) && isset($_POST['date']) && $_POST['date']) {
    $date_to_clear = $_POST['date'];
    $conn->query("DELETE FROM checkins WHERE scan_date = '$date_to_clear'");
    header("Location: checkedin_students.php?date=" . urlencode($date_to_clear));
    exit();
}

// Query: Show one row per student for selected date, with all check-in/out times
$sql = "
    SELECT 
        lrn,
        name,
        grade,
        MIN(CASE WHEN am_in IS NOT NULL THEN am_in END) AS am_in,
        MAX(CASE WHEN am_out IS NOT NULL THEN am_out END) AS am_out,
        MIN(CASE WHEN pm_in IS NOT NULL THEN pm_in END) AS pm_in,
        MAX(CASE WHEN pm_out IS NOT NULL THEN pm_out END) AS pm_out
    FROM checkins
    WHERE scan_date = '$date'
    GROUP BY lrn, name, grade
    ORDER BY name
";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Checked-in Students</title>
    <style>
        body {font-family: Arial, sans-serif; background: #181b1e; color: #f5f5f5; padding: 30px; text-align: center;}
        .dark-mode { background: #181b1e; color: #f5f5f5; }
        .light-mode { background: #f9f9f9; color: #333; }
        .mode-toggle { margin: 12px 8px 18px 0; padding: 7px 20px; border: none; border-radius: 6px; background: #323437; color: #f5f5f5; cursor: pointer; font-size: 1em; transition: background 0.3s; display: inline-block;}
        .mode-toggle.light { background: #e2e2e2; color: #181b1e;}
        .back-btn {display: inline-block; margin: 12px 0 18px 0; padding: 8px 30px; background: #1679ff; color: #fff; border: none; border-radius: 6px; text-decoration: none; font-weight: bold; font-size: 1em; transition: background 0.3s;}
        .back-btn:hover {background: #145c32;}
        table {margin: 0 auto; border-collapse: collapse; width: 90%; background-color: #23262b; transition: background 0.3s;}
        .light-mode table {background-color: #fff;}
        th, td {padding: 10px; border: 1px solid #444;}
        th {background-color: #198754; color: white;}
        .light-mode th {background-color: #198754; color: white;}
        tr:nth-child(even){background-color: #2e2e2e;}
        .light-mode tr:nth-child(even){background-color: #f2f2f2;}
        h2 { margin-bottom: 24px; }
        .clear-btn {margin-top: 16px; padding: 8px 30px; background: #bb2d3b; color: #fff; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; transition: background 0.3s;}
        .clear-btn:hover {background: #a31b23;}
        /* Filter box styling */
        .filter-box {margin: 20px 0; padding: 8px; width: 280px; font-size: 1em; border-radius: 6px; border: 1px solid #888;}
        .light-mode .filter-box {border: 1px solid #ccc;}
        .date-filter-form {margin: 18px 0 10px 0;}
        .date-input {padding: 7px 12px; border-radius: 6px; border: 1px solid #888; font-size: 1em;}
    </style>
</head>
<body class="dark-mode" id="mainBody">
    <button class="mode-toggle" id="modeToggleBtn" onclick="toggleMode()">🌙 Dark Mode</button>
    <a href="dashboard.php" class="back-btn">← Back to Dashboard</a>
    <h2>✅ Checked-in Students for <?= date('F d, Y', strtotime($date)) ?></h2>

    <!-- Date Filter Form -->
    <form class="date-filter-form" method="get" action="checkedin_students.php">
        <input type="date" name="date" class="date-input" value="<?= htmlspecialchars($date) ?>" max="<?= $today ?>">
        <button type="submit" class="mode-toggle">🗓️ Filter Date</button>
    </form>
    
    <form method="post" onsubmit="return confirm('Are you sure you want to clear the logs for this date?');" style="display:inline;">
        <input type="hidden" name="date" value="<?= htmlspecialchars($date) ?>">
        <button type="submit" name="clear_logs" class="clear-btn">🗑️ Clear This Date's Logs</button>
    </form>
    <!-- Filter box -->
    <input type="text" id="filterInput" class="filter-box" placeholder="🔍 Search by LRN, Name, or Grade..." onkeyup="filterTable()">
    <table id="studentsTable">
        <tr>
            <th>LRN</th>
            <th>Name</th>
            <th>Grade</th>
            <th>AM IN</th>
            <th>AM OUT</th>
            <th>PM IN</th>
            <th>PM OUT</th>
        </tr>
        <?php
        if ($result && $result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo "<tr>
                    <td>{$row['lrn']}</td>
                    <td>{$row['name']}</td>
                    <td>{$row['grade']}</td>
                    <td>" . ($row['am_in'] ?? '-') . "</td>
                    <td>" . ($row['am_out'] ?? '-') . "</td>
                    <td>" . ($row['pm_in'] ?? '-') . "</td>
                    <td>" . ($row['pm_out'] ?? '-') . "</td>
                </tr>";
            }
        } else {
            echo "<tr><td colspan='7'>Walay check-ins aning adlawa.</td></tr>";
        }
        $conn->close();
        ?>
    </table>
    <script>
        function toggleMode() {
            var body = document.getElementById('mainBody');
            var btn = document.getElementById('modeToggleBtn');
            if (body.classList.contains('dark-mode')) {
                body.classList.remove('dark-mode');
                body.classList.add('light-mode');
                btn.textContent = "☀️ Light Mode";
                btn.classList.add('light');
                localStorage.setItem('theme', 'light');
            } else {
                body.classList.remove('light-mode');
                body.classList.add('dark-mode');
                btn.textContent = "🌙 Dark Mode";
                btn.classList.remove('light');
                localStorage.setItem('theme', 'dark');
            }
        }
        (function(){
            var theme = localStorage.getItem('theme');
            if(theme === 'light') {
                document.getElementById('mainBody').classList.remove('dark-mode');
                document.getElementById('mainBody').classList.add('light-mode');
                var btn = document.getElementById('modeToggleBtn');
                btn.textContent = "☀️ Light Mode";
                btn.classList.add('light');
            }
        })();

        // Filter function
        function filterTable() {
            var input = document.getElementById("filterInput");
            var filter = input.value.toUpperCase();
            var table = document.getElementById("studentsTable");
            var tr = table.getElementsByTagName("tr");
            // Loop through all table rows, except the first (header)
            for (var i = 1; i < tr.length; i++) {
                var show = false;
                var tds = tr[i].getElementsByTagName("td");
                for (var j = 0; j < 3; j++) { // Only LRN, Name, Grade
                    if (tds[j] && tds[j].textContent.toUpperCase().indexOf(filter) > -1) {
                        show = true;
                        break;
                    }
                }
                tr[i].style.display = show ? "" : "none";
            }
        }
    </script>
</body>
</html>