<?php
require_once '../config/config.php';
requireRole('employee');

$pageTitle = 'Activity Calendar - Employee - PSAU GAD';
$db = getDB();
$userId = getCurrentUserId();

// Get all active activities for calendar
$stmt = $db->query("
    SELECT 
        a.*,
        COUNT(DISTINCT ar.registration_id) as registration_count,
        COUNT(DISTINCT CASE WHEN ar.status = 'approved' THEN ar.registration_id END) as approved_count,
        MAX(CASE WHEN ar.user_id = $userId THEN ar.status END) as my_status
    FROM activities a
    LEFT JOIN activity_registrations ar ON a.activity_id = ar.activity_id
    WHERE a.is_active = 1 AND a.activity_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
    GROUP BY a.activity_id
");
$activities = $stmt->fetchAll();

// Prepare events for FullCalendar
$events = [];
foreach ($activities as $activity) {
    // Determine color based on registration status
    if ($activity['my_status'] === 'approved') {
        $color = '#10b981'; // Green - Registered
    } elseif ($activity['my_status'] === 'pending') {
        $color = '#f59e0b'; // Yellow - Pending
    } else {
        // Color by category
        $categoryColors = [
            'Gender Sensitivity' => '#3b82f6',  // Blue
            'Women Empowerment' => '#ec4899',   // Pink
            'LGBTQ+ Rights' => '#8b5cf6',       // Purple
            'Anti-VAWC' => '#ef4444',           // Red
            'Other' => '#6b7280'                // Gray
        ];
        $color = $categoryColors[$activity['category']] ?? '#6b7280';
    }
    
    // Create event object
    $events[] = [
        'id' => $activity['activity_id'],
        'title' => $activity['title'],
        'start' => $activity['activity_date'] . 'T' . $activity['start_time'],
        'end' => $activity['activity_date'] . 'T' . $activity['end_time'],
        'backgroundColor' => $color,
        'borderColor' => $color,
        'extendedProps' => [
            'description' => $activity['description'],
            'venue' => $activity['venue'],
            'category' => $activity['category'],
            'level' => $activity['level'],
            'registrations' => $activity['approved_count'],
            'target' => $activity['target_participants'],
            'myStatus' => $activity['my_status']
        ]
    ];
}

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

<div class="min-h-screen bg-gradient-to-br from-green-50 via-white to-blue-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">
                        <i class="fas fa-calendar-alt text-employee mr-3"></i>
                        Activity Calendar
                    </h1>
                    <p class="text-gray-600 mt-2">Browse and register for upcoming GAD activities</p>
                </div>
                <div class="flex gap-3">
                    <a href="activities.php" 
                       class="bg-employee hover:bg-employee-dark text-white px-6 py-3 rounded-lg font-semibold transition btn-animate">
                        <i class="fas fa-list mr-2"></i>
                        List View
                    </a>
                    <a href="my-activities.php" 
                       class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg font-semibold transition btn-animate">
                        <i class="fas fa-user-check mr-2"></i>
                        My Activities
                    </a>
                </div>
            </div>
        </div>

        <!-- Legend -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h2 class="text-lg font-bold text-gray-900 mb-4">
                <i class="fas fa-palette text-employee mr-2"></i>
                Legend
            </h2>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="flex items-center">
                    <div class="w-4 h-4 rounded" style="background-color: #10b981;"></div>
                    <span class="ml-2 text-sm text-gray-700 font-semibold">Registered</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 rounded" style="background-color: #f59e0b;"></div>
                    <span class="ml-2 text-sm text-gray-700 font-semibold">Pending Approval</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 rounded" style="background-color: #3b82f6;"></div>
                    <span class="ml-2 text-sm text-gray-700">Gender Sensitivity</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 rounded" style="background-color: #ec4899;"></div>
                    <span class="ml-2 text-sm text-gray-700">Women Empowerment</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 rounded" style="background-color: #8b5cf6;"></div>
                    <span class="ml-2 text-sm text-gray-700">LGBTQ+ Rights</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 rounded" style="background-color: #ef4444;"></div>
                    <span class="ml-2 text-sm text-gray-700">Anti-VAWC</span>
                </div>
                <div class="flex items-center">
                    <div class="w-4 h-4 rounded" style="background-color: #6b7280;"></div>
                    <span class="ml-2 text-sm text-gray-700">Other</span>
                </div>
            </div>
        </div>

        <!-- Calendar -->
        <div class="bg-white rounded-xl shadow-lg p-6">
            <div id="calendar"></div>
        </div>

    </div>
</div>

<!-- Event Details Modal -->
<div id="eventModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div class="p-6">
            <!-- Modal Header -->
            <div class="flex items-start justify-between mb-6">
                <div class="flex-1">
                    <h2 id="modalTitle" class="text-2xl font-bold text-gray-900 mb-2"></h2>
                    <div class="flex gap-2">
                        <div id="modalCategory" class="inline-block px-3 py-1 rounded-full text-sm font-semibold"></div>
                        <div id="modalStatus" class="inline-block px-3 py-1 rounded-full text-sm font-semibold"></div>
                    </div>
                </div>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 transition">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>

            <!-- Modal Body -->
            <div class="space-y-4">
                <div>
                    <h3 class="text-sm font-semibold text-gray-500 uppercase mb-2">Description</h3>
                    <p id="modalDescription" class="text-gray-700"></p>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <h3 class="text-sm font-semibold text-gray-500 uppercase mb-2">
                            <i class="fas fa-calendar mr-1"></i> Date & Time
                        </h3>
                        <p id="modalDateTime" class="text-gray-700"></p>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-500 uppercase mb-2">
                            <i class="fas fa-map-marker-alt mr-1"></i> Venue
                        </h3>
                        <p id="modalVenue" class="text-gray-700"></p>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <h3 class="text-sm font-semibold text-gray-500 uppercase mb-2">
                            <i class="fas fa-signal mr-1"></i> Level
                        </h3>
                        <p id="modalLevel" class="text-gray-700"></p>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-500 uppercase mb-2">
                            <i class="fas fa-users mr-1"></i> Participants
                        </h3>
                        <p id="modalParticipants" class="text-gray-700"></p>
                    </div>
                </div>
            </div>

            <!-- Modal Footer -->
            <div class="mt-6 flex gap-3">
                <a id="modalViewBtn" href="#" class="flex-1 bg-employee hover:bg-employee-dark text-white px-6 py-3 rounded-lg font-semibold transition text-center">
                    <i class="fas fa-eye mr-2"></i>
                    View Details
                </a>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    
    var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,listMonth'
        },
        buttonText: {
            today: 'Today',
            month: 'Month',
            week: 'Week',
            list: 'List'
        },
        events: <?php echo json_encode($events); ?>,
        eventClick: function(info) {
            showEventDetails(info.event);
        },
        eventMouseEnter: function(info) {
            info.el.style.cursor = 'pointer';
            info.el.style.transform = 'scale(1.02)';
        },
        eventMouseLeave: function(info) {
            info.el.style.transform = 'scale(1)';
        },
        height: 'auto',
        aspectRatio: 1.8,
        eventTimeFormat: {
            hour: 'numeric',
            minute: '2-digit',
            meridiem: 'short'
        }
    });
    
    calendar.render();
});

function showEventDetails(event) {
    const props = event.extendedProps;
    
    // Set modal content
    document.getElementById('modalTitle').textContent = event.title;
    document.getElementById('modalCategory').textContent = props.category;
    document.getElementById('modalCategory').style.backgroundColor = event.backgroundColor + '20';
    document.getElementById('modalCategory').style.color = event.backgroundColor;
    
    // Set status badge
    const statusEl = document.getElementById('modalStatus');
    if (props.myStatus === 'approved') {
        statusEl.textContent = 'Registered';
        statusEl.className = 'inline-block px-3 py-1 rounded-full text-sm font-semibold bg-green-100 text-green-800';
    } else if (props.myStatus === 'pending') {
        statusEl.textContent = 'Pending Approval';
        statusEl.className = 'inline-block px-3 py-1 rounded-full text-sm font-semibold bg-yellow-100 text-yellow-800';
    } else {
        statusEl.textContent = 'Not Registered';
        statusEl.className = 'inline-block px-3 py-1 rounded-full text-sm font-semibold bg-gray-100 text-gray-800';
    }
    
    document.getElementById('modalDescription').textContent = props.description || 'No description available';
    
    // Format date and time
    const startDate = new Date(event.start);
    const endTime = event.end ? new Date(event.end) : null;
    const dateStr = startDate.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
    const startTimeStr = startDate.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
    const endTimeStr = endTime ? endTime.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' }) : '';
    document.getElementById('modalDateTime').textContent = `${dateStr}\n${startTimeStr} - ${endTimeStr}`;
    
    document.getElementById('modalVenue').textContent = props.venue || 'TBA';
    document.getElementById('modalLevel').textContent = props.level || 'N/A';
    document.getElementById('modalParticipants').textContent = `${props.registrations} / ${props.target || 'N/A'}`;
    
    // Set button link
    document.getElementById('modalViewBtn').href = `activity-details.php?id=${event.id}`;
    
    // Show modal
    document.getElementById('eventModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('eventModal').classList.add('hidden');
}

// Close modal on outside click
document.getElementById('eventModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});

// Close modal on ESC key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal();
    }
});
</script>

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

