<?php
if (session_status() === PHP_SESSION_NONE) session_start();

// A view espera que o controller defina $employee (associative array).
$employee = $employee ?? null;
$errorMessage = $errorMessage ?? null;

if (!$employee) {
    // Se acessado diretamente sem controller, redireciona para a listagem.
    if (defined('BASE_URL')) {
        header('Location: ' . rtrim(BASE_URL, '/') . '/employees');
        exit;
    }
}

if (!function_exists('e')) {
    function e(?string $v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}

// Inclui os partials do layout (cabeçalho/rodapé)
require_once dirname(__DIR__, 1) . '/partials/header.php';
?>

<style>
    .details-container { max-width: 760px; margin: 24px auto; padding: 20px; background:#fff; border-radius:10px; border:1px solid #e9ecef; }
    .details-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; border-bottom:1px solid #dee2e6; padding-bottom:12px; }
    .details-header h1 { font-size:1.6rem; margin:0; }
    .details-content { display:flex; flex-wrap:wrap; gap:24px; }
    .photo-column { flex: 0 0 140px; text-align:center; }
    .details-column { flex:1; min-width:240px; }
    .employee-photo-preview { width:120px; height:120px; border-radius:50%; object-fit:cover; border:3px solid #e9ecef; }
    .info-group { margin-bottom:14px; }
    .info-group strong { display:block; color:#6c757d; margin-bottom:6px; font-size:0.85rem; text-transform:uppercase; }
    .info-group span { font-size:1.02rem; color:#212529; }
</style>

<!-- Cabeçalho de página no estilo RH -->
<div class="container-fluid py-4">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="mb-1" style="color: #2c3e50; font-weight: 600;">
                    <i class="bi bi-person-badge me-2"></i>Colaborador
                    <?= !empty($employee['full_name']) ? '— ' . e($employee['full_name']) : '' ?>
                </h1>
                <p class="text-muted mb-0">Detalhes do colaborador e informações pessoais</p>
            </div>
        </div>

        <div class="details-container">
        <div class="details-header">
            <h1><?= e($employee['full_name'] ?? 'Colaborador') ?></h1>
            <a href="<?= rtrim(BASE_URL, '/') ?>/employees" class="btn btn-outline-secondary btn-sm">Voltar</a>
        </div>

        <?php if (!empty($errorMessage)): ?>
            <div class="alert alert-danger"><?= e($errorMessage) ?></div>
        <?php elseif (!$employee): ?>
            <div class="alert alert-warning">Colaborador não encontrado.</div>
        <?php else: ?>
            <div class="details-content">
                <div class="photo-column">
                    <?php
                        $defaultPhoto = (defined('BASE_URL') ? rtrim(BASE_URL, '/') : '') . '/assets/images/default-avatar.png';
                        $photoPath = $defaultPhoto;
                        $rel = '';
                        if (!empty($employee['photo_path'])) {
                            $rel = ltrim($employee['photo_path'], '/\\');
                        }
                    ?>
                    <img id="employee-photo" src="<?= $photoPath ?>" alt="Foto de <?= e($employee['full_name']) ?>" class="employee-photo-preview" data-rel="<?= e($rel) ?>">

                    <?php if (!empty($rel)): ?>
                    <script>
                        (function(){
                            const rel = <?= json_encode($rel) ?>;
                            const base = <?= json_encode(rtrim(defined('BASE_URL') ? BASE_URL : '', '/')) ?>;
                            const img = document.getElementById('employee-photo');
                            const candidates = [];
                            if (base) {
                                candidates.push(base + '/' + rel);
                                candidates.push(base + '/public/' + rel);
                            }
                            candidates.push('/' + rel);
                            candidates.push('/public/' + rel);

                            function testUrl(url, cb) {
                                const i = new Image();
                                i.onload = function(){ cb(true, url); };
                                i.onerror = function(){ cb(false, url); };
                                i.src = url + (url.indexOf('?') === -1 ? '' : '');
                            }

                            (function findNext(index){
                                if (index >= candidates.length) return; // nenhum candidato válido
                                testUrl(candidates[index], function(ok, url){
                                    if (ok) { img.src = url; }
                                    else { findNext(index+1); }
                                });
                            })(0);
                        })();
                    </script>
                    <?php endif; ?>
                </div>

                <div class="details-column">
                    <div class="row">
                        <div class="col-md-6 info-group">
                            <strong>Cargo:</strong>
                            <span><?= e($employee['job_title']) ?></span>
                        </div>
                        <div class="col-md-6 info-group">
                            <strong>Status:</strong>
                            <span><?= ucfirst(e($employee['status'] ?? '')) ?></span>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 info-group">
                            <strong>Email:</strong>
                            <span><?= e($employee['email'] ?? 'Não informado') ?></span>
                        </div>
                        <div class="col-md-6 info-group">
                            <strong>Telefone:</strong>
                            <span><?= e($employee['phone_number'] ?? '') ?></span>
                        </div>
                    </div>

                    <div class="info-group">
                        <strong>Endereço:</strong>
                        <span><?= e($employee['address'] ?? '') ?></span>
                    </div>

                    <div class="row">
                        <div class="col-md-6 info-group">
                            <strong>Admissão:</strong>
                            <span><?= !empty($employee['hire_date']) ? date('d/m/Y', strtotime($employee['hire_date'])) : '' ?></span>
                        </div>
                        <div class="col-md-6 info-group">
                            <strong>Salário:</strong>
                            <span><?= isset($employee['salary']) ? 'R$ ' . number_format((float)$employee['salary'], 2, ',', '.') : '' ?></span>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
        </div>
    </div>
</div>

<?php require_once dirname(__DIR__, 1) . '/partials/footer.php';