<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Proteção de rota
if (empty($_SESSION['user_id'])) {
    header('Location: ' . BASE_URL . '/login.php', true, 302);
    exit;
}

$nome = $_SESSION['nome'] ?? 'Usuário';
?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agenda de Compromissos - Gabinete</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.8/index.global.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #a1b9f6ff;
            --secondary-color: #a1b9f6ff;
            --accent-color: #3b82f6;
            --hover-color: #2563eb;
        }

        body {
            background: var(--primary-color);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        /* Cabeçalho com cor azul personalizada */
        .navbar-custom {
            background: linear-gradient(135deg, #070849ff, #070849ff) !important;
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .content-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            margin: 20px 0;
        }

        .navbar-brand {
            font-weight: 600;
            font-size: 1.25rem;
        }

        .btn-outline-light:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.3);
            color: white;
        }

        .content-box {
            padding: 30px;
        }

        #calendario {
            margin-top: 20px;
        }

        /* Estilos do modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: none;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .close-button {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close-button:hover {
            color: #000;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-row {
            display: flex;
            gap: 15px;
        }

        .form-row .form-group {
            flex: 1;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #333;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .btn-primary {
            background: var(--accent-color);
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            color: white;
            cursor: pointer;
            font-weight: 600;
        }

        .btn-primary:hover {
            background: var(--hover-color);
        }

        .btn-secondary {
            background: #6c757d;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            color: white;
            cursor: pointer;
            font-weight: 600;
            margin-left: 10px;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .btn-danger {
            background: #dc3545;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            color: white;
            cursor: pointer;
            font-weight: 600;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        /* Estilos do FullCalendar */
        .fc-toolbar-title {
            font-size: 1.5rem !important;
            font-weight: 600 !important;
            color: #333 !important;
        }

        .fc-button-primary {
            background: var(--accent-color) !important;
            border-color: var(--accent-color) !important;
        }

        .fc-button-primary:hover {
            background: var(--hover-color) !important;
            border-color: var(--hover-color) !important;
        }

        .fc-event {
            border-radius: 6px !important;
            border: none !important;
            padding: 2px 6px !important;
        }
    </style>
</head>

<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom">
        <div class="container-fluid">
            <span class="navbar-brand">
                <i class="bi bi-calendar-event me-2"></i>
                Agenda de Compromissos
            </span>
            <div class="d-flex align-items-center text-white">
                <span class="me-3">Olá, <?= htmlspecialchars($nome) ?></span>
                <a href="<?= BASE_URL ?>/src/views/dashboard/" class="btn btn-outline-light btn-sm">
                    <i class="bi bi-house-fill me-1"></i>Painel
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid py-4">
        <div class="content-container">
            <div class="content-box">
                <h1 class="mb-4" style="color: #2c3e50; font-weight: 600;"><i
                        class="bi bi-calendar-event me-2"></i>Agenda de Compromissos</h1>
                <p class="text-muted">Clique numa data para adicionar um novo agendamento.</p>
                <div id="calendario"></div>
            </div>
        </div>
    </div>

    <!-- Modal de Criação -->
    <div id="modal-agendamento" class="modal">
        <div class="modal-content">
            <span class="close-button">&times;</span>
            <h2>Novo Agendamento</h2>
            <form id="form-agendamento">
                <div class="form-group">
                    <label for="titulo">Título:</label>
                    <input type="text" id="titulo" name="titulo" required>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="data_inicio">Início:</label>
                        <input type="datetime-local" id="data_inicio" name="data_inicio" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="data_fim">Fim:</label>
                        <input type="datetime-local" id="data_fim" name="data_fim">
                    </div>
                </div>
                <div class="form-group">
                    <label for="categoria">Categoria:</label>
                    <select id="categoria" name="categoria" required>
                        <option value="Reunião">Reunião</option>
                        <option value="Visita">Visita</option>
                        <option value="Saúde">Saúde</option>
                        <option value="Jurídico">Jurídico</option>
                        <option value="Assistência Social">Assistência Social</option>
                        <option value="Ação Social">Ação Social</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="id_eleitor">Associar Eleitor (Opcional):</label>
                    <select id="id_eleitor" name="id_eleitor">
                        <option value="">Nenhum</option>
                        <?php foreach ($eleitores as $eleitor): ?>
                            <option value="<?= $eleitor['id'] ?>"><?= htmlspecialchars($eleitor['nome_completo']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="descricao">Descrição:</label>
                    <textarea id="descricao" name="descricao" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label class="checkbox-container">
                        <input type="checkbox" id="whatsapp_notificacao" name="whatsapp_notificacao" value="1">
                        <span class="checkmark"></span>
                        Enviar lembrete por WhatsApp
                        <small class="form-text">A notificação será enviada 2 horas antes do compromisso</small>
                    </label>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn-primary">Salvar Agendamento</button>
                    <button type="button" class="btn btn-secondary"
                        onclick="document.getElementById('modal-agendamento').style.display='none'">Cancelar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal de Edição -->
    <div id="modal-editar-agendamento" class="modal">
        <div class="modal-content">
            <span class="close-button-edit">&times;</span>
            <h2>Editar Agendamento</h2>
            <form id="form-editar-agendamento">
                <input type="hidden" id="edit-id" name="id">
                <div class="form-group">
                    <label for="edit-titulo">Título:</label>
                    <input type="text" id="edit-titulo" name="titulo" required>
                </div>
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="edit-data_inicio">Início:</label>
                        <input type="datetime-local" id="edit-data_inicio" name="data_inicio" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="edit-data_fim">Fim:</label>
                        <input type="datetime-local" id="edit-data_fim" name="data_fim">
                    </div>
                </div>
                <div class="form-group">
                    <label for="edit-categoria">Categoria:</label>
                    <select id="edit-categoria" name="categoria" required>
                        <option value="Reunião">Reunião</option>
                        <option value="Visita">Visita</option>
                        <option value="Saúde">Saúde</option>
                        <option value="Jurídico">Jurídico</option>
                        <option value="Assistência Social">Assistência Social</option>
                        <option value="Ação Social">Ação Social</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="edit-id_eleitor">Associar Eleitor (Opcional):</label>
                    <select id="edit-id_eleitor" name="id_eleitor">
                        <option value="">Nenhum</option>
                        <?php foreach ($eleitores as $eleitor): ?>
                            <option value="<?= $eleitor['id'] ?>"><?= htmlspecialchars($eleitor['nome_completo']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="edit-descricao">Descrição:</label>
                    <textarea id="edit-descricao" name="descricao" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label class="checkbox-container">
                        <input type="checkbox" id="edit-whatsapp_notificacao" name="whatsapp_notificacao" value="1">
                        <span class="checkmark"></span>
                        Enviar lembrete por WhatsApp
                        <small class="form-text">A notificação será enviada 2 horas antes do compromisso</small>
                    </label>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn-primary">Atualizar Agendamento</button>
                    <button type="button" class="btn btn-danger" id="btn-excluir">Excluir</button>
                    <button type="button" class="btn btn-secondary"
                        onclick="document.getElementById('modal-editar-agendamento').style.display='none'">Cancelar</button>
                </div>
            </form>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const calendarioEl = document.getElementById('calendario');
            const modal = document.getElementById('modal-agendamento');
            const modalEdit = document.getElementById('modal-editar-agendamento');
            const form = document.getElementById('form-agendamento');
            const formEdit = document.getElementById('form-editar-agendamento');
            const closeButton = document.querySelector('.close-button');
            const closeButtonEdit = document.querySelector('.close-button-edit');
            const btnExcluir = document.getElementById('btn-excluir');

            const calendario = new FullCalendar.Calendar(calendarioEl, {
                initialView: 'dayGridMonth',
                locale: 'pt-br',
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
                },
                buttonText: { today: 'Hoje', month: 'Mês', week: 'Semana', day: 'Dia', list: 'Lista' },
                events: '<?= BASE_URL ?>/src/controllers/AgendasController.php?action=getEventosJson',
                editable: true,
                selectable: true,
                select: function (info) {
                    form.reset();
                    const startDate = new Date(info.startStr + 'T09:00:00');
                    document.getElementById('data_inicio').value = startDate.toISOString().slice(0, 16);
                    modal.style.display = 'block';
                },
                eventClick: function (info) {
                    carregarDadosParaEdicao(info.event.id);
                }
            });
            calendario.render();

            // Eventos dos modais
            closeButton.onclick = () => modal.style.display = 'none';
            closeButtonEdit.onclick = () => modalEdit.style.display = 'none';

            window.onclick = (event) => {
                if (event.target == modal) modal.style.display = 'none';
                if (event.target == modalEdit) modalEdit.style.display = 'none';
            }

            // Submissão do formulário de criação
            form.addEventListener('submit', function (e) {
                e.preventDefault();
                const formData = new FormData(form);

                fetch('<?= BASE_URL ?>/src/controllers/AgendasController.php?action=store', {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            modal.style.display = 'none';
                            calendario.refetchEvents();
                            alert(data.message);
                        } else if (data.redirect) {
                            alert(data.message);
                            window.location.href = data.redirect;
                        } else {
                            alert('Erro: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('Erro ao salvar agendamento.');
                    });
            });

            // Carregar dados para edição
            function carregarDadosParaEdicao(eventoId) {
                fetch(`<?= BASE_URL ?>/src/controllers/AgendasController.php?action=getAgendamento&id=${eventoId}`, {
                    method: 'GET',
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            const a = data.data;
                            document.getElementById('edit-id').value = a.id;
                            document.getElementById('edit-titulo').value = a.titulo;
                            document.getElementById('edit-data_inicio').value = a.data_inicio.slice(0, 16);
                            document.getElementById('edit-data_fim').value = a.data_fim ? a.data_fim.slice(0, 16) : '';
                            document.getElementById('edit-categoria').value = a.categoria;
                            document.getElementById('edit-id_eleitor').value = a.id_eleitor || '';
                            document.getElementById('edit-descricao').value = a.descricao || '';
                            document.getElementById('edit-whatsapp_notificacao').checked = a.whatsapp_notificacao == 1;
                            modalEdit.style.display = 'block';
                        } else {
                            alert('Erro: ' + data.message);
                        }
                    })
                    .catch(() => alert('Erro ao carregar agendamento.'));
            }

            // Submissão do formulário de edição
            formEdit.addEventListener('submit', function (e) {
                e.preventDefault();
                const formData = new FormData(formEdit);

                fetch('<?= BASE_URL ?>/src/controllers/AgendasController.php?action=update', {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            modalEdit.style.display = 'none';
                            calendario.refetchEvents();
                            alert(data.message);
                        } else {
                            alert('Erro: ' + data.message);
                        }
                    })
                    .catch(() => alert('Erro ao atualizar agendamento.'));
            });

            // Exclusão de agendamento
            btnExcluir.addEventListener('click', function () {
                if (confirm('Tem certeza que deseja excluir este agendamento?')) {
                    const formData = new FormData();
                    formData.append('id', document.getElementById('edit-id').value);

                    fetch('<?= BASE_URL ?>/src/controllers/AgendasController.php?action=delete', {
                        method: 'POST',
                        body: formData,
                        headers: { 'X-Requested-With': 'XMLHttpRequest' }
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === 'success') {
                                modalEdit.style.display = 'none';
                                calendario.refetchEvents();
                                alert(data.message);
                            } else {
                                alert('Erro: ' + data.message);
                            }
                        })
                        .catch(() => alert('Erro ao excluir agendamento.'));
                }
            });

            window.carregarDadosParaEdicao = carregarDadosParaEdicao;
        });
    </script>

    <style>
        #calendario {
            max-width: 1100px;
            margin: 20px auto;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 500px;
            border-radius: 8px;
        }

        .close-button {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close-button:hover,
        .close-button:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        .form-row {
            display: flex;
            gap: 15px;
        }

        .form-group {
            margin-bottom: 15px;
            flex: 1;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-actions {
            text-align: right;
            margin-top: 15px;
        }

        /* ESTILO ADICIONADO PARA O BOTÃO */
        .btn-primary {
            background-color: #28a745;
            /* Verde */
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-primary:hover {
            background-color: #218838;
            /* Verde mais escuro */
        }

        .btn-danger {
            background-color: #dc3545;
            /* Vermelho */
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
            margin-right: 10px;
        }

        .btn-danger:hover {
            background-color: #c82333;
            /* Vermelho mais escuro */
        }

        .btn-secondary {
            background-color: #6c757d;
            /* Cinza */
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-secondary:hover {
            background-color: #5a6268;
            /* Cinza mais escuro */
        }

        .checkbox-container {
            display: block;
            position: relative;
            padding-left: 35px;
            margin-bottom: 12px;
            cursor: pointer;
            font-size: 14px;
            user-select: none;
        }

        .checkbox-container input {
            position: absolute;
            opacity: 0;
            cursor: pointer;
            height: 0;
            width: 0;
        }

        .checkmark {
            position: absolute;
            top: 0;
            left: 0;
            height: 20px;
            width: 20px;
            background-color: #eee;
            border-radius: 3px;
            border: 1px solid #ccc;
        }

        .checkbox-container:hover input~.checkmark {
            background-color: #ccc;
        }

        .checkbox-container input:checked~.checkmark {
            background-color: #28a745;
            border-color: #28a745;
        }

        .checkmark:after {
            content: "";
            position: absolute;
            display: none;
        }

        .checkbox-container input:checked~.checkmark:after {
            display: block;
        }

        .checkbox-container .checkmark:after {
            left: 6px;
            top: 2px;
            width: 6px;
            height: 12px;
            border: solid white;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
        }

        .form-text {
            display: block;
            margin-top: 5px;
            color: #6c757d;
            font-size: 12px;
        }
    </style>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>