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

$pageTitle = 'Activity Calendar - Secretariat - PSAU GAD';
$db = getDB();

// Get all 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
    FROM activities a
    LEFT JOIN activity_registrations ar ON a.activity_id = ar.activity_id
    WHERE a.is_active = 1
    GROUP BY a.activity_id
");
$activities = $stmt->fetchAll();

// Prepare events for FullCalendar
$events = [];
foreach ($activities as $activity) {
    // Determine color based on 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'],
            'budget' => $activity['budget']
        ]
    ];
}

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

<div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-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-secretariat mr-3"></i>
                        Activity Calendar
                    </h1>
                    <p class="text-gray-600 mt-2">Visual schedule of all GAD activities</p>
                </div>
                <div class="flex gap-3">
                    <a href="activities.php" 
                       class="bg-secretariat hover:bg-secretariat-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="activity-create.php" 
                       class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg font-semibold transition btn-animate">
                        <i class="fas fa-plus mr-2"></i>
                        New Activity
                    </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-secretariat mr-2"></i>
                Category Legend
            </h2>
            <div class="flex flex-wrap gap-4">
                <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 id="modalCategory" class="inline-block px-3 py-1 rounded-full text-sm font-semibold"></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>
                    <h3 class="text-sm font-semibold text-gray-500 uppercase mb-2">
                        <i class="fas fa-money-bill-wave mr-1"></i> Budget
                    </h3>
                    <p id="modalBudget" class="text-gray-700"></p>
                </div>
            </div>

            <!-- Modal Footer -->
            <div class="mt-6 flex gap-3">
                <a id="modalViewBtn" href="#" class="flex-1 bg-secretariat hover:bg-secretariat-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>
                <a id="modalEditBtn" href="#" class="flex-1 bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg font-semibold transition text-center">
                    <i class="fas fa-edit mr-2"></i>
                    Edit Activity
                </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,timeGridDay,listMonth'
        },
        buttonText: {
            today: 'Today',
            month: 'Month',
            week: 'Week',
            day: 'Day',
            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;
    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'}`;
    document.getElementById('modalBudget').textContent = props.budget ? `₱${parseFloat(props.budget).toLocaleString('en-US', {minimumFractionDigits: 2})}` : 'N/A';
    
    // Set button links
    document.getElementById('modalViewBtn').href = `activity-details.php?id=${event.id}`;
    document.getElementById('modalEditBtn').href = `activity-edit.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'; ?>

