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

// Verificar login
requireLogin();

// Verificar se é um usuário admin
if ($_SESSION['user']['type'] !== 'admin') {
    header("Location: ../index.php");
    exit();
}

// Processamento do formulário de cadastro
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $users_file = '../data/users.json';
    
    // Carregar usuários existentes
    $users = json_decode(file_get_contents($users_file), true) ?: [];
    
    // Validações básicas
    $username = trim($_POST['username']);
    $name = trim($_POST['name']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $type = $_POST['type'];
    $office_id = $_POST['office_id'] ?? null;
    
    // Verificar se usuário já existe
    $user_exists = false;
    foreach ($users as $existing_user) {
        if ($existing_user['username'] === $username) {
            $user_exists = true;
            break;
        }
    }
    
    if ($user_exists) {
        $error = "Usuário já existe";
    } elseif (empty($username) || empty($name) || empty($password)) {
        $error = "Todos os campos são obrigatórios";
    } elseif ($password !== $confirm_password) {
        $error = "Senhas não conferem";
    } else {
        // Criar novo usuário
        $new_user = [
            'id' => uniqid(),
            'username' => $username,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'name' => $name,
            'type' => $type,
            'office_id' => $type === 'doctor' ? $office_id : null
        ];
        
        // Adicionar novo usuário
        $users[] = $new_user;
        
        // Salvar usuários
        file_put_contents($users_file, json_encode($users, JSON_PRETTY_PRINT));
        
        $success = "Usuário cadastrado com sucesso!";
        
        // Limpar campos após sucesso
        $username = $name = $type = $office_id = '';
    }
}

// Carregar consultórios para médicos
$offices = loadOffices();

function loadOffices() {
    $offices_file = BASE_PATH . '/data/offices.json';
    if (!file_exists($offices_file)) {
        $default_offices = [
            ['id' => uniqid(), 'name' => 'Clínico Geral'],
            ['id' => uniqid(), 'name' => 'Pediatria'],
            ['id' => uniqid(), 'name' => 'Ginecologia'],
            ['id' => uniqid(), 'name' => 'Dermatologia']
        ];
        usort($default_offices, function($a, $b) {
            return strcmp($a['name'], $b['name']);
        });
        file_put_contents($offices_file, json_encode($default_offices, JSON_PRETTY_PRINT));
        return $default_offices;
    }
    $offices = json_decode(file_get_contents($offices_file), true) ?: [];
    usort($offices, function($a, $b) {
        return strcmp($a['name'], $b['name']);
    });
    return $offices;
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Cadastro de Usuários</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">Cadastro de Usuários</h1>
            <div class="flex items-center space-x-4">
                <span class="text-gray-700">Bem-vindo, <?= htmlspecialchars($_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>

        <?php if ($error): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
                <?= htmlspecialchars($success) ?>
            </div>
        <?php endif; ?>

        <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
            <div class="mb-4">
                <label class="block text-gray-700 text-sm font-bold mb-2" for="username">
                    Usuário
                </label>
                <input 
                    type="text" 
                    name="username" 
                    value="<?= htmlspecialchars($username ?? '') ?>"
                    required 
                    class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700"
                >
            </div>

            <div class="mb-4">
                <label class="block text-gray-700 text-sm font-bold mb-2" for="name">
                    Nome Completo
                </label>
                <input 
                    type="text" 
                    name="name" 
                    value="<?= htmlspecialchars($name ?? '') ?>"
                    required 
                    class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700"
                >
            </div>

            <div class="mb-4">
                <label class="block text-gray-700 text-sm font-bold mb-2" for="type">
                    Tipo de Usuário
                </label>
                <select 
                    name="type" 
                    required 
                    class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700"
                    onchange="toggleOfficeField(this)"
                >
                    <option value="">Selecione o Tipo</option>
                    <option value="admin" <?= ($type ?? '') === 'admin' ? 'selected' : '' ?>>Administrador</option>
                    <option value="doctor" <?= ($type ?? '') === 'doctor' ? 'selected' : '' ?>>Médico</option>
                </select>
            </div>

            <div id="office-field" class="mb-4" style="display: none;">
                <label class="block text-gray-700 text-sm font-bold mb-2" for="office_id">
                    Consultório
                </label>
                <select 
                    name="office_id" 
                    class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700"
                >
                    <option value="">Selecione o Consultório</option>
                    <?php foreach ($offices as $office): ?>
                        <option value="<?= $office['id'] ?>" <?= ($office_id ?? '') === $office['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($office['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="mb-4">
                <label class="block text-gray-700 text-sm font-bold mb-2" for="password">
                    Senha
                </label>
                <input 
                    type="password" 
                    name="password" 
                    required 
                    class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700"
                >
            </div>

            <div class="mb-6">
                <label class="block text-gray-700 text-sm font-bold mb-2" for="confirm_password">
                    Confirmar Senha
                </label>
                <input 
                    type="password" 
                    name="confirm_password" 
                    required 
                    class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700"
                >
            </div>

            <div class="flex items-center justify-center">
                <button 
                    type="submit" 
                    class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                >
                    Cadastrar Usuário
                </button>
            </div>
        </form>
    </div>
    
    <script>
        function toggleOfficeField(select) {
            const officeField = document.getElementById('office-field');
            officeField.style.display = select.value === 'doctor' ? 'block' : 'none';
        }

        // Inicializa o estado do campo de consultório
        document.addEventListener('DOMContentLoaded', function() {
            const typeSelect = document.querySelector('select[name="type"]');
            toggleOfficeField(typeSelect);
        });
    </script>
</body>
</html>