<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

// Arquivos de dados
$patients_file = '../data/patients.json';
$offices_file = '../data/offices.json';
$users_file = '../data/users.json';

// Função para carregar usuários
function loadUsers() {
    global $users_file;
    if (!file_exists($users_file)) {
        $default_users = [
            [
                'username' => 'admin',
                'password' => password_hash('admin123', PASSWORD_DEFAULT),
                'name' => 'Administrador'
            ]
        ];
        file_put_contents($users_file, json_encode($default_users, JSON_PRETTY_PRINT));
        return $default_users;
    }
    return json_decode(file_get_contents($users_file), true) ?: [];
}

// Função de autenticação
function authenticateUser($username, $password) {
    $users = loadUsers();
    foreach ($users as $user) {
        if ($user['username'] === $username && 
            password_verify($password, $user['password'])) {
            return $user;
        }
    }
    return false;
}

// Função para verificar se usuário está logado
function isLoggedIn() {
    return isset($_SESSION['user']);
}

// Logout
if (isset($_GET['logout'])) {
    unset($_SESSION['user']);
    session_destroy();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit();
}

// Processo de login
if (isset($_POST['login'])) {
    $user = authenticateUser($_POST['username'], $_POST['password']);
    if ($user) {
        $_SESSION['user'] = $user;
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    } else {
        $login_error = "Usuário ou senha inválidos";
    }
}

// Se não estiver logado, mostrar tela de login
if (!isLoggedIn()) {
    ?>
    <!DOCTYPE html>
    <html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login - Sistema de Pacientes</title>
        <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
        <style>
    @media (min-width: 768px) {
        .mobile-view {
            display: none;
        }
        .desktop-view {
            display: block;
        }
    }
    
    @media (max-width: 767px) {
        .mobile-view {
            display: block;
        }
        .desktop-view {
            display: none;
        }
    }
</style>
    </head>
    <body class="bg-gray-100 flex items-center justify-center min-h-screen">
        <div class="w-full max-w-md px-4">
            <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
                <h2 class="text-2xl font-bold mb-6 text-center">Login do Sistema</h2>
                <?php if (isset($login_error)): ?>
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                        <?= $login_error ?>
                    </div>
                <?php endif; ?>
                <div class="mb-4">
                    <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
                        Usuário
                    </label>
                    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" 
                           id="username" name="username" type="text" placeholder="Usuário" required>
                </div>
                <div class="mb-6">
                    <label class="block text-gray-700 text-sm font-bold mb-2" for="password">
                        Senha
                    </label>
                    <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline" 
                           id="password" name="password" type="password" placeholder="Senha" required>
                </div>
                <div class="flex items-center justify-center">
                    <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" 
                            type="submit" name="login">
                        Entrar
                    </button>
                </div>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit();
}

// Funções de gerenciamento de dados
function savePatients($patients) {
    global $patients_file;
    file_put_contents($patients_file, json_encode($patients, JSON_PRETTY_PRINT));
}

function loadPatients() {
    global $patients_file;
    if (!file_exists($patients_file)) {
        return [];
    }
    return json_decode(file_get_contents($patients_file), true) ?: [];
}

function loadOffices() {
    global $offices_file;
    if (!file_exists($offices_file)) {
        return [];
    }
    $offices = json_decode(file_get_contents($offices_file), true) ?: [];
    
    // Ordena os consultórios por nome em ordem alfabética
    usort($offices, function($a, $b) {
        return strcmp($a['name'], $b['name']);
    });
    
    return $offices;
}

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);
}

// Processar ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $patients = loadPatients();
    
    if (isset($_POST['call_patient_id'])) {
        $patients = array_map(function($patient) {
            if ($patient['id'] === $_POST['call_patient_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);
        savePatients($patients);
        
        // Redireciona para evitar reprocessamento
        header("Location: " . $_SERVER['PHP_SELF'] . "?" . http_build_query($_GET));
        exit();
    }
}

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

// Filtro de consultório
$selected_office = $_GET['office'] ?? 'all';

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

function getOfficeName($officeId, $offices) {
    foreach ($offices as $office) {
        if ($office['id'] === $officeId) {
            return $office['name'];
        }
    }
    return 'Consultório não encontrado';
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistema de Pacientes</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">

    <style>
    @media (min-width: 768px) {
        .mobile-view {
            display: none !important;
        }
        .desktop-view {
            display: block !important;
        }
    }
    
    @media (max-width: 767px) {
        .mobile-view {
            display: block !important;
        }
        .desktop-view {
            display: none !important;
        }
    }
</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-3xl font-bold">Chamada de Pacientes</h1>
            <div class="space-x-4">
                <span class="font-semibold">
                    Dr(a). <?= htmlspecialchars($_SESSION['user']['name']) ?> 
                    -  <?= 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>

            <!-- Filtro de Consultório -->
            <div class="mt-4">
                <form method="get" class="flex space-x-2">
                    <select name="office" class="flex-grow rounded py-3 px-4 text-lg border">
                        <option value="all">Todos os Consultórios</option>
                        <?php foreach ($offices as $office): ?>
                            <option value="<?= $office['id'] ?>" 
                                <?= $selected_office === $office['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($office['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-3 px-6 rounded text-lg">
                        Filtrar
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="container mx-auto px-4 py-4 mt-4">
    <!-- Fila de Espera -->
    <div class="desktop-view">
        <div class="bg-white shadow rounded-lg p-4 mb-6">
            <h2 class="text-xl font-bold mb-4">Fila de Espera</h2>
            <table class="w-full table-auto border-collapse">
                <thead>
                    <tr class="bg-gray-200">
                        <th class="border px-4 py-2 text-left">Nome</th>
                        <th class="border px-4 py-2 text-left">Consultório</th>
                        <th class="border px-4 py-2 text-left">Chegada</th>
                        <th class="border px-4 py-2 text-center">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($waiting_patients)): ?>
                        <tr>
                            <td colspan="4" class="text-center py-4 text-gray-500">
                                Nenhum paciente na fila
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($waiting_patients as $patient): ?>
                            <tr class="border-b">
                                <td class="border px-4 py-2"><?= htmlspecialchars($patient['name']) ?></td>
                                <td class="border px-4 py-2">
                                    <?= htmlspecialchars(getOfficeName($patient['office_id'], $offices)) ?>
                                </td>
                                <td class="border px-4 py-2"><?= $patient['arrival_time'] ?></td>
                                <td class="border px-4 py-2 text-center">
                                    <form method="post" class="inline" data-call-button>
                                        <input type="hidden" name="call_patient_id" value="<?= $patient['id'] ?>">
                                        <button type="submit" class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded">
                                            Chamar
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="mobile-view">
        <div class="bg-white shadow rounded-lg p-4 mb-6">
            <h2 class="text-xl font-bold mb-4">Fila de Espera</h2>
            <div class="space-y-4">
                <?php if (empty($waiting_patients)): ?>
                    <div class="text-center py-4 text-gray-500">
                        Nenhum paciente na fila
                    </div>
                <?php else: ?>
                    <?php foreach ($waiting_patients as $patient): ?>
                        <div class="bg-gray-100 rounded-lg p-4 grid grid-cols-2 gap-2">
                            <div>
                                <strong>Nome:</strong> 
                                <?= htmlspecialchars($patient['name']) ?>
                            </div>
                            <div>
                                <strong>Consultório:</strong> 
                                <?= htmlspecialchars(getOfficeName($patient['office_id'], $offices)) ?>
                            </div>
                            <div>
                                <strong>Chegada:</strong> 
                                <?= $patient['arrival_time'] ?>
                            </div>
                            <div>
                                <form method="post" data-call-button>
                                    <input type="hidden" name="call_patient_id" value="<?= $patient['id'] ?>">
                                    <button type="submit" class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded w-full">
                                        Chamar
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Pacientes Chamados - Desktop -->
    <div class="desktop-view">
        <div class="bg-white shadow rounded-lg p-4">
            <h2 class="text-xl font-bold mb-4">Chamados</h2>
            <table class="w-full table-auto border-collapse">
                <thead>
                    <tr class="bg-gray-200">
                        <th class="border px-4 py-2 text-left">Nome</th>
                        <th class="border px-4 py-2 text-left">Consultório</th>
                        <th class="border px-4 py-2 text-left">Chamada</th>
                        <th class="border px-4 py-2 text-center">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($called_patients)): ?>
                        <tr>
                            <td colspan="4" class="text-center py-4 text-gray-500">
                                Nenhum paciente chamado
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($called_patients as $patient): ?>
                            <tr class="border-b">
                                <td class="border px-4 py-2"><?= htmlspecialchars($patient['name']) ?></td>
                                <td class="border px-4 py-2">
                                    <?= htmlspecialchars(getOfficeName($patient['office_id'], $offices)) ?>
                                </td>
                                <td class="border px-4 py-2"><?= $patient['called_time'] ?></td>
                                <td class="border px-4 py-2 text-center">
                                    <form method="post" class="inline" data-call-button>
                                        <input type="hidden" name="call_patient_id" value="<?= $patient['id'] ?>">
                                        <button type="submit" class="bg-yellow-500 hover:bg-yellow-600 text-black font-bold py-2 px-4 rounded">
                                            Chamar Novamente
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Pacientes Chamados - Mobile -->
    <div class="mobile-view">
        <div class="bg-white shadow rounded-lg p-4">
            <h2 class="text-xl font-bold mb-4">Chamados</h2>
            <div class="space-y-4">
                <?php if (empty($called_patients)): ?>
                    <div class="text-center py-4 text-gray-500">
                        Nenhum paciente chamado
                    </div>
                <?php else: ?>
                    <?php foreach ($called_patients as $patient): ?>
                        <div class="bg-gray-100 rounded-lg p-4 grid grid-cols-2 gap-2">
                            <div>
                                <strong>Nome:</strong> 
                                <?= htmlspecialchars($patient['name']) ?>
                            </div>
                            <div>
                                <strong>Consultório:</strong> 
                                <?= htmlspecialchars(getOfficeName($patient['office_id'], $offices)) ?>
                            </div>
                            <div>
                                <strong>Chamada:</strong> 
                                <?= $patient['called_time'] ?>
                            </div>
                            <div>
                                <form method="post" data-call-button>
                                    <input type="hidden" name="call_patient_id" value="<?= $patient['id'] ?>">
                                    <button type="submit" class="bg-yellow-500 hover:bg-yellow-600 text-black font-bold py-2 px-4 rounded w-full">
                                        Chamar Novamente
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
    <script>
        // Função para atualizar a página automaticamente
        function autoRefresh() {
            setTimeout(function() {
                // Verifica se não houve interação recente com o botão de chamar
                if (!sessionStorage.getItem('preventAutoRefresh')) {
                    window.location.reload();
                }
            }, 30000); // Atualiza a cada 30 segundos
        }
        
        // Inicia o auto refresh
        autoRefresh();

        // Adiciona evento de clique nos botões de chamada
        document.addEventListener('DOMContentLoaded', function() {
            var callButtons = document.querySelectorAll('form[data-call-button]');
            
            callButtons.forEach(function(form) {
                form.addEventListener('submit', function(e) {
                    // Define um flag para prevenir atualização automática
                    sessionStorage.setItem('preventAutoRefresh', 'true');
                });
            });
        });

        // Mantém a posição do scroll após o refresh
        document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = sessionStorage.getItem('scrollpos');
            if (scrollpos) {
                window.scrollTo(0, scrollpos);
                sessionStorage.removeItem('scrollpos');
            }
            
            // Remove o flag de prevenção após um tempo para permitir futuras atualizações
            setTimeout(function() {
                sessionStorage.removeItem('preventAutoRefresh');
            }, 5000);
        });

        window.onbeforeunload = function(e) {
            sessionStorage.setItem('scrollpos', window.scrollY);
        };
    </script>
</body>
</html>