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

use PhpOffice\PhpSpreadsheet\IOFactory;

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

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['excel_file'])) {
    try {
        $inputFileName = $_FILES['excel_file']['tmp_name'];
        
        // Carregar arquivo Excel
        $spreadsheet = IOFactory::load($inputFileName);
        $worksheet = $spreadsheet->getActiveSheet();
        $rows = $worksheet->toArray();
        
        // Remover cabeçalho
        array_shift($rows);
        
        $importados = 0;
        $erros = 0;
        $erroDetalhes = [];
        
        foreach ($rows as $index => $row) {
            // Mapear colunas do Excel para o banco de dados
            $patient = [
                'name' => trim($row[0] ?? ''), // Nome na coluna A
                'cpf' => trim($row[1] ?? ''),  // CPF na coluna B
                'rg' => trim($row[2] ?? ''),   // RG na coluna C
                'birth_date' => !empty($row[3]) ? date('Y-m-d', strtotime(str_replace('/', '-', $row[3]))) : null,
                'gender' => strtoupper(substr(trim($row[4] ?? ''), 0, 1)), // Pega primeira letra
                'email' => trim($row[5] ?? ''),
                'whatsapp' => trim($row[6] ?? ''),
                'phone' => trim($row[7] ?? ''),
                'phone2' => trim($row[8] ?? ''),
                'cep' => trim($row[9] ?? ''),
                'street' => trim($row[10] ?? ''),
                'number' => trim($row[11] ?? ''),
                'complement' => trim($row[12] ?? ''),
                'neighborhood' => trim($row[13] ?? ''),
                'city' => trim($row[14] ?? ''),
                'state' => trim($row[15] ?? ''),
                'notes' => trim($row[16] ?? ''),
                'status' => 'Ativo'
            ];
            
            // Validar dados obrigatórios
            if (empty($patient['name'])) {
                $erros++;
                $erroDetalhes[] = "Linha " . ($index + 2) . ": Nome é obrigatório";
                continue;
            }
            
            // Limpar dados
            $patient['cpf'] = preg_replace('/[^0-9]/', '', $patient['cpf']);
            $patient['whatsapp'] = preg_replace('/[^0-9]/', '', $patient['whatsapp']);
            $patient['phone'] = preg_replace('/[^0-9]/', '', $patient['phone']);
            $patient['phone2'] = preg_replace('/[^0-9]/', '', $patient['phone2']);
            $patient['cep'] = preg_replace('/[^0-9]/', '', $patient['cep']);
            
            if (savePatientData($patient)) {
                $importados++;
            } else {
                $erros++;
                $erroDetalhes[] = "Linha " . ($index + 2) . ": Erro ao salvar paciente " . $patient['name'];
            }
        }
        
        $message = "Importação concluída! Importados: $importados | Erros: $erros";
        if (!empty($erroDetalhes)) {
            $message .= "<br>Detalhes dos erros:<br>" . implode("<br>", $erroDetalhes);
        }
        $messageType = $erros === 0 ? 'success' : 'error';
        
    } catch (Exception $e) {
        $message = "Erro ao importar arquivo: " . $e->getMessage();
        $messageType = 'error';
    }
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Importar 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">Importar Pacientes</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="<?= $messageType === 'success' ? 'bg-green-100 border-green-400 text-green-700' : 'bg-red-100 border-red-400 text-red-700' ?> px-4 py-3 rounded relative mb-4">
                <?= $message ?>
            </div>
        <?php endif; ?>

        <div class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
            <form method="post" enctype="multipart/form-data">
                <div class="mb-6">
                    <label class="block text-gray-700 text-sm font-bold mb-2">
                        Arquivo Excel (.xlsx)
                    </label>
                    <input type="file" name="excel_file" accept=".xlsx" required
                           class="shadow appearance-none border rounded w-full py-2 px-3">
                    <p class="text-gray-600 text-xs mt-1">
                        O arquivo Excel deve ter pelo menos a coluna Nome (primeira coluna).
                        Os pacientes serão importados com prioridade padrão e serão associados ao consultório atual.
                    </p>
                </div>

                <div class="flex justify-end">
                    <button type="submit" 
                            class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                        Importar
                    </button>
                </div>
            </form>
        </div>
    </div>
</body>
</html> 