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

date_default_timezone_set('America/Sao_Paulo');

// Processar requisições
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Adicionar paciente
    if (isset($_POST['patient_name'], $_POST['patient_office'], $_POST['attendance_type'])) {
        $patientData = [
            'name' => $_POST['patient_name'],
            'office_id' => $_POST['patient_office'],
            'priority' => $_POST['patient_priority'] ?? 'Padrao',
            'attendance_type' => $_POST['attendance_type'],
            'procedure' => $_POST['procedure'] ?? null,
            'procedure_value' => $_POST['procedure_value'] ?? null,
            'payment_method' => $_POST['payment_method'] ?? null,
            'paid_amount' => $_POST['paid_amount'] ?? null
        ];

        if (addPatient($patientData)) {
            header("Location: " . $_SERVER['PHP_SELF'] . "?" . http_build_query($_GET));
            exit();
        }
    }

    // Chamar paciente
    if (isset($_POST['call_patient_id'])) {
        if (callPatient($_POST['call_patient_id'])) {
            header("Location: " . $_SERVER['PHP_SELF'] . "?" . http_build_query($_GET));
            exit();
        }
    }

    // Excluir paciente
    if (isset($_POST['delete_patient_id'])) {
        if (deletePatient($_POST['delete_patient_id'])) {
            header("Location: " . $_SERVER['PHP_SELF'] . "?" . http_build_query($_GET));
            exit();
        }
    }

    // Iniciar Atendimento (limpar todas as listas)
    if (isset($_POST['start_service'])) {
        if (clearAllPatients()) {
            header("Location: " . $_SERVER['PHP_SELF']);
            exit();
        }
    }
}

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

// Carregar dados
$offices = getOffices();
$procedures = getProcedures();
$waiting_patients = getWaitingPatients($selected_office);
$called_patients = getCalledPatients($selected_office);

// Ordenar pacientes por prioridade e tempo de chegada
usort($waiting_patients, function($a, $b) {
    $priority_order = ['Alta' => 1, 'Media' => 2, 'Padrao' => 3];
    
    if ($priority_order[$a['priority']] !== $priority_order[$b['priority']]) {
        return $priority_order[$a['priority']] - $priority_order[$b['priority']];
    }
    
    return strtotime($a['arrival_time']) - strtotime($b['arrival_time']);
});

// Ordenar pacientes chamados do mais recente para o mais antigo
usort($called_patients, function($a, $b) {
    return strtotime($b['called_time']) - strtotime($a['called_time']);
});

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>Administração - Chamada de Pacientes</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">Painel de Chamada de Pacientes</h1>
            <div class="flex items-center space-x-4">
                <span class="text-gray-700">Bem-vindo, <?= $_SESSION['user']['name'] ?></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>

<div class="grid md:grid-cols-2 gap-4 mb-6">
    <!-- Filtro de Consultório -->
    <form method="get" class="flex space-x-2">
        <select name="office" class="flex-grow border rounded py-2 px-3">
            <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-2 px-4 rounded">
            Filtrar
        </button>
    </form>
</div>

<!-- Adicionar Paciente -->
<form method="post" class="grid md:grid-cols-3 gap-4 mb-6">
    <input type="text" name="patient_name" placeholder="Nome do Paciente" 
           class="border rounded py-2 px-3" required>
    
    <select name="attendance_type" id="attendance_type" class="border rounded py-2 px-3" required onchange="togglePaymentFields()">
        <option value="">Selecione o Tipo de Atendimento</option>
        <option value="Particular">Particular</option>
        <option value="Pasmed">Pasmed</option>
        <option value="Revisao">Revisão</option>
    </select>
    
    <div id="payment_fields" style="display: none;">
        <select name="payment_method" class="border rounded py-2 px-3">
            <option value="">Forma de Pagamento</option>
            <option value="Dinheiro">Dinheiro</option>
            <option value="Pix">Pix</option>
            <option value="Credito_Vista">Crédito à Vista</option>
            <option value="Credito_Parcelado">Crédito Parcelado</option>
            <option value="Debito">Débito</option>
        </select>
        <input type="text" name="paid_amount" placeholder="Valor Pago" 
               class="border rounded py-2 px-3 payment-input" 
               data-mask="currency">
    </div>
    
    <select name="procedure" id="procedure" class="border rounded py-2 px-3" onchange="toggleProcedureValue()">
        <option value="">Selecione o Procedimento (Opcional)</option>
        <?php foreach ($procedures as $procedure): ?>
            <option value="<?= $procedure['id'] ?>"><?= htmlspecialchars($procedure['name']) ?></option>
        <?php endforeach; ?>
    </select>
    
    <input type="text" name="procedure_value" id="procedure_value" 
           placeholder="Valor do Procedimento" 
           class="border rounded py-2 px-3 procedure-input" 
           data-mask="currency"
           style="display: none;">
    
    <select name="patient_office" class="border rounded py-2 px-3" required>
        <option value="">Selecione o Consultório</option>
        <?php foreach ($offices as $office): ?>
            <option value="<?= $office['id'] ?>"><?= htmlspecialchars($office['name']) ?></option>
        <?php endforeach; ?>
    </select>
    
    <select name="patient_priority" class="border rounded py-2 px-3" required>
        <option value="Padrao">Prioridade Padrão</option>
        <option value="Media">Prioridade Média</option>
        <option value="Alta">Prioridade Alta</option>
    </select>
    
    <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
        Adicionar Paciente
    </button>
</form>

<script>
function togglePaymentFields() {
    var attendanceType = document.getElementById('attendance_type');
    var paymentFields = document.getElementById('payment_fields');
    if (attendanceType.value === 'Particular') {
        paymentFields.style.display = 'block';
    } else {
        paymentFields.style.display = 'none';
    }
}

function toggleProcedureValue() {
    var procedure = document.getElementById('procedure');
    var procedureValue = document.getElementById('procedure_value');
    if (procedure.value) {
        procedureValue.style.display = 'block';
    } else {
        procedureValue.style.display = 'none';
    }
}

// Função para formatar campos numéricos como moeda
function setupCurrencyMask() {
    const currencyInputs = document.querySelectorAll('[data-mask="currency"]');
    currencyInputs.forEach(input => {
        input.addEventListener('input', function(e) {
            // Remove todos os caracteres que não são números
            let value = this.value.replace(/\D/g, '');
            
            // Converte para número decimal
            value = (value / 100).toFixed(2);
            
            // Formata com pontuação
            this.value = new Intl.NumberFormat('pt-BR', {
                style: 'currency',
                currency: 'BRL'
            }).format(value);
        });
    });
}

// Inicializa máscaras de moeda
setupCurrencyMask();
</script>

        <!-- Botões de Ação -->
        <div class="mb-6 flex space-x-4">
            <form method="post" id="start-service-form" class="inline">
                <input type="hidden" name="start_service" value="1">
                <button type="submit" class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded">
                    Iniciar Atendimento
                </button>
            </form>
            
            <form method="post" id="generate-report-form" class="inline">
                <input type="hidden" name="generate_report" value="1">
                <button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
                    Fechamento do Dia
                </button>
            </form>
        </div>

<!-- Pacientes na Fila de Espera -->
<div id="waiting-patients" class="bg-white shadow rounded-lg p-6 mb-6">
    <h2 class="text-2xl font-bold mb-4">Pacientes na Fila de Espera</h2>
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead>
                <tr class="bg-gray-200">
                    <th class="py-2 px-4 text-left">Nome</th>
                    <th class="py-2 px-4 text-left">Consultório</th>
                    <th class="py-2 px-4 text-left">Tipo de Atendimento</th>
                    <th class="py-2 px-4 text-left">Chegada</th>
                    <th class="py-2 px-4 text-left">Prioridade</th>
                    <th class="py-2 px-4 text-left">Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($waiting_patients as $patient): ?>
                    <tr class="border-b">
                        <td class="py-2 px-4"><?= htmlspecialchars($patient['name']) ?></td>
                        <td class="py-2 px-4">
                            <?= htmlspecialchars(getOfficeName($patient['office_id'], $offices)) ?>
                        </td>
                        <td class="py-2 px-4"><?= htmlspecialchars($patient['attendance_type']) ?></td>
                        <td class="py-2 px-4"><?= $patient['arrival_time'] ?></td>
                        <td class="py-2 px-4">
                            <?php 
                            $priority_classes = [
                                'Alta' => 'text-red-600 font-bold',
                                'Media' => 'text-yellow-600',
                                'Padrao' => 'text-green-600'
                            ];
                            ?>
                            <span class="<?= $priority_classes[$patient['priority']] ?>">
                                <?= $patient['priority'] ?>
                            </span>
                        </td>
                        <td class="py-2 px-4">
                            <div class="flex space-x-2">
                                <form method="post" class="inline">
                                    <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-1 px-3 rounded">
                                        Chamar
                                    </button>
                                </form>
                                <button onclick='showFinancialDetails(<?= json_encode($patient) ?>)' 
                                        class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-1 px-3 rounded">
                                    Financeiro
                                </button>
                                <form method="post" class="inline" onsubmit="return confirmDelete();">
                                    <input type="hidden" name="delete_patient_id" value="<?= $patient['id'] ?>">
                                    <button type="submit" class="bg-red-500 hover:bg-red-600 text-white font-bold py-1 px-3 rounded">
                                        Excluir
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($waiting_patients)): ?>
                    <tr>
                        <td colspan="6" class="text-center py-4 text-gray-500">
                            Nenhum paciente na fila de espera
                            <?= $selected_office !== 'all' ? ' para este consultório' : '' ?>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<!-- Pacientes Chamados -->
<div id="called-patients" class="bg-white shadow rounded-lg p-6">
    <h2 class="text-2xl font-bold mb-4">Pacientes Chamados</h2>
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead>
                <tr class="bg-gray-200">
                    <th class="py-2 px-4 text-left">Nome</th>
                    <th class="py-2 px-4 text-left">Consultório</th>
                    <th class="py-2 px-4 text-left">Tipo de Atendimento</th>
                    <th class="py-2 px-4 text-left">Chegada</th>
                    <th class="py-2 px-4 text-left">Chamada</th>
                    <th class="py-2 px-4 text-left">Tempo de Espera</th>
                    <th class="py-2 px-4 text-left">Prioridade</th>
                    <th class="py-2 px-4 text-left">Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($called_patients as $patient): ?>
                    <tr class="border-b">
                        <td class="py-2 px-4"><?= htmlspecialchars($patient['name']) ?></td>
                        <td class="py-2 px-4">
                            <?= htmlspecialchars(getOfficeName($patient['office_id'], $offices)) ?>
                        </td>
                        <td class="py-2 px-4"><?= htmlspecialchars($patient['attendance_type']) ?></td>
                        <td class="py-2 px-4"><?= $patient['arrival_time'] ?></td>
                        <td class="py-2 px-4"><?= $patient['called_time'] ?></td>
                        <td class="py-2 px-4"><?= $patient['waiting_time'] ?? 'N/A' ?></td>
                        <td class="py-2 px-4">
                            <?php 
                            $priority_classes = [
                                'Alta' => 'text-red-600 font-bold',
                                'Media' => 'text-yellow-600',
                                'Padrao' => 'text-green-600'
                            ];
                            ?>
                            <span class="<?= $priority_classes[$patient['priority']] ?>">
                                <?= $patient['priority'] ?>
                            </span>
                        </td>
                        <td class="py-2 px-4">
                            <div class="flex space-x-2">
                                <form method="post" class="inline">
                                    <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-1 px-3 rounded">
                                        Chamar Novamente
                                    </button>
                                </form>
                                <button onclick='showFinancialDetails(<?= json_encode($patient) ?>)' 
                                        class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-1 px-3 rounded">
                                    Financeiro
                                </button>
                                <form method="post" class="inline" onsubmit="return confirmDelete();">
                                    <input type="hidden" name="delete_patient_id" value="<?= $patient['id'] ?>">
                                    <button type="submit" class="bg-red-500 hover:bg-red-600 text-white font-bold py-1 px-3 rounded">
                                        Excluir
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($called_patients)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4 text-gray-500">
                            Nenhum paciente chamado
                            <?= $selected_office !== 'all' ? ' para este consultório' : '' ?>
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Financeiro -->
<div id="financial-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center">
    <div class="bg-white p-8 rounded-lg max-w-2xl w-full relative">
        <button id="close-financial-modal" class="absolute top-4 right-4 text-2xl font-bold">&times;</button>
        <h2 class="text-2xl font-bold mb-6">Detalhes Financeiros</h2>
        
        <div id="financial-details" class="space-y-4">
            <!-- Conteúdo do modal será preenchido dinamicamente via JavaScript -->
        </div>
    </div>
</div>

<script>
function showFinancialDetails(patientData) {
    const modal = document.getElementById('financial-modal');
    const detailsContainer = document.getElementById('financial-details');
    
    const formatCurrency = (value) => {
        if (value === null || value === undefined || value === '') {
            return 'N/A';
        }
        
        return new Intl.NumberFormat('pt-BR', { 
            style: 'currency', 
            currency: 'BRL' 
        }).format(value);
    };
    
    // Limpar conteúdo anterior
    detailsContainer.innerHTML = '';
    
    // Criar elementos de detalhes
    const createDetailRow = (label, value) => {
        const row = document.createElement('div');
        row.className = 'flex justify-between border-b pb-2';
        row.innerHTML = `
            <span class="font-medium">${label}:</span>
            <span>${value}</span>
        `;
        return row;
    };
    
    // Calcular total
    const procedureValue = patientData.procedure_value || 0;
    const paidAmount = patientData.paid_amount || 0;
    const totalValue = procedureValue + paidAmount;
    
    // Adicionar detalhes na ordem especificada
    detailsContainer.appendChild(createDetailRow('Nome', patientData.name));
    detailsContainer.appendChild(createDetailRow('Tipo de Atendimento', patientData.attendance_type));
    
    // Detalhes de pagamento
    if (patientData.attendance_type === 'Particular') {
        detailsContainer.appendChild(createDetailRow('Forma de Pagamento', patientData.payment_method || 'N/A'));
        detailsContainer.appendChild(createDetailRow('Valor Pago', formatCurrency(paidAmount)));
    }
    
    // Detalhes de procedimento
    if (patientData.procedure) {
        detailsContainer.appendChild(createDetailRow('Procedimento', patientData.procedure_name || 'N/A'));
        detailsContainer.appendChild(createDetailRow('Valor do Procedimento', formatCurrency(procedureValue)));
    }
    
    // Total
    detailsContainer.appendChild(createDetailRow('Total', formatCurrency(totalValue)));
    
    // Exibir modal
    modal.classList.remove('hidden');
}
// Fechar modal
document.getElementById('close-financial-modal').addEventListener('click', () => {
    document.getElementById('financial-modal').classList.add('hidden');
});

// Adicionar fechamento do modal ao clicar fora
document.getElementById('financial-modal').addEventListener('click', (event) => {
    if (event.target === event.currentTarget) {
        event.currentTarget.classList.add('hidden');
    }
});
</script>

    </div>

    <script>
        function confirmDelete() {
            return confirm('Tem certeza que deseja excluir este paciente?');
        }

        document.getElementById('start-service-form').addEventListener('submit', function(e) {
            const confirmacao = confirm('Tem certeza que deseja iniciar um novo atendimento? Todos os pacientes serão removidos das listas.');
            if (!confirmacao) {
                e.preventDefault();
            }
        });

        // Função para atualizar as listas de pacientes
        function updatePatientLists() {
            fetch(window.location.href)
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    
                    const waitingPatients = doc.getElementById('waiting-patients');
                    const calledPatients = doc.getElementById('called-patients');
                    
                    if (waitingPatients) {
                        document.getElementById('waiting-patients').innerHTML = waitingPatients.innerHTML;
                    }
                    if (calledPatients) {
                        document.getElementById('called-patients').innerHTML = calledPatients.innerHTML;
                    }
                });
        }

        // Atualiza as listas a cada 30 segundos
        setInterval(updatePatientLists, 30000);
    </script>
</body>
</html>