<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'pdo_config.php'; // $pdo connection

date_default_timezone_set('Asia/Manila');
$current_date = date('Y-m-d');
$current_time = date('H:i:s');

// Adjusted cutoff time from 18:00:00 (6:00 PM) to 18:30:00 (6:30 PM)
$cutoff_time = '18:30:00';

$date = isset($_GET['date']) ? $_GET['date'] : $current_date;
$selected_grade = isset($_GET['grade']) ? $_GET['grade'] : '';

$show_list = true;
$notice = "";
$msg = "";

// --- RESET ALL SF2 LOGS FUNCTIONALITY ---
if (isset($_POST['reset_sf2'])) {
    $pdo->query("DELETE FROM sf2");
    $msg = "<div class='notice' style='color:#1fd655;background:#e6ffe6;'>All SF2 attendance logs have been reset!</div>";
}

// Hide list before 6:30pm for today's date
if ($date == $current_date && $current_time < $cutoff_time) {
    $show_list = false;
    $notice = "<div class='notice'>List will be shown after 6:30 PM today.</div>";
}

// Hardcoded grades for dropdown
$grades = ["Nursery", "Kindergarten"];
for ($i = 1; $i <= 6; $i++) $grades[] = "Grade $i";

// Only run query if list should show
$students = [];
if ($show_list) {
    $params = [$date];

    $sql = "SELECT s.lrn, s.first_name, s.last_name, s.grade,
                   COALESCE(f.am_absent, 0) AS am_absent,
                   COALESCE(f.pm_absent, 0) AS pm_absent,
                   f.date AS attendance_date
            FROM students s
            LEFT JOIN sf2 f ON f.lrn = s.lrn AND f.date = ?";

    if (!empty($selected_grade)) {
        $sql .= " WHERE s.grade = ?";
        $params[] = $selected_grade;
    }

    $sql .= " GROUP BY s.lrn, s.first_name, s.last_name, s.grade, f.am_absent, f.pm_absent, f.date
              ORDER BY s.grade, s.last_name, s.first_name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
}

// Function to determine label-type status
function getAttendanceLabel($am_absent, $pm_absent) {
    if ($am_absent == 0 && $pm_absent == 0) {
        return 'AM Present, PM Present';
    } elseif ($am_absent == 0 && $pm_absent == 1) {
        return 'AM Present';
    } elseif ($am_absent == 1 && $pm_absent == 0) {
        return 'PM Present';
    } else {
        return 'Absent';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>SF2 Attendance Summary</title>
    <style>
        body { font-family: Arial, sans-serif; background: #222; color: #fff; margin: 0; }
        .container { max-width: 820px; margin: 48px auto; background: #333; border-radius: 18px; padding: 28px 28px 20px 28px; box-shadow: 0 6px 24px #0008; }
        h2 { text-align: center; font-size: 2em; margin-top: 0; }
        .date-select { text-align: center; margin-bottom: 18px; }
        .date-select input[type="date"], .date-select select { font-size: 1em; padding: 7px 12px; border-radius: 6px; border: none; }
        .notice { background: #ffe59e; color: #8d6708; border-radius: 7px; text-align: center; padding: 10px; margin-bottom: 18px; font-weight: bold; }
        table { width: 100%; border-collapse: collapse; background: #252525; border-radius: 10px; margin-top: 10px; }
        th, td { padding: 10px 8px; text-align: left; }
        th { background: #1679ff; color: #fff; }
        tr:nth-child(even) { background: #292929; }
        tr:nth-child(odd) { background: #222; }
        .empty { text-align: center; color: #bbb; font-size: 1.1em; margin: 25px 0 20px 0; }
        .status-present { color: #1fd655; font-weight: bold; }
        .status-absent { color: #ff2424; font-weight: bold; }
        .tick { color: #1fd655; font-size: 1.3em; font-weight: bold; }
        .cross { color: #ff2424; font-size: 1.3em; font-weight: bold; }
        a.back { display: inline-block; margin-bottom: 18px; color: #ffd93d; text-decoration: none; font-weight: bold; }
        a.back:hover { color: #fff200; }
        .reset-btn {
            background: #e74c3c;
            color: #fff;
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            font-size: 1em;
            cursor: pointer;
            margin-bottom: 18px;
            float: right;
        }
        .reset-btn:hover { background:#b92d1c;}
        @media (max-width: 670px) {
            .container { max-width: 99vw; padding: 10px 2vw 20px 2vw;}
            th, td { font-size: 1em; padding: 8px 4px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="dashboard.php" class="back">&larr; Back to Dashboard</a>
        <form method="post" style="display:inline;">
            <button type="submit" name="reset_sf2" class="reset-btn" onclick="return confirm('Are you sure you want to RESET all SF2 data? This cannot be undone.')">
                🧹 Reset All SF2 Data
            </button>
        </form>
        <h2>SF2 Attendance Summary</h2>
        <?php if ($msg) echo $msg; ?>
        <div class="date-select">
            <form method="get">
                <label for="date">Select date: </label>
                <input type="date" id="date" name="date" value="<?= htmlspecialchars($date) ?>" max="<?= $current_date ?>">
                &nbsp;
                <label for="grade">Grade: </label>
                <select id="grade" name="grade">
                    <option value="">All</option>
                    <option value="Nursery" <?= $selected_grade == "Nursery" ? 'selected' : '' ?>>Nursery</option>
                    <option value="Kindergarten" <?= $selected_grade == "Kindergarten" ? 'selected' : '' ?>>Kindergarten</option>
                    <?php for ($i = 1; $i <= 6; $i++): ?>
                        <option value="Grade <?= $i ?>" <?= $selected_grade == "Grade $i" ? 'selected' : '' ?>>Grade <?= $i ?></option>
                    <?php endfor; ?>
                </select>
                <button type="submit">View</button>
            </form>
        </div>
        <?php if ($notice) echo $notice; ?>
        <?php if ($show_list): ?>
            <table>
                <tr>
                    <th>#</th>
                    <th>LRN</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Grade</th>
                    <th>AM</th>
                    <th>PM</th>
                    <th>Status</th>
                    <th>Attendance Date</th>
                </tr>
                <?php if (count($students) == 0): ?>
                    <tr><td colspan="9" class="empty">No students found for this selection.</td></tr>
                <?php else: ?>
                    <?php
                    $seen = [];
                    foreach ($students as $i => $student):
                        // Prevent duplicate row for same lrn/date
                        $unique_key = $student['lrn'] . '_' . $student['attendance_date'];
                        if (isset($seen[$unique_key])) continue;
                        $seen[$unique_key] = true;
                        $label = getAttendanceLabel($student['am_absent'], $student['pm_absent']);
                        $status_class = ($label == 'Absent') ? 'status-absent' : 'status-present';
                    ?>
                        <tr>
                            <td><?= $i+1 ?></td>
                            <td><?= htmlspecialchars($student['lrn']) ?></td>
                            <td><?= htmlspecialchars($student['first_name']) ?></td>
                            <td><?= htmlspecialchars($student['last_name']) ?></td>
                            <td><?= htmlspecialchars($student['grade']) ?></td>
                            <td class="<?= $student['am_absent'] ? 'cross' : 'tick' ?>">
                                <?= $student['am_absent'] ? '❌' : '✅' ?>
                            </td>
                            <td class="<?= $student['pm_absent'] ? 'cross' : 'tick' ?>">
                                <?= $student['pm_absent'] ? '❌' : '✅' ?>
                            </td>
                            <td class="<?= $status_class ?>">
                                <?= $label ?>
                            </td>
                            <td>
                                <?= $student['attendance_date'] ? htmlspecialchars($student['attendance_date']) : '-' ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </table>
        <?php endif; ?>
    </div>
</body>
</html>