<?php
require_once '../config/config.php';

// Require admin login
requireRole('admin');

$pageTitle = 'GAD Attendance - PSAU GAD';
$db = getDB();

// Get filter parameters
$search = get('search', '');
$status = get('status', 'all');

// Build query
$query = "
    SELECT 
        a.*,
        COUNT(DISTINCT ar.registration_id) as total_registrations,
        COUNT(DISTINCT CASE WHEN ar.status = 'approved' THEN ar.registration_id END) as approved_registrations,
        COUNT(DISTINCT aa.attendance_id) as total_attendance,
        COUNT(DISTINCT CASE WHEN aa.status = 'present' THEN aa.attendance_id END) as present_count,
        COUNT(DISTINCT CASE WHEN aa.status = 'late' THEN aa.attendance_id END) as late_count
    FROM activities a
    LEFT JOIN activity_registrations ar ON a.activity_id = ar.activity_id
    LEFT JOIN activity_attendance aa ON ar.registration_id = aa.registration_id
    WHERE a.is_active = 1
";

$params = [];

if (!empty($search)) {
    $query .= " AND (a.title LIKE ? OR a.venue LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status === 'today') {
    $query .= " AND a.activity_date = CURDATE()";
} elseif ($status === 'upcoming') {
    $query .= " AND a.activity_date > CURDATE()";
} elseif ($status === 'past') {
    $query .= " AND a.activity_date < CURDATE()";
}

$query .= " GROUP BY a.activity_id ORDER BY a.activity_date DESC";

$stmt = $db->prepare($query);
$stmt->execute($params);
$activities = $stmt->fetchAll();

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <!-- Page Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900 mb-2">
                <i class="fas fa-qrcode text-admin mr-3"></i>
                GAD Attendance
            </h1>
            <p class="text-gray-600">Track and manage activity attendance</p>
        </div>

        <!-- Filters -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <!-- Search -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Search</label>
                    <input type="text" 
                           name="search" 
                           value="<?php echo htmlspecialchars($search); ?>"
                           placeholder="Search activities..."
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-admin focus:border-transparent">
                </div>

                <!-- Status Filter -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Status</label>
                    <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-admin focus:border-transparent">
                        <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All Activities</option>
                        <option value="today" <?php echo $status === 'today' ? 'selected' : ''; ?>>Today</option>
                        <option value="upcoming" <?php echo $status === 'upcoming' ? 'selected' : ''; ?>>Upcoming</option>
                        <option value="past" <?php echo $status === 'past' ? 'selected' : ''; ?>>Past</option>
                    </select>
                </div>

                <!-- Submit -->
                <div class="flex items-end">
                    <button type="submit" class="w-full bg-admin text-white px-4 py-2 rounded-lg hover:bg-admin-dark transition">
                        <i class="fas fa-filter mr-2"></i> Filter
                    </button>
                </div>
            </form>
        </div>

        <!-- Activities List -->
        <div class="grid grid-cols-1 gap-6">
            <?php if (empty($activities)): ?>
                <div class="bg-white rounded-xl shadow-lg p-16 text-center">
                    <i class="fas fa-calendar-times text-6xl text-gray-300 mb-4"></i>
                    <h3 class="text-xl font-semibold text-gray-600 mb-2">No Activities Found</h3>
                    <p class="text-gray-500">Try adjusting your filters</p>
                </div>
            <?php else: ?>
                <?php foreach ($activities as $activity): ?>
                    <?php
                    $isPast = strtotime($activity['activity_date']) < strtotime('today');
                    $isToday = date('Y-m-d') === $activity['activity_date'];
                    $attendanceRate = $activity['approved_registrations'] > 0 
                        ? round(($activity['total_attendance'] / $activity['approved_registrations']) * 100) 
                        : 0;
                    ?>
                    <div class="bg-white rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition">
                        <div class="p-6">
                            <div class="flex items-start justify-between mb-4">
                                <div class="flex-1">
                                    <div class="flex items-center mb-2">
                                        <h3 class="text-xl font-bold text-gray-900">
                                            <?php echo htmlspecialchars($activity['title']); ?>
                                        </h3>
                                        <?php if ($isToday): ?>
                                            <span class="ml-3 px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700 animate-pulse">
                                                <i class="fas fa-circle text-xs mr-1"></i> Today
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm text-gray-600">
                                        <p>
                                            <i class="fas fa-calendar mr-2 text-admin"></i>
                                            <?php echo formatDate($activity['activity_date']); ?>
                                        </p>
                                        <p>
                                            <i class="fas fa-clock mr-2 text-admin"></i>
                                            <?php echo formatTime($activity['start_time']); ?> - <?php echo formatTime($activity['end_time']); ?>
                                        </p>
                                        <p>
                                            <i class="fas fa-map-marker-alt mr-2 text-admin"></i>
                                            <?php echo htmlspecialchars($activity['venue']); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <!-- Statistics -->
                            <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mb-4">
                                <div class="bg-blue-50 rounded-lg p-3 text-center">
                                    <p class="text-2xl font-bold text-blue-600"><?php echo $activity['approved_registrations']; ?></p>
                                    <p class="text-xs text-gray-600">Registered</p>
                                </div>
                                <div class="bg-green-50 rounded-lg p-3 text-center">
                                    <p class="text-2xl font-bold text-green-600"><?php echo $activity['present_count']; ?></p>
                                    <p class="text-xs text-gray-600">Present</p>
                                </div>
                                <div class="bg-yellow-50 rounded-lg p-3 text-center">
                                    <p class="text-2xl font-bold text-yellow-600"><?php echo $activity['late_count']; ?></p>
                                    <p class="text-xs text-gray-600">Late</p>
                                </div>
                                <div class="bg-red-50 rounded-lg p-3 text-center">
                                    <p class="text-2xl font-bold text-red-600">
                                        <?php echo $activity['approved_registrations'] - $activity['total_attendance']; ?>
                                    </p>
                                    <p class="text-xs text-gray-600">Absent</p>
                                </div>
                                <div class="bg-purple-50 rounded-lg p-3 text-center">
                                    <p class="text-2xl font-bold text-purple-600"><?php echo $attendanceRate; ?>%</p>
                                    <p class="text-xs text-gray-600">Attendance</p>
                                </div>
                            </div>

                            <!-- Actions -->
                            <div class="flex items-center space-x-3">
                                <a href="attendance-details.php?id=<?php echo $activity['activity_id']; ?>" 
                                   class="flex-1 bg-admin text-white px-4 py-2 rounded-lg hover:bg-admin-dark transition text-center text-sm font-semibold">
                                    <i class="fas fa-list mr-2"></i> View Attendance List
                                </a>
                                <?php if ($isToday || !$isPast): ?>
                                    <a href="attendance-scanner.php?id=<?php echo $activity['activity_id']; ?>" 
                                       class="flex-1 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition text-center text-sm font-semibold">
                                        <i class="fas fa-qrcode mr-2"></i> Scan QR Code
                                    </a>
                                    <a href="attendance-walkin.php?activity_id=<?php echo $activity['activity_id']; ?>"
                                       class="flex-1 bg-yellow-500 text-white px-4 py-2 rounded-lg hover:bg-yellow-600 transition text-center text-sm font-semibold">
                                        <i class="fas fa-user-plus mr-2"></i> Walk-in
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

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

