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

// Verificar login
if (!isLoggedIn() || $_SESSION['user']['type'] !== 'admin') {
    header("Location: ../index.php");
    exit();
}

$message = '';
$doctors = getAllDoctors();
$selectedDate = $_GET['date'] ?? date('Y-m-d');
$selectedDoctor = $_GET['doctor_id'] ?? '';

// Buscar horários disponíveis e ocupados
$timeSlots = [];
if ($selectedDoctor) {
    $timeSlots = getDoctorTimeSlots($selectedDoctor, $selectedDate);
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agendar Consulta</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <style>
        .time-slot {
            border-left-width: 4px;
            margin-bottom: 8px;
        }
        .time-slot.available {
            border-color: #F59E0B;
        }
        .time-slot.booked {
            border-color: #3B82F6;
        }
    </style>
</head>
<body class="bg-gray-100">
    <div class="container mx-auto px-4 py-8">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold">Agendar Consulta</h1>
            <a href="index.php" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded">
                Voltar
            </a>
        </div>

        <?php if ($message): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4">
                <?= $message ?>
            </div>
        <?php endif; ?>

        <!-- Filtros de Busca -->
        <div class="bg-white shadow-md rounded p-6 mb-6">
            <div class="grid grid-cols-2 gap-6">
                <div>
                    <label class="block text-gray-700 mb-2">Médico - Especialidade</label>
                    <select id="doctor_id" name="doctor_id" 
                            class="w-full p-2 border rounded">
                        <option value="">Selecione</option>
                        <?php foreach ($doctors as $doctor): ?>
                            <option value="<?= $doctor['id'] ?>" <?= $selectedDoctor == $doctor['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($doctor['name']) ?> - <?= htmlspecialchars($doctor['specialty_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-gray-700 mb-2">Data</label>
                    <input type="date" id="appointment_date" name="date" 
                           value="<?= $selectedDate ?>" min="<?= date('Y-m-d') ?>"
                           class="w-full p-2 border rounded">
                </div>
            </div>
            <div class="mt-4">
                <button id="buscar" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-6 rounded">
                    Buscar
                </button>
            </div>
        </div>

        <!-- Lista de Horários -->
        <?php if ($selectedDoctor && $selectedDate): ?>
            <div class="space-y-2">
                <?php foreach ($timeSlots as $slot): ?>
                    <div class="time-slot bg-white shadow rounded p-4 <?= $slot['status'] == 'available' ? 'available' : 'booked' ?>">
                        <div class="flex justify-between items-center">
                            <div class="font-medium">
                                <?= $slot['status'] == 'available' ? 'Vaga Disponível' : htmlspecialchars($slot['patient_name']) ?>
                            </div>
                            <div class="font-bold text-lg">
                                <?= formatTime($slot['time']) ?>
                            </div>
                        </div>
                        <div class="mt-2">
                            <?php if ($slot['status'] == 'available'): ?>
                                <button onclick="selectSlot('<?= $slot['time'] ?>')" 
                                        class="bg-yellow-500 hover:bg-yellow-600 text-white py-1 px-4 rounded">
                                    Selecionar
                                </button>
                            <?php else: ?>
                                <button onclick="viewDetails('<?= $slot['id'] ?>')"
                                        class="bg-blue-500 hover:bg-blue-600 text-white py-1 px-4 rounded">
                                    Ver Detalhes
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#buscar').click(function() {
                const doctorId = $('#doctor_id').val();
                const date = $('#appointment_date').val();
                if (!doctorId) {
                    alert('Por favor, selecione um médico');
                    return;
                }
                if (!date) {
                    alert('Por favor, selecione uma data');
                    return;
                }
                window.location.href = `agendar_consulta.php?doctor_id=${doctorId}&date=${date}`;
            });
        });

        function selectSlot(time) {
            const doctorId = $('#doctor_id').val();
            const date = $('#appointment_date').val();
            window.location.href = `criar_agendamento.php?doctor_id=${doctorId}&date=${date}&time=${time}`;
        }

        function viewDetails(id) {
            window.location.href = `ver_agendamento.php?id=${id}`;
        }
    </script>
</body>
</html> 