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

// Funções de carregamento caso não estejam no functions.php
if (!function_exists('loadPatients')) {
    function loadPatients() {
        $patients_file = BASE_PATH . '/data/patients.json';
        if (!file_exists($patients_file)) {
            return [];
        }
        return json_decode(file_get_contents($patients_file), true) ?: [];
    }
}

if (!function_exists('loadOffices')) {
    function loadOffices() {
        $offices_file = BASE_PATH . '/data/offices.json';
        if (!file_exists($offices_file)) {
            return [];
        }
        return json_decode(file_get_contents($offices_file), true) ?: [];
    }
}

// Adicione esta função
if (!function_exists('getOfficeName')) {
    function getOfficeName($officeId, $offices) {
        foreach ($offices as $office) {
            if ($office['id'] === $officeId) {
                return $office['name'];
            }
        }
        return 'Consultório não encontrado';
    }
}

// Se ainda não existir, adicione também
if (!function_exists('calculateWaitingTime')) {
    function calculateWaitingTime($arrival, $called) {
        $arrival_time = strtotime($arrival);
        $called_time = strtotime($called);
        
        $diff = $called_time - $arrival_time;
        
        $hours = floor($diff / 3600);
        $minutes = floor(($diff % 3600) / 60);
        $seconds = $diff % 60;
        
        return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
    }
}

// Verificações de segurança
requireLogin();
if ($_SESSION['user']['type'] !== 'doctor') {
    header("Location: ../index.php");
    exit();
}

// Carregar pacientes
$patients = loadPatients();
$offices = loadOffices();

// Obter o ID do consultório do médico
$doctor_office_id = $_SESSION['user']['office_id'];

// Filtrar pacientes
$waiting_patients = array_filter($patients, function($patient) use ($doctor_office_id) {
    return !$patient['called'] && $patient['office_id'] === $doctor_office_id;
});

$called_patients = array_filter($patients, function($patient) use ($doctor_office_id) {
    return $patient['called'] && $patient['office_id'] === $doctor_office_id;
});

// Processar chamada de paciente
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['call_patient_id'])) {
        $patients = array_map(function($patient) use ($doctor_office_id) {
            if ($patient['id'] === $_POST['call_patient_id'] && $patient['office_id'] === $doctor_office_id) {
                if (!$patient['called']) {
                    $patient['called'] = true;
                    $patient['called_time'] = date('H:i:s');
                    $patient['waiting_time'] = calculateWaitingTime(
                        date('Y-m-d ') . $patient['arrival_time'], 
                        date('Y-m-d ') . $patient['called_time']
                    );
                } else {
                    $patient['called_time'] = date('H:i:s');
                }
                $patient['displayed'] = false;
            }
            return $patient;
        }, $patients);
        
        // Salvar pacientes atualizados
        $patients_file = BASE_PATH . '/data/patients.json';
        file_put_contents($patients_file, json_encode($patients, JSON_PRETTY_PRINT));
        
        // Recarregar pacientes
        header("Location: chamada_pacientes.php");
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Chamada de Pacientes - <?= htmlspecialchars($_SESSION['user']['name']) ?></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-6">
            <h1 class="text-3xl font-bold">Chamada de Pacientes</h1>
            <div class="space-x-4">
                <span class="font-semibold">
                    Dr(a). <?= htmlspecialchars($_SESSION['user']['name']) ?> 
                    - Consultório: <?= getOfficeName($_SESSION['user']['office_id'], $offices) ?>
                </span>
                <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white font-bold py-2 px-4 rounded">
                    Sair
                </a>
            </div>
        </div>

        <!-- Pacientes em Espera -->
        <div class="bg-white shadow rounded-lg p-6 mb-6">
            <h2 class="text-2xl font-bold mb-4">Pacientes em Espera</h2>
            <?php if (!empty($waiting_patients)): ?>
                <table class="w-full border-collapse">
                    <thead>
                        <tr class="bg-gray-200">
                            <th class="border p-2">Nome</th>
                            <th class="border p-2">Hora de Chegada</th>
                            <th class="border p-2">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($waiting_patients as $patient): ?>
                            <tr>
                                <td class="border p-2"><?= htmlspecialchars($patient['name']) ?></td>
                                <td class="border p-2"><?= $patient['arrival_time'] ?? 'Não definido' ?></td>
                                <td class="border p-2">
                                    <form method="post" class="inline">
                                        <input type="hidden" name="call_patient_id" value="<?= $patient['id'] ?>">
                                        <button type="submit" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">
                                            Chamar
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="text-gray-500">Não há pacientes em espera no momento.</p>
            <?php endif; ?>
        </div>

        <!-- Pacientes Chamados -->
        <?php if (!empty($called_patients)): ?>
            <div class="bg-white shadow rounded-lg p-6">
                <h2 class="text-2xl font-bold mb-4">Pacientes Chamados</h2>
                <table class="w-full border-collapse">
                    <thead>
                        <tr class="bg-gray-200">
                            <th class="border p-2">Nome</th>
                            <th class="border p-2">Hora de Chegada</th>
                            <th class="border p-2">Hora da Chamada</th>
                            <th class="border p-2">Tempo de Espera</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($called_patients as $patient): ?>
                            <tr>
                                <td class="border p-2"><?= htmlspecialchars($patient['name']) ?></td>
                                <td class="border p-2"><?= $patient['arrival_time'] ?? 'Não definido' ?></td>
                                <td class="border p-2"><?= $patient['called_time'] ?? 'Não definido' ?></td>
                                <td class="border p-2"><?= $patient['waiting_time'] ?? 'N/A' ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>