<?php
// create.php — Página para Adicionar Novo Colaborador (Design Refinado)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$pageTitle = 'Novo Colaborador';
require_once __DIR__ . '/../partials/header.php'; // Inclui o cabeçalho azul escuro que criamos

$old = $_SESSION['old'] ?? [];
$bairros = require __DIR__ . '/../../../src/config/bairros.php';
?>

<main>
    <div class="border-b border-slate-200 bg-white">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-5">
            <nav class="text-sm" aria-label="Breadcrumb">
                <ol class="flex items-center gap-2 text-slate-500">
                    <li>
                        <a href="<?= BASE_URL ?>/employees"
                            class="hover:text-indigo-600 font-medium transition-colors">Colaboradores</a>
                    </li>
                    <li class="text-slate-400">/</li>
                    <li class="font-semibold text-slate-800">Novo Colaborador</li>
                </ol>
            </nav>
            <h1 class="mt-3 text-2xl sm:text-3xl font-bold tracking-tight text-slate-900">
                Adicionar Novo Colaborador
            </h1>
        </div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <?php if (!empty($_SESSION['errors'])): ?>
            <div class="rounded-md bg-red-50 p-4 mb-6 border border-red-200" role="alert">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <svg class="h-5 w-5 text-red-500" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                            <path fill-rule="evenodd"
                                d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.28 7.22a.75.75 0 00-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 101.06 1.06L10 11.06l1.72 1.72a.75.75 0 101.06-1.06L11.06 10l1.72-1.72a.75.75 0 00-1.06-1.06L10 8.94 8.28 7.22z"
                                clip-rule="evenodd" />
                        </svg>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-red-800">Foram encontrados alguns erros:</h3>
                        <ul class="mt-2 text-sm text-red-700 list-disc pl-5 space-y-1">
                            <?php foreach ($_SESSION['errors'] as $error): ?>
                                <li><?= htmlspecialchars($error) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>
            <?php unset($_SESSION['errors']); ?>
        <?php endif; ?>

        <form method="POST" action="<?= BASE_URL ?>/employees/store" enctype="multipart/form-data" novalidate>
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

                <div class="lg:col-span-2 space-y-8">
                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 rounded-xl">
                        <div class="px-6 py-5">
                            <h2 class="text-lg font-semibold text-slate-900">Informações Pessoais</h2>
                            <p class="mt-1 text-sm text-slate-500">Dados de identificação do colaborador.</p>
                        </div>
                        <div class="p-6 border-t border-slate-200 grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-5">
                            <div class="sm:col-span-2">
                                <label for="full_name" class="block text-sm font-medium text-slate-700">Nome completo
                                    *</label>
                                <input type="text" id="full_name" name="full_name" required
                                    value="<?= htmlspecialchars($old['full_name'] ?? '') ?>"
                                    class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition sm:text-sm">
                            </div>
                            <div>
                                <label for="cpf" class="block text-sm font-medium text-slate-700">CPF *</label>
                                <input type="text" id="cpf" name="cpf" required placeholder="000.000.000-00"
                                    value="<?= htmlspecialchars($old['cpf'] ?? '') ?>"
                                    class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition sm:text-sm">
                            </div>
                            <div>
                                <label for="phone_number"
                                    class="block text-sm font-medium text-slate-700">Telefone</label>
                                <input type="text" id="phone_number" name="phone_number" placeholder="(00) 00000-0000"
                                    value="<?= htmlspecialchars($old['phone_number'] ?? '') ?>"
                                    class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition sm:text-sm">
                            </div>
                            <div class="sm:col-span-2">
                                <label for="address" class="block text-sm font-medium text-slate-700">Endereço</label>
                                <input type="text" id="address" name="address"
                                    value="<?= htmlspecialchars($old['address'] ?? '') ?>"
                                    class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition sm:text-sm">
                            </div>
                            <div class="sm:col-span-2">
                                <label for="bairro" class="block text-sm font-medium text-slate-700">Bairro</label>
                                <input type="text" id="bairro" name="bairro" list="lista-bairros"
                                    placeholder="Selecione ou digite..."
                                    value="<?= htmlspecialchars($old['bairro'] ?? '') ?>"
                                    class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition sm:text-sm">
                                <datalist id="lista-bairros">
                                    <?php foreach ($bairros as $b): ?>
                                        <option value="<?= htmlspecialchars($b) ?>">
                                        <?php endforeach; ?>
                                </datalist>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 rounded-xl">
                        <div class="px-6 py-5">
                            <h2 class="text-lg font-semibold text-slate-900">Informações do Cargo</h2>
                            <p class="mt-1 text-sm text-slate-500">Detalhes sobre a função e remuneração.</p>
                        </div>
                        <div class="p-6 border-t border-slate-200 grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-5">
                            <div>
                                <label for="job_title" class="block text-sm font-medium text-slate-700">Cargo *</label>
                                <input type="text" id="job_title" name="job_title" required
                                    value="<?= htmlspecialchars($old['job_title'] ?? '') ?>"
                                    class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition sm:text-sm">
                            </div>
                            <div>
                                <label for="salary" class="block text-sm font-medium text-slate-700">Salário
                                    (R$)</label>
                                <input type="text" id="salary" name="salary" placeholder="1.412,00"
                                    value="<?= htmlspecialchars($old['salary'] ?? '') ?>"
                                    class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 transition sm:text-sm">
                            </div>
                        </div>
                    </div>
                </div>

                <div>
                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 rounded-xl">
                        <div class="px-6 py-5">
                            <h2 class="text-lg font-semibold text-slate-900">Foto de Perfil</h2>
                        </div>
                        <div class="p-6 border-t border-slate-200 flex flex-col items-center text-center">
                            <img id="photoPreview" src="<?= BASE_URL ?>/assets/img/placeholder-user.png"
                                alt="Prévia da foto"
                                class="h-40 w-40 rounded-full object-cover bg-slate-100 mb-4 ring-4 ring-white">
                            <label for="photo"
                                class="cursor-pointer rounded-md bg-slate-100 px-3.5 py-2 text-sm font-semibold text-slate-800 shadow-sm hover:bg-slate-200 transition-colors">
                                <span>Escolher foto</span>
                                <input id="photo" name="photo" type="file" class="sr-only" accept="image/*">
                            </label>
                            <p class="mt-2 text-xs text-slate-500">PNG, JPG ou GIF (máx. 10MB)</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mt-8 pt-5 border-t border-slate-200 flex justify-end gap-3">
                <a href="<?= BASE_URL ?>/employees"
                    class="rounded-md bg-white px-4 py-2 text-sm font-semibold text-slate-900 shadow-sm ring-1 ring-inset ring-slate-300 hover:bg-slate-50 transition-all duration-200">
                    Cancelar
                </a>
                <button type="submit"
                    class="inline-flex justify-center rounded-md bg-indigo-600 px-5 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 transition-all duration-200">
                    Salvar Colaborador
                </button>
            </div>
        </form>
    </div>
</main>
<?php
unset($_SESSION['old']);
require_once __DIR__ . '/../partials/footer.php';
?>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const photoInput = document.getElementById('photo');
        const photoPreview = document.getElementById('photoPreview');
        if (photoInput && photoPreview) {
            photoInput.addEventListener('change', (event) => {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => { photoPreview.src = e.target.result; };
                    reader.readAsDataURL(file);
                }
            });
        }

        const maskCPF = (v) => v.replace(/\D/g, '').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d{1,2})$/, '$1-$2').slice(0, 14);
        const maskPhone = (v) => {
            v = v.replace(/\D/g, '');
            return v.length > 10 ? v.replace(/(\d{2})(\d{5})(\d{4}).*/, '($1) $2-$3') : v.replace(/(\d{2})(\d{4})(\d{0,4}).*/, '($1) $2-$3');
        };
        const formatSalary = (v) => {
            v = v.replace(/\D/g, '');
            if (!v) return '';
            v = (parseInt(v, 10) / 100).toFixed(2).replace('.', ',');
            return v.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
        };

        const cpfInput = document.getElementById('cpf');
        if (cpfInput) cpfInput.addEventListener('input', e => { e.target.value = maskCPF(e.target.value); });

        const phoneInput = document.getElementById('phone_number');
        if (phoneInput) phoneInput.addEventListener('input', e => { e.target.value = maskPhone(e.target.value); });

        const salaryInput = document.getElementById('salary');
        if (salaryInput) salaryInput.addEventListener('input', e => { e.target.value = formatSalary(e.target.value); });
    });
</script>