<?php
// Set default timezone to Africa Central Time (CAT, UTC+2) for Harare, Zimbabwe
date_default_timezone_set('Africa/Harare');

require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is admin
adminOnly();

$user = getUserContext();
$db = getDB();

$page_title = 'Calendar Events';
require_once 'includes/admin_header.php';
?>

<!-- FullCalendar CDN -->
<link href='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.css' rel='stylesheet' />
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.js'></script>

<!-- Calendar JavaScript -->
<script>
    let calendar;
    let selectedDate = null;
    let isModalOpen = false;
    let newEventTitle = '';
    let newEventDesc = '';
    let newEventTime = '09:00';

    document.addEventListener('DOMContentLoaded', function() {
        var calendarEl = document.getElementById('calendar');

        calendar = new FullCalendar.Calendar(calendarEl, {
            initialView: 'dayGridMonth',
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay'
            },
            timeZone: 'Africa/Harare',
            events: function(fetchInfo, successCallback, failureCallback) {
                fetch('../api/calendar.php', { credentials: 'same-origin' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const events = data.events.map(event => ({
                                id: event.id,
                                title: event.title,
                                start: event.event_date + 'T' + event.event_time + '+02:00',
                                description: event.description,
                                extendedProps: {
                                    creator: event.creator_name || 'Admin',
                                    time: event.event_time
                                }
                            }));
                            successCallback(events);
                            renderEventsList(events);
                        } else {
                            failureCallback(data.error);
                        }
                    })
                    .catch(failureCallback);
            },
            dateClick: function(info) {
                selectedDate = info.dateStr;
                isModalOpen = true;
                renderModal();
            },
            eventClick: function(info) {
                if (confirm('Delete this event?')) {
                    handleDeleteEvent(info.event.id);
                }
            },
            eventDidMount: function(info) {
                // Add custom styling or tooltips if needed
            }
        });

        calendar.render();
    });

    const handleAddEvent = async (e) => {
        e.preventDefault();

        const title = document.getElementById('modal-title-input').value;
        const description = document.getElementById('modal-desc-input').value;
        const date = document.getElementById('modal-date-input').value;
        const time = document.getElementById('modal-time-input').value;

        if (!title || !date) return;

        try {
            const response = await fetch('../api/calendar.php', {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    title: title,
                    description: description,
                    event_date: date,
                    event_time: time
                })
            });

            let data;
            try {
                data = await response.json();
            } catch (err) {
                console.error('Invalid JSON response when adding event:', err);
                alert('Error adding event: unexpected server response');
                return;
            }

            if (response.ok && data.success) {
                calendar.refetchEvents();
                closeModal();
            } else {
                alert('Failed to add event: ' + (data.error || response.statusText || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error adding event:', error);
            alert('Error adding event');
        }
    };

    const handleDeleteEvent = async (id) => {
        try {
            const response = await fetch(`../api/calendar.php?id=${id}`, { method: 'DELETE', credentials: 'same-origin' });
            let data;
            try {
                data = await response.json();
            } catch (err) {
                console.error('Invalid JSON response when deleting event:', err);
                alert('Error deleting event: unexpected server response');
                return;
            }

            if (response.ok && data.success) {
                calendar.refetchEvents();
            } else {
                alert('Failed to delete event: ' + (data.error || response.statusText || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error deleting event:', error);
            alert('Error deleting event');
        }
    };

    const closeModal = () => {
        isModalOpen = false;
        newEventTitle = '';
        newEventDesc = '';
        newEventTime = '09:00';
        renderModal();
    };

    function renderEventsList(events) {
        const eventsListEl = document.getElementById('events-list');
        const eventsCountEl = document.getElementById('events-count');

        const sortedEvents = events.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());

        eventsCountEl.textContent = events.length;

        let html = '';

        if (sortedEvents.length === 0) {
            html = `
                <div class="text-center py-8 text-slate-400">
                    <svg class="w-10 h-10 mx-auto mb-2 opacity-20" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                    <p>No events scheduled.</p>
                </div>
            `;
        } else {
            html = sortedEvents.map(event => `
                <div class="group flex gap-4 p-3 rounded-xl hover:bg-slate-50 border border-transparent hover:border-slate-100 transition-all relative">
                    <div class="flex-shrink-0 w-14 h-14 bg-indigo-50 rounded-lg flex flex-col items-center justify-center border border-indigo-100">
                        <span class="text-xs text-indigo-600 font-bold uppercase">
                            ${new Date(event.start).toLocaleString('default', { month: 'short' })}
                        </span>
                        <span class="text-xl font-bold text-slate-800">
                            ${new Date(event.start).getDate()}
                        </span>
                    </div>
                    <div class="flex-grow min-w-0">
                        <h4 class="font-semibold text-slate-800 truncate">${event.title}</h4>
                        <p class="text-xs text-slate-500 mb-2 truncate">${event.description}</p>
                        <div class="flex items-center gap-3 text-xs text-slate-400">
                            <span class="flex items-center gap-1">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                ${event.extendedProps.time}
                            </span>
                            <span class="flex items-center gap-1">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
                                ${event.extendedProps.creator}
                            </span>
                        </div>
                    </div>
                    <button onclick="handleDeleteEvent('${event.id}')" class="absolute top-3 right-3 text-slate-300 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                    </button>
                </div>
            `).join('');
        }

        eventsListEl.innerHTML = html;
    }

    function renderModal() {
        const modalContainer = document.getElementById('modal-container');

        if (!isModalOpen) {
            modalContainer.innerHTML = '';
            return;
        }

        const html = `
            <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
                <div class="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in duration-200">
                    <div class="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50">
                        <h3 class="text-lg font-bold text-slate-800">
                            ${selectedDate ? `Add Event for ${selectedDate}` : 'Add New Event'}
                        </h3>
                        <button onclick="closeModal()" class="text-slate-400 hover:text-slate-600">
                            <svg class="w-6 h-6 rotate-45" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                        </button>
                    </div>
                    <form id="event-form" class="p-6 space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-1">Event Title</label>
                            <input
                                type="text"
                                id="modal-title-input"
                                required
                                placeholder="e.g. Client Meeting"
                                class="w-full px-4 py-2 rounded-lg border border-slate-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all"
                            />
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-1">Date</label>
                                <input
                                    type="date"
                                    id="modal-date-input"
                                    required
                                    class="w-full px-4 py-2 rounded-lg border border-slate-300 focus:ring-2 focus:ring-indigo-500 outline-none"
                                />
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-1">Time</label>
                                <input
                                    type="time"
                                    id="modal-time-input"
                                    required
                                    class="w-full px-4 py-2 rounded-lg border border-slate-300 focus:ring-2 focus:ring-indigo-500 outline-none"
                                />
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-1">Description</label>
                            <textarea
                                id="modal-desc-input"
                                rows="3"
                                placeholder="Details about the event..."
                                class="w-full px-4 py-2 rounded-lg border border-slate-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-all resize-none"
                            ></textarea>
                        </div>
                        <div class="pt-2 flex gap-3">
                            <button
                                type="button"
                                onclick="closeModal()"
                                class="flex-1 px-4 py-2 rounded-lg border border-slate-200 text-slate-700 hover:bg-slate-50 font-medium transition-colors"
                            >
                                Cancel
                            </button>
                            <button
                                type="submit"
                                class="flex-1 px-4 py-2 rounded-lg bg-indigo-600 text-white hover:bg-indigo-700 font-medium shadow-md shadow-indigo-200 transition-colors"
                            >
                                Save Event
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        modalContainer.innerHTML = html;

        document.getElementById('modal-title-input').value = newEventTitle;
        document.getElementById('modal-date-input').value = selectedDate || '';
        document.getElementById('modal-time-input').value = newEventTime;
        document.getElementById('modal-desc-input').value = newEventDesc;

        document.getElementById('event-form').addEventListener('submit', handleAddEvent);

        document.getElementById('modal-title-input').addEventListener('input', (e) => newEventTitle = e.target.value);
        document.getElementById('modal-date-input').addEventListener('input', (e) => selectedDate = e.target.value);
        document.getElementById('modal-time-input').addEventListener('input', (e) => newEventTime = e.target.value);
        document.getElementById('modal-desc-input').addEventListener('input', (e) => newEventDesc = e.target.value);
    }

    // Expose functions globally
    window.handleAddEvent = handleAddEvent;
    window.handleDeleteEvent = handleDeleteEvent;
    window.closeModal = closeModal;
</script>

<div class="min-h-screen bg-slate-50 p-4 md:p-8 font-sans text-slate-800">

    <!-- Header -->
    <header class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <h1 class="text-3xl font-bold text-slate-900 flex items-center gap-2">
                <svg class="w-8 h-8 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                Event Dashboard
            </h1>
            <p class="text-slate-500 mt-1">Manage your schedule and upcoming events</p>
        </div>

        <div class="flex items-center gap-2 bg-white p-1 rounded-lg shadow-sm border border-slate-200">
            <button
                onclick="isModalOpen = true; renderModal();"
                class="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-md flex items-center gap-2 transition-colors font-medium text-sm"
            >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                New Event
            </button>
        </div>
    </header>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

        <!-- Left Column: Calendar Grid -->
        <div class="lg:col-span-2 space-y-6">
            <div id="calendar">
                <!-- Calendar will be rendered here -->
            </div>
        </div>

        <!-- Right Column: Upcoming Events List -->
        <div class="lg:col-span-1 space-y-6">
            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
                <h3 class="text-lg font-bold text-slate-800 mb-4 flex items-center justify-between">
                    <span>Upcoming Events</span>
                    <span id="events-count" class="bg-slate-100 text-slate-600 text-xs px-2 py-1 rounded-full">0</span>
                </h3>

                <div class="space-y-4 max-h-[600px] overflow-y-auto pr-2" id="events-list">
                    <!-- Events will be rendered here -->
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Container -->
    <div id="modal-container"></div>
</div>


<?php require_once 'includes/admin_footer.php'; ?>