<?php

declare(strict_types=1);

if (! function_exists('cuti_tanggal_label')) {
    /**
     * Label tanggal cuti untuk tampilan admin (d/m/Y). Nilai tidak valid → tanda em dash.
     * Menerima string (Y-m-d, ISO datetime, d/m/Y), DateTimeInterface, angka 8 digit yyyymmdd, atau array hasil JSON aneh.
     */
    function cuti_tanggal_label(mixed $raw): string
    {
        if ($raw === null || $raw === '') {
            return '—';
        }

        if (is_array($raw)) {
            $raw = $raw['date'] ?? $raw['value'] ?? null;
            if ($raw === null || $raw === '') {
                return '—';
            }
        }

        if ($raw instanceof \DateTimeInterface) {
            return $raw->format('d/m/Y');
        }

        if (is_object($raw) && ! $raw instanceof \Stringable) {
            return '—';
        }

        if ($raw instanceof \Stringable) {
            $raw = (string) $raw;
        }

        if (is_int($raw)) {
            $s = (string) $raw;
            if (strlen($s) === 8 && preg_match('/^\d{8}$/', $s)) {
                $y = substr($s, 0, 4);
                $m = substr($s, 4, 2);
                $d = substr($s, 6, 2);
                $ts = strtotime($y . '-' . $m . '-' . $d);

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

            return '—';
        }

        if (is_float($raw)) {
            return '—';
        }

        if (! is_string($raw)) {
            return '—';
        }

        $s = trim($raw);
        if ($s === '' || str_starts_with($s, '0000-00-00')) {
            return '—';
        }

        if (preg_match('/^(\d{4}-\d{1,2}-\d{1,2})/', $s, $m)) {
            $ts = strtotime($m[1]);
            if ($ts !== false) {
                return date('d/m/Y', $ts);
            }
        }

        foreach (['!d/m/Y', '!d-m-Y', '!j/n/Y', '!j-n-Y'] as $fmt) {
            $dt = \DateTimeImmutable::createFromFormat($fmt, $s);
            if ($dt instanceof \DateTimeImmutable) {
                return $dt->format('d/m/Y');
            }
        }

        $ts = strtotime($s);

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

if (! function_exists('cuti_tanggal_label_from_row')) {
    /**
     * Ambil tanggal cuti dari baris API/DB (kunci case-insensitive + fallback kolom umum).
     */
    function cuti_tanggal_label_from_row(array $row): string
    {
        $lower = array_change_key_case($row, CASE_LOWER);
        $raw   = $lower['tanggal_cuti'] ?? $lower['tanggal'] ?? $lower['tgl_cuti'] ?? null;

        return cuti_tanggal_label($raw);
    }
}
