<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../includes/db.php';
include '../includes/header_admin.php';

$date = $_GET['date'] ?? date('Y-m-d');
$bus_id = $_GET['bus_id'] ?? '';
$action = $_GET['action'] ?? '';
$student_search = $_GET['student_search'] ?? '';
$grade = $_GET['grade'] ?? '';

// Fetch active buses for filter
$buses = $pdo->query("SELECT * FROM buses WHERE status = 'active'")->fetchAll();

// Fetch unique grades for filter
$grades = $pdo->query("SELECT DISTINCT grade FROM students WHERE grade IS NOT NULL ORDER BY grade")->fetchAll(PDO::FETCH_COLUMN);

// Fetch attendance logs
$query = "SELECT al.*, s.name as student_name, s.grade, b.bus_number, bs.stop_name 
          FROM attendance_logs al
          JOIN students s ON al.student_id = s.id
          JOIN buses b ON al.bus_id = b.id
          LEFT JOIN bus_stops bs ON s.stop_id = bs.id
          WHERE DATE(al.log_time) = ?";
$params = [$date];

if ($bus_id) {
    $query .= " AND al.bus_id = ?";
    $params[] = $bus_id;
}

if ($action) {
    $query .= " AND al.action = ?";
    $params[] = $action;
}

if ($student_search) {
    $query .= " AND s.name LIKE ?";
    $params[] = "%$student_search%";
}

if ($grade) {
    $query .= " AND s.grade = ?";
    $params[] = $grade;
}

$query .= " ORDER BY al.log_time DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$logs = $stmt->fetchAll();
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <h2>Daily Attendance Logs</h2>
</div>

<div class="card" style="margin-bottom: 1.5rem;">
    <form method="GET" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; align-items: end;">
        <div class="form-group" style="margin-bottom: 0;">
            <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9rem;">Date</label>
            <input type="date" name="date" class="form-control" value="<?= $date ?>" onchange="this.form.submit()">
        </div>
        
        <div class="form-group" style="margin-bottom: 0;">
            <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9rem;">Bus</label>
            <select name="bus_id" class="form-control" onchange="this.form.submit()">
                <option value="">-- All Buses --</option>
                <?php foreach ($buses as $bus): ?>
                    <option value="<?= $bus['id'] ?>" <?= $bus_id == $bus['id'] ? 'selected' : '' ?>>
                        <?= $bus['bus_number'] ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="form-group" style="margin-bottom: 0;">
            <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9rem;">Action</label>
            <select name="action" class="form-control" onchange="this.form.submit()">
                <option value="">-- All Actions --</option>
                <option value="pickup" <?= $action == 'pickup' ? 'selected' : '' ?>>Pickup</option>
                <option value="drop" <?= $action == 'drop' ? 'selected' : '' ?>>Drop</option>
            </select>
        </div>
        
        <div class="form-group" style="margin-bottom: 0;">
            <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9rem;">Grade</label>
            <select name="grade" class="form-control" onchange="this.form.submit()">
                <option value="">-- All Grades --</option>
                <?php foreach ($grades as $g): ?>
                    <option value="<?= $g ?>" <?= $grade == $g ? 'selected' : '' ?>><?= $g ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="form-group" style="margin-bottom: 0;">
            <label style="display: block; margin-bottom: 0.5rem; font-weight: 500; font-size: 0.9rem;">Student Name</label>
            <input type="text" name="student_search" class="form-control" value="<?= htmlspecialchars($student_search) ?>" placeholder="Search by name...">
        </div>
        
        <div style="display: flex; gap: 0.5rem;">
            <button type="submit" class="btn btn-primary" style="flex: 1;">
                <i class="fas fa-search"></i> Filter
            </button>
            <a href="attendance.php" class="btn" style="flex: 1; text-align: center; text-decoration: none; display: inline-flex; align-items: center; justify-content: center;">
                <i class="fas fa-times"></i> Clear
            </a>
        </div>
    </form>
</div>

<?php if (!empty($logs)): ?>
<div class="card" style="margin-bottom: 1.5rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
    <div style="display: flex; justify-content: space-around; align-items: center;">
        <div style="text-align: center;">
            <div style="font-size: 2rem; font-weight: bold;"><?= count($logs) ?></div>
            <div style="font-size: 0.9rem; opacity: 0.9;">Total Records</div>
        </div>
        <div style="text-align: center;">
            <div style="font-size: 2rem; font-weight: bold;"><?= count(array_filter($logs, fn($l) => $l['action'] == 'pickup')) ?></div>
            <div style="font-size: 0.9rem; opacity: 0.9;">Pickups</div>
        </div>
        <div style="text-align: center;">
            <div style="font-size: 2rem; font-weight: bold;"><?= count(array_filter($logs, fn($l) => $l['action'] == 'drop')) ?></div>
            <div style="font-size: 0.9rem; opacity: 0.9;">Drops</div>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="card">
    <table style="width: 100%; border-collapse: collapse;">
        <thead>
            <tr style="text-align: left; border-bottom: 2px solid #eee;">
                <th style="padding: 1rem;">Time</th>
                <th style="padding: 1rem;">Student</th>
                <th style="padding: 1rem;">Class</th>
                <th style="padding: 1rem;">Bus</th>
                <th style="padding: 1rem;">Stop</th>
                <th style="padding: 1rem;">Status</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($logs)): ?>
                <tr>
                    <td colspan="6" style="padding: 2rem; text-align: center; color: var(--dark-gray);">No attendance records found for this selection.</td>
                </tr>
            <?php else: ?>
                <?php foreach ($logs as $log): ?>
                <tr style="border-bottom: 1px solid #eee;">
                    <td style="padding: 1rem;"><?= date('H:i:s', strtotime($log['log_time'])) ?></td>
                    <td style="padding: 1rem;"><strong><?= htmlspecialchars($log['student_name']) ?></strong></td>
                    <td style="padding: 1rem;"><?= htmlspecialchars($log['grade']) ?></td>
                    <td style="padding: 1rem;"><?= htmlspecialchars($log['bus_number']) ?></td>
                    <td style="padding: 1rem;"><?= htmlspecialchars($log['stop_name'] ?: 'N/A') ?></td>
                    <td style="padding: 1rem;">
                        <span style="padding: 0.3rem 0.8rem; border-radius: 1rem; font-size: 0.75rem; font-weight: bold; background: <?= $log['action'] == 'pickup' ? '#e1f7f0; color: #1dbf73' : '#ffeaea; color: #f94144' ?>">
                            <?= strtoupper($log['action']) ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php include '../includes/footer_admin.php'; ?>
