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

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

$db = Database::getInstance()->getConnection();

// Definir período do relatório
$start_date = $_GET['start_date'] ?? date('Y-m-d');
$end_date = $_GET['end_date'] ?? date('Y-m-d');

// Buscar estatísticas
$stmt = $db->prepare("
    SELECT 
        COUNT(*) as total_patients,
        COUNT(CASE WHEN attendance_type = 'Particular' THEN 1 END) as total_particular,
        COUNT(CASE WHEN attendance_type = 'Pasmed' THEN 1 END) as total_pasmed,
        COUNT(CASE WHEN attendance_type = 'Revisao' THEN 1 END) as total_revisao,
        SEC_TO_TIME(AVG(TIME_TO_SEC(waiting_time))) as avg_waiting_time,
        SUM(CASE WHEN attendance_type = 'Particular' THEN procedure_value + paid_amount ELSE 0 END) as total_value
    FROM patients
    WHERE DATE(created_at) BETWEEN :start_date AND :end_date
    AND called = 1
");
$stmt->execute([
    ':start_date' => $start_date,
    ':end_date' => $end_date
]);
$stats = $stmt->fetch();

// Buscar atendimentos por consultório
$stmt = $db->prepare("
    SELECT 
        o.name as office_name,
        COUNT(*) as total_calls,
        SEC_TO_TIME(AVG(TIME_TO_SEC(p.waiting_time))) as avg_waiting
    FROM patients p
    JOIN offices o ON o.id = p.office_id
    WHERE DATE(p.created_at) BETWEEN :start_date AND :end_date
    AND p.called = 1
    GROUP BY p.office_id, o.name
    ORDER BY total_calls DESC
");
$stmt->execute([
    ':start_date' => $start_date,
    ':end_date' => $end_date
]);
$office_stats = $stmt->fetchAll();

// Buscar procedimentos realizados
$stmt = $db->prepare("
    SELECT 
        pr.name as procedure_name,
        COUNT(*) as total,
        SUM(p.procedure_value) as total_value
    FROM patients p
    JOIN procedures pr ON pr.id = p.procedure_id
    WHERE DATE(p.created_at) BETWEEN :start_date AND :end_date
    AND p.called = 1
    GROUP BY p.procedure_id, pr.name
    ORDER BY total DESC
");
$stmt->execute([
    ':start_date' => $start_date,
    ':end_date' => $end_date
]);
$procedure_stats = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Relatório de Atendimentos</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <div class="container mx-auto px-4 py-8">
        <div class="flex justify-between items-center mb-8">
            <h1 class="text-3xl font-bold">Relatório de Atendimentos</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>

        <!-- Filtro de Data -->
        <form class="bg-white shadow rounded-lg p-6 mb-6">
            <div class="grid md:grid-cols-3 gap-4">
                <div>
                    <label class="block mb-2">Data Inicial</label>
                    <input type="date" name="start_date" value="<?= $start_date ?>"
                           class="w-full border rounded py-2 px-3">
                </div>
                <div>
                    <label class="block mb-2">Data Final</label>
                    <input type="date" name="end_date" value="<?= $end_date ?>"
                           class="w-full border rounded py-2 px-3">
                </div>
                <div class="flex items-end">
                    <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
                        Filtrar
                    </button>
                </div>
            </div>
        </form>

        <!-- Resumo Geral -->
        <div class="grid md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold text-gray-600 mb-4">Total de Atendimentos</h3>
                <div class="space-y-2">
                    <p>Total: <span class="font-bold"><?= $stats['total_patients'] ?></span></p>
                    <p>Particular: <span class="font-bold"><?= $stats['total_particular'] ?></span></p>
                    <p>Pasmed: <span class="font-bold"><?= $stats['total_pasmed'] ?></span></p>
                    <p>Revisão: <span class="font-bold"><?= $stats['total_revisao'] ?></span></p>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold text-gray-600 mb-4">Tempo Médio de Espera</h3>
                <p class="text-3xl font-bold"><?= $stats['avg_waiting_time'] ?: '00:00:00' ?></p>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold text-gray-600 mb-4">Valor Total (Particular)</h3>
                <p class="text-3xl font-bold">R$ <?= number_format($stats['total_value'], 2, ',', '.') ?></p>
            </div>
        </div>

        <!-- Atendimentos por Consultório -->
        <div class="bg-white shadow rounded-lg p-6 mb-8">
            <h2 class="text-xl font-bold mb-4">Atendimentos por Consultório</h2>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-gray-50">
                            <th class="px-4 py-2 text-left">Consultório</th>
                            <th class="px-4 py-2 text-right">Total</th>
                            <th class="px-4 py-2 text-right">Tempo Médio</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($office_stats as $office): ?>
                            <tr class="border-t">
                                <td class="px-4 py-2"><?= htmlspecialchars($office['office_name']) ?></td>
                                <td class="px-4 py-2 text-right"><?= $office['total_calls'] ?></td>
                                <td class="px-4 py-2 text-right"><?= $office['avg_waiting'] ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Procedimentos Realizados -->
        <div class="bg-white shadow rounded-lg p-6">
            <h2 class="text-xl font-bold mb-4">Procedimentos Realizados</h2>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-gray-50">
                            <th class="px-4 py-2 text-left">Procedimento</th>
                            <th class="px-4 py-2 text-right">Quantidade</th>
                            <th class="px-4 py-2 text-right">Valor Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($procedure_stats as $proc): ?>
                            <tr class="border-t">
                                <td class="px-4 py-2"><?= htmlspecialchars($proc['procedure_name']) ?></td>
                                <td class="px-4 py-2 text-right"><?= $proc['total'] ?></td>
                                <td class="px-4 py-2 text-right">
                                    R$ <?= number_format($proc['total_value'], 2, ',', '.') ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>