<?php
declare(strict_types=1);

/** @var array<string, mixed>|object|null $profil */
$p = $profil ?? null;
if (is_object($p)) {
    $json = json_encode($p);
    $p    = is_string($json) ? json_decode($json, true) : [];
}
$p = is_array($p) ? $p : [];

/**
 * @param array<string, mixed> $row
 */
$nestedNama = static function (mixed $row, string ...$keys): string {
    if (! is_array($row)) {
        return '';
    }
    foreach ($keys as $k) {
        if (isset($row[$k]) && is_string($row[$k]) && $row[$k] !== '') {
            return $row[$k];
        }
    }

    return '';
};

$fmtDate = static function (mixed $v): string {
    if ($v === null || $v === '') {
        return '—';
    }
    $s = trim((string) $v);
    if ($s === '' || str_starts_with($s, '0000-00-00')) {
        return '—';
    }
    if (preg_match('/^(\d{4}-\d{1,2}-\d{1,2})/', $s, $m)) {
        $t = strtotime($m[1]);

        return $t !== false ? date('d/m/Y', $t) : '—';
    }

    return '—';
};

$fmtDateTime = static function (mixed $v): string {
    if ($v === null || $v === '') {
        return '—';
    }
    $s = trim((string) $v);
    $t = strtotime($s);

    return $t !== false ? date('d/m/Y H:i', $t) : $s;
};

$fmtBool = static function (mixed $v): string {
    if ($v === null || $v === '') {
        return '—';
    }
    if (is_bool($v)) {
        return $v ? 'Ya' : 'Tidak';
    }
    $f = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

    return $f === null ? (string) $v : ($f ? 'Ya' : 'Tidak');
};

$scalarOrDash = static function (mixed $v): string {
    if ($v === null) {
        return '—';
    }
    if (is_bool($v)) {
        return $v ? 'Ya' : 'Tidak';
    }
    if (is_scalar($v)) {
        $s = trim((string) $v);

        return $s === '' ? '—' : $s;
    }

    return '—';
};

$lemburLabel = static function (mixed $v): string {
    if ($v === null || $v === false || $v === '') {
        return 'Tidak ada';
    }
    if (is_string($v) || is_int($v) || is_float($v)) {
        $s = trim((string) $v);

        return $s === '' ? 'Tidak ada' : $s;
    }
    if (is_array($v)) {
        return $v !== [] ? 'Ada (hari ini)' : 'Tidak ada';
    }
    if (is_object($v)) {
        $a = (array) $v;

        return $a !== [] ? 'Ada (hari ini)' : 'Tidak ada';
    }

    return '—';
};

$rows = [
    ['key' => 'nip', 'label' => 'NIP', 'fmt' => 'scalar'],
    ['key' => 'jenis_kelamin', 'label' => 'Jenis kelamin', 'fmt' => 'scalar'],
    ['key' => 'tempat_lahir', 'label' => 'Tempat lahir', 'fmt' => 'scalar'],
    ['key' => 'tanggal_lahir', 'label' => 'Tanggal lahir', 'fmt' => 'date'],
    ['key' => 'email', 'label' => 'Email', 'fmt' => 'scalar'],
    ['key' => 'kantor', 'label' => 'Kantor', 'fmt' => 'nested', 'nested' => ['nama_kantor', 'nama']],
    ['key' => 'jabatan', 'label' => 'Jabatan', 'fmt' => 'nested', 'nested' => ['nama_jabatan', 'nama']],
    ['key' => 'unit_kerja', 'label' => 'Unit kerja', 'fmt' => 'nested', 'nested' => ['nama_unit_kerja', 'nama']],
    ['key' => 'golongan_pekerjaan', 'label' => 'Golongan (ID)', 'fmt' => 'scalar'],
    ['key' => 'status_kepegawaian', 'label' => 'Status kepegawaian', 'fmt' => 'scalar'],
    ['key' => 'tanggal_bergabung', 'label' => 'Tanggal bergabung', 'fmt' => 'date'],
    ['key' => 'super_akses', 'label' => 'Super akses', 'fmt' => 'bool'],
    ['key' => 'last_login', 'label' => 'Terakhir login', 'fmt' => 'dt'],
    ['key' => 'lembur', 'label' => 'Lembur hari ini', 'fmt' => 'lembur'],
    ['key' => 'dilapangan', 'label' => 'Tugas luar / lapangan', 'fmt' => 'bool'],
];

$nama = (string) ($p['nama_lengkap'] ?? '');
$nip  = (string) ($p['nip'] ?? '');
$idPeg = isset($p['id_pegawai']) ? (string) $p['id_pegawai'] : '';
$photo = trim((string) ($p['photo'] ?? ''));
$jadwal = $p['jadwal'] ?? null;
?>

<section class="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm">
    <h2 class="text-xs font-semibold uppercase tracking-wide text-gray-500">Profil pegawai</h2>

    <?php if ($p === []) : ?>
        <div class="mt-4">
            <?= view('layouts/partials/empty_state', [
                'icon'  => 'fa-user',
                'title' => 'Belum ada data profil',
                'hint'  => 'Setelah login pegawai valid, ringkasan profil akan tampil di sini.',
            ]) ?>
        </div>
    <?php else : ?>
        <div class="mt-4 flex flex-col gap-4 border-b border-gray-100 pb-4 sm:flex-row sm:items-start sm:gap-5">
            <div class="flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-gray-200 bg-gray-50 text-gray-400">
                <?php if ($photo !== '') : ?>
                    <img src="<?= esc($photo) ?>" alt="" class="h-full w-full object-cover" loading="lazy" decoding="async" onerror="this.style.display='none'; this.nextElementSibling?.classList.remove('hidden');">
                    <i class="fa-solid fa-user hidden text-2xl"></i>
                <?php else : ?>
                    <i class="fa-solid fa-user text-2xl"></i>
                <?php endif ?>
            </div>
            <div class="min-w-0 flex-1">
                <p class="text-lg font-semibold tracking-tight text-gray-900"><?= esc($nama !== '' ? $nama : '—') ?></p>
                <?php if ($nip !== '') : ?>
                    <p class="mt-0.5 font-mono text-sm text-gray-600"><?= esc($nip) ?></p>
                <?php endif ?>
                <?php if ($idPeg !== '') : ?>
                    <p class="mt-1 text-xs text-gray-400">ID pegawai <?= esc($idPeg) ?></p>
                <?php endif ?>
            </div>
        </div>

        <dl class="mt-4 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2">
            <?php foreach ($rows as $spec) : ?>
                <?php
                $key = $spec['key'];
                $raw = $p[$key] ?? null;
                $label = $spec['label'];
                $fmt = $spec['fmt'];
                $out = '—';
                if ($fmt === 'scalar') {
                    $out = $scalarOrDash($raw);
                } elseif ($fmt === 'date') {
                    $out = $fmtDate($raw);
                } elseif ($fmt === 'dt') {
                    $out = $fmtDateTime($raw);
                } elseif ($fmt === 'bool') {
                    $out = $fmtBool($raw);
                } elseif ($fmt === 'lembur') {
                    $out = $lemburLabel($raw);
                } elseif ($fmt === 'nested' && isset($spec['nested'])) {
                    $out = $nestedNama(is_array($raw) ? $raw : (is_object($raw) ? (array) $raw : []), ...$spec['nested']);
                    $out = $out !== '' ? $out : '—';
                }
                if ($key === 'email' && $out === '—') {
                    continue;
                }
                ?>
                <div class="flex flex-col gap-0.5 border-b border-gray-50 pb-3 sm:border-0 sm:pb-0">
                    <dt class="text-xs font-medium text-gray-500"><?= esc($label) ?></dt>
                    <dd class="font-medium text-gray-900"><?= esc((string) $out) ?></dd>
                </div>
            <?php endforeach ?>
        </dl>

        <?php if (is_array($jadwal) && $jadwal !== []) : ?>
            <div class="mt-5 rounded-xl border border-gray-100 bg-gray-50/80 px-4 py-3">
                <p class="text-xs font-semibold uppercase tracking-wide text-gray-500">Jadwal hari ini</p>
                <p class="mt-1 text-sm text-gray-800">
                    <?php
                    $hari = (string) ($jadwal['hari'] ?? '');
                    $masuk = (string) ($jadwal['masuk'] ?? '');
                    $pulang = (string) ($jadwal['pulang'] ?? '');
                    $ket = (string) ($jadwal['ket_libur'] ?? '');
                    $libur = ! empty($jadwal['libur']);
                    ?>
                    <?php if ($hari !== '') : ?><span class="font-medium"><?= esc($hari) ?></span><?php endif ?>
                    <?php if (! $libur && ($masuk !== '' || $pulang !== '')) : ?>
                        <span class="text-gray-600"> · Masuk <?= esc($masuk !== '' ? $masuk : '—') ?>, pulang <?= esc($pulang !== '' ? $pulang : '—') ?></span>
                    <?php endif ?>
                    <?php if ($ket !== '') : ?>
                        <span class="mt-1 block text-xs text-amber-800"><?= esc($ket) ?></span>
                    <?php elseif ($libur && $ket === '') : ?>
                        <span class="mt-1 block text-xs text-gray-600">Hari libur / tidak ada jadwal masuk</span>
                    <?php endif ?>
                </p>
            </div>
        <?php endif ?>
    <?php endif ?>
</section>
