<?php
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit;
}

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

date_default_timezone_set('Asia/Manila');
$reset_file = __DIR__ . '/last_reset.txt';
$today = date('Y-m-d');
$now_hour = date('H');

// Get the filter date if provided, otherwise use today
$filter_date = $_GET['date'] ?? '';
$check_date = $filter_date ?: $today;

// Check if the viewed date is in the past
$is_past_date = ($check_date < $today);

// --- SUSPENSION DUE TO HOLIDAY OR TYPHOON (FROM DB) ---
$suspension_dates = [];
$suspension_reasons = [];
$sql_holidays = "SELECT date, description FROM holidays";
$res_holidays = $conn->query($sql_holidays);
if ($res_holidays && $res_holidays->num_rows > 0) {
    while ($h = $res_holidays->fetch_assoc()) {
        $suspension_dates[] = $h['date'];
        $suspension_reasons[$h['date']] = $h['description'];
    }
}

// Check if the date being viewed is suspended, not just today
$suspended = in_array($check_date, $suspension_dates);
$suspension_reason = $suspended ? $suspension_reasons[$check_date] : '';
$is_weekend = in_array(date('l', strtotime($check_date)), ['Saturday', 'Sunday']);

// --- AUTO CLEAR LOGS AT 12AM ---
if ($now_hour === '00' && (!file_exists($reset_file) || trim(file_get_contents($reset_file)) !== $today)) {
    $conn->query("UPDATE checkins SET cleared = 1 WHERE DATE(scan_date) = '" . $conn->real_escape_string($today) . "'");
    file_put_contents($reset_file, $today);
    header("Location: logs.php");
    exit;
}

// Manual clear logs (mark as cleared for the filtered or current date)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_logs'])) {
    if ($suspended || $is_past_date) {
        $error_message = $suspended ? "Cannot clear logs for suspended dates." : "Cannot clear logs for past dates.";
        header("Location: logs.php?error=" . urlencode($error_message) . ($filter_date ? "&date=" . urlencode($filter_date) : ""));
        exit;
    }
    $target_date = $check_date;
    $conn->query("UPDATE checkins SET cleared = 1 WHERE DATE(scan_date) = '" . $conn->real_escape_string($target_date) . "'");
    header("Location: logs.php" . ($filter_date ? "?date=" . urlencode($filter_date) : ""));
    exit;
}

function getCategory($grade) {
    return in_array($grade, ['Nursery', 'Kindergarten']) ? 'Preschool' : 'Grade School';
}

// Deletion of record - prevent deletion for past dates
if (isset($_GET['delete_id'])) {
    if ($suspended || $is_past_date) {
        $error_message = $suspended ? "Cannot delete logs for suspended dates." : "Cannot delete logs for past dates.";
        header("Location: logs.php?error=" . urlencode($error_message) . ($filter_date ? "&date=" . urlencode($filter_date) : ""));
        exit;
    }
    $id = intval($_GET['delete_id']);
    $conn->query("DELETE FROM checkins WHERE id = $id");
    header("Location: logs.php" . ($filter_date ? "?date=" . urlencode($filter_date) : ""));
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Attendance Logs - SDAESI</title>
  <style>
    body { 
        font-family: Arial, sans-serif; 
        background: #121212; 
        color: #f1f1f1; 
        padding: 20px; 
        text-align: center; 
        background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 100 100"><g opacity="0.1"><circle cx="15" cy="15" r="10" fill="orange"/><path d="M15,5 Q20,0 25,5 T35,5 T45,5 T55,5 T65,5 T75,5 T85,5 Q90,0 95,5 Q100,10 95,15 T95,25 T95,35 T95,45 T95,55 T95,65 T95,75 T95,85 Q100,90 95,95 Q90,100 85,95 T75,95 T65,95 T55,95 T45,95 T35,95 T25,95 T15,95 Q10,100 5,95 Q0,90 5,85 T5,75 T5,65 T5,55 T5,45 T5,35 T5,25 T5,15 Q0,10 5,5 Q10,0 15,5" fill="red"/><circle cx="35" cy="15" r="8" fill="green"/><circle cx="85" cy="25" r="12" fill="orange"/><circle cx="65" cy="55" r="9" fill="red"/><circle cx="25" cy="75" r="10" fill="purple"/><circle cx="75" cy="85" r="8" fill="green"/><path d="M45,35 Q50,30 55,35 Q60,40 55,45 Q50,50 45,45 Q40,40 45,35" fill="yellow"/><path d="M65,15 Q70,10 75,15 Q80,20 75,25 Q70,30 65,25 Q60,20 65,15" fill="red"/></g></svg>');
        background-attachment: fixed;
    }
    .container {
        max-width: 1200px;
        margin: 0 auto;
        position: relative;
        z-index: 1;
    }
    .fruit-corner {
        position: absolute;
        width: 150px;
        height: 150px;
        opacity: 0.6;
        pointer-events: none;
        z-index: -1;
    }
    .fruit-top-left {
        top: 0;
        left: 0;
        background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="150" height="150" viewBox="0 0 100 100"><circle cx="30" cy="30" r="25" fill="orange"/><path d="M30,5 Q40,0 50,10 Q60,20 50,30 Q40,40 30,30 Q20,20 30,5" fill="green"/></svg>');
    }
    .fruit-top-right {
        top: 0;
        right: 0;
        background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="150" height="150" viewBox="0 0 100 100"><circle cx="40" cy="40" r="30" fill="red"/><path d="M40,10 Q45,5 50,10 L50,30 Q45,35 40,30 L40,10" fill="green"/></svg>');
    }
    .fruit-bottom-left {
        bottom: 0;
        left: 0;
        background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="150" height="150" viewBox="0 0 100 100"><path d="M20,20 Q40,10 60,20 Q80,30 60,50 Q40,70 20,50 Q0,30 20,20" fill="purple"/><path d="M40,10 L42,5 L45,10 L40,10" fill="green"/></svg>');
    }
    .fruit-bottom-right {
        bottom: 0;
        right: 0;
        background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="150" height="150" viewBox="0 0 100 100"><path d="M30,30 Q50,20 70,30 Q80,50 70,70 Q50,80 30,70 Q20,50 30,30" fill="yellow"/><path d="M50,20 L50,10 L55,5 L60,10 L60,20 L50,20" fill="green"/></svg>');
    }
    table { margin: 20px auto; border-collapse: collapse; width: 98%; background-color: rgba(30,30,30,0.9); border-radius: 10px; overflow: hidden; box-shadow: 0 4px 8px rgba(0,0,0,0.3); }
    th, td { border: 1px solid #444; padding: 10px; }
    th { background-color: #007bff; color: white; }
    .btn { padding: 8px 15px; margin: 10px 5px; border: none; border-radius: 5px; color: white; cursor: pointer; text-decoration: none; background-color: #28a745; box-shadow: 0 2px 4px rgba(0,0,0,0.2); transition: all 0.3s; }
    .btn:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.3); }
    .btn-back { background-color: #6c757d; }
    .btn-clear { background-color: #dc3545; }
    .btn-clear:hover { background-color: #a71d2a; }
    .grade-header { text-align: left; background-color: #bb2d3b; font-weight: bold; color: white; }
    .checkin { color: #0f0; font-weight: bold; }
    .late { color: orange; font-weight: bold; }
    .ontime { color: #00bfff; font-weight: bold; }
    .checkout { color: #f00; font-weight: bold; }
    .delete-link { color: red; text-decoration: none; font-weight: bold; }
    .disabled-link { color: #666; text-decoration: none; cursor: not-allowed; }
    input[type=date] { padding: 8px; border-radius: 4px; border: none; background: #333; color: white; }
    .cleared-row { background-color: #444444 !important; opacity: 0.7; }
    .cleared-status { color: gray; font-weight: bold; }
    .suspended-box {
        background: linear-gradient(135deg, #e74c3c, #c0392b);
        color: #fff;
        border-radius: 10px;
        padding: 30px;
        margin: 30px auto 20px auto;
        font-size: 1.3em;
        max-width: 650px;
        box-shadow: 0 8px 16px rgba(0,0,0,0.4);
        font-weight: bold;
        position: relative;
        overflow: hidden;
    }
    .suspended-box:before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 100 100"><g opacity="0.1"><circle cx="20" cy="20" r="15" fill="white"/><circle cx="80" cy="30" r="12" fill="white"/><circle cx="30" cy="70" r="10" fill="white"/><circle cx="80" cy="80" r="15" fill="white"/></g></svg>');
        opacity: 0.5;
    }
    .suspended-box span { font-size: 1.6em; text-shadow: 2px 2px 4px rgba(0,0,0,0.4); }
    .fruit-icon {
        display: inline-block;
        width: 24px;
        height: 24px;
        vertical-align: middle;
        margin-right: 5px;
    }
    .apple { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="60" r="40" fill="red"/><path d="M50,20 Q55,15 60,20 L60,40 Q55,45 50,40 L50,20" fill="green"/></svg>'); }
    .banana { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><path d="M20,80 Q40,60 60,50 Q80,40 90,20 Q95,35 90,50 Q85,65 70,75 Q50,85 30,85 Q20,85 20,80" fill="yellow"/></svg>'); }
    h2, h3 { text-shadow: 2px 2px 4px rgba(0,0,0,0.5); }
    .logo-container { 
        background: rgba(255,255,255,0.1); 
        border-radius: 50%; 
        padding: 15px; 
        display: inline-block; 
        box-shadow: 0 4px 8px rgba(0,0,0,0.3);
        margin-bottom: 10px;
    }
    .date-info {
        background: rgba(0,0,0,0.2);
        border-radius: 4px;
        padding: 5px 10px;
        display: inline-block;
        margin: 10px 0;
    }
    .past-date-info {
        background: rgba(255,193,7,0.2);
        border: 1px solid rgba(255,193,7,0.4);
        color: #ffc107;
        border-radius: 4px;
        padding: 8px 15px;
        display: inline-block;
        margin: 10px 0;
        font-weight: bold;
    }
    .error-message {
        background: #e74c3c;
        color: white;
        padding: 10px;
        border-radius: 5px;
        margin: 10px auto;
        max-width: 80%;
        font-weight: bold;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="fruit-corner fruit-top-left"></div>
    <div class="fruit-corner fruit-top-right"></div>
    <div class="fruit-corner fruit-bottom-left"></div>
    <div class="fruit-corner fruit-bottom-right"></div>
    
    <div class="logo-container">
      <img src="school_logo.png" alt="Logo" style="width: 100px;">
    </div>
    <h2>🍎 SIOCON DISTRICT ADVENTIST ELEMENTARY SCHOOL INC 🍎</h2>
    <h3>📋 Attendance Logs</h3>

    <a href="dashboard.php" class="btn btn-back">← Back to Dashboard</a>
    <form method="get" style="display:inline-block;">
      <label>🗕️ Filter by Date:</label>
      <input type="date" name="date" value="<?= htmlspecialchars($filter_date) ?>">
      <button type="submit" class="btn">🔍 Filter</button>
    </form>

    <?php if (isset($_GET['error'])): ?>
    <div class="error-message">
      <?= htmlspecialchars($_GET['error']) ?>
    </div>
    <?php endif; ?>

    <?php if ($filter_date): ?>
    <div class="date-info">
      Viewing: <?= htmlspecialchars(date('F j, Y (l)', strtotime($check_date))) ?>
    </div>
    <?php endif; ?>
    
    <?php if ($is_past_date): ?>
    <div class="past-date-info">
      ⚠️ Historical Records - Logs from past dates cannot be modified or deleted
    </div>
    <?php endif; ?>

    <?php if (!$suspended && !$is_past_date): ?>
    <form method="post" style="display:inline-block;">
      <button type="submit" name="reset_logs" class="btn btn-clear" onclick="return confirm('Are you sure you want to clear all logs?')">🪝 Clear Logs</button>
    </form>
    <?php endif; ?>

<?php if ($suspended): ?>
  <div class="suspended-box">
    <span>🚨 SUSPENDED 🚨</span><br>
    Classes and attendance checking are <span style="color:yellow;">SUSPENDED</span> on this date due to:<br>
    <span style="color:#ffffc0; font-size: 1.4em;"><?= htmlspecialchars($suspension_reason) ?></span><br>
    <div style="margin-top: 15px; font-size: 0.9em;">No attendance records available for suspended days.</div>
    <div style="margin-top: 10px;">
      <span class="fruit-icon apple"></span>
      <span class="fruit-icon banana"></span>
      <span class="fruit-icon apple"></span>
    </div>
  </div>
<?php elseif ($is_weekend): ?>
  <div class="suspended-box" style="background: linear-gradient(135deg, #3498db, #2980b9);">
    <span>🏖️ WEEKEND 🏖️</span><br>
    No attendance logs on weekends (Saturday & Sunday).<br>
    <div style="margin-top: 10px;">
      <span class="fruit-icon apple"></span>
      <span class="fruit-icon banana"></span>
      <span class="fruit-icon apple"></span>
    </div>
  </div>
<?php else: ?>
  <table>
    <tr>
      <th>LRN</th><th>Name</th><th>Grade</th><th>Category</th>
      <th>AM In</th><th>AM Out</th><th>PM In</th><th>PM Out</th>
      <th>Room/In-Charge</th><th>Date</th>
      <th>Status</th> 
      <th>Action</th>
    </tr>
<?php
$sql = "
    SELECT 
        c.lrn,
        MAX(c.id) as id,
        c.grade,
        c.incharge,
        DATE(c.scan_date) as scan_date,
        MIN(c.am_in) as am_in,
        MAX(c.am_out) as am_out,
        MIN(c.pm_in) as pm_in,
        MAX(c.pm_out) as pm_out,
        MAX(c.cleared) as cleared,
        s.first_name,
        s.middle_name,
        s.last_name
    FROM checkins c
    LEFT JOIN students s ON TRIM(UPPER(c.lrn)) = TRIM(UPPER(s.lrn))
    WHERE " . ($filter_date ? "DATE(c.scan_date) = '" . $conn->real_escape_string($filter_date) . "'" : "1") . "
    GROUP BY c.lrn, c.grade, c.incharge, DATE(c.scan_date), s.first_name, s.middle_name, s.last_name
    ORDER BY c.grade ASC, s.last_name ASC, s.first_name ASC, scan_date DESC
";

$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    $last_grade = '';
    while ($r = $result->fetch_assoc()) {
        $category = getCategory($r['grade']);

        $lname = !empty($r['last_name']) ? strtoupper(trim($r['last_name'])) : '';
        $fname = !empty($r['first_name']) ? strtoupper(trim($r['first_name'])) : '';
        $mname = !empty($r['middle_name']) ? strtoupper(trim($r['middle_name'])) : '';
        $full = ($lname || $fname) ? trim("$lname, $fname $mname") : htmlspecialchars($r['lrn']);

        if ($r['grade'] !== $last_grade) {
            $fruit_icon = (mt_rand(0,1) == 0) ? 'apple' : 'banana';
            echo "<tr><td colspan='12' class='grade-header'>📚 Grade: " . htmlspecialchars($r['grade']) . " <span class='fruit-icon $fruit_icon'></span></td></tr>";
            $last_grade = $r['grade'];
        }

        $status = "<span style='color:#888;'>---</span>";
        if (!empty($r['am_in']) || !empty($r['pm_in'])) {
            $late = false;

            if (!empty($r['am_in'])) {
                $am_cutoff = strtotime("08:30:00");
                $am_in_time = strtotime($r['am_in']);
                if ($am_in_time > $am_cutoff) $late = true;
            }

            if (!empty($r['pm_in'])) {
                $pm_cutoff = strtotime("13:30:00");
                $pm_in_time = strtotime($r['pm_in']);
                if ($pm_in_time > $pm_cutoff) $late = true;
            }

            $status = $late ? "<span class='late'>Late</span>" : "<span class='ontime'>On Time</span>";
        }

        $row_class = $r['cleared'] ? " class='cleared-row'" : "";
        $display_status = $r['cleared'] ? "<span class='cleared-status'>Cleared</span>" : $status;

        echo "<tr{$row_class}>";
        echo "<td>" . htmlspecialchars($r['lrn']) . "</td>";
        echo "<td>" . htmlspecialchars($full) . "</td>";
        echo "<td>" . htmlspecialchars($r['grade']) . "</td>";
        echo "<td>" . htmlspecialchars($category) . "</td>";
        echo "<td class='checkin'>" . ($r['am_in'] ? htmlspecialchars($r['am_in']) : '–') . "</td>";
        echo "<td class='checkout'>" . ($r['am_out'] ? htmlspecialchars($r['am_out']) : '–') . "</td>";
        echo "<td class='checkin'>" . ($r['pm_in'] ? htmlspecialchars($r['pm_in']) : '–') . "</td>";
        echo "<td class='checkout'>" . ($r['pm_out'] ? htmlspecialchars($r['pm_out']) : '–') . "</td>";
        echo "<td>" . ($r['incharge'] ? htmlspecialchars($r['incharge']) : '–') . "</td>";
        echo "<td>" . htmlspecialchars($r['scan_date']) . "</td>";
        echo "<td>" . $display_status . "</td>";
        
        // Only show active delete link for current/future dates
        if (!$is_past_date) {
            echo "<td><a class='delete-link' href='?delete_id=" . intval($r['id']) . ($filter_date ? "&date=" . urlencode($filter_date) : "") . "' onclick=\"return confirm('Delete this record?')\">🗑️</a></td>";
        } else {
            echo "<td><span class='disabled-link' title='Cannot delete past records'>🔒</span></td>";
        }
        
        echo "</tr>";
    }
} else {
    echo "<tr><td colspan='12'>No logs found for this date.</td></tr>";
}

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