<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Services\ApiClient;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Beranda: statistik admin (`/api/admin/dashboard`) + profil/berita mobile (opsional).
 */
class Dashboard extends BaseAdminController
{
    public function index(): string|ResponseInterface
    {
        if (($deny = $this->enforceAccess('dashboard')) !== null) {
            return $deny;
        }

        $token   = $this->adminToken();
        $profil  = null;
        $berita  = null;
        $errors  = [];
        $summary = null;

        if ($token === null) {
            $errors[] = 'Silakan login untuk memuat data dari API.';
        } else {
            $d = $this->apiAdminGet('dashboard');
            if ($d['transport_ok'] && ApiClient::isSuccess($d['json'])) {
                $summary = $d['json']['data'] ?? null;
            } else {
                $errors[] = $d['error'] ?? (is_array($d['json']) ? (string) ($d['json']['pesan'] ?? 'Ringkasan dashboard tidak dapat dimuat.') : 'Ringkasan dashboard tidak dapat dimuat.');
            }

            $p = $this->apiMobile('profil', []);
            if ($p['transport_ok'] && ApiClient::isSuccess($p['json'])) {
                $profil = $p['json']['pegawai'] ?? null;
            } else {
                $errors[] = $p['error'] ?? (is_array($p['json']) ? (string) ($p['json']['pesan'] ?? 'Profil tidak dapat dimuat.') : 'Profil tidak dapat dimuat.');
            }

            $b = $this->apiMobile('berita', ['dari' => '0', 'jumlah' => '5']);
            if ($b['transport_ok'] && ApiClient::isSuccess($b['json'])) {
                $berita = $b['json']['data'] ?? [];
            } else {
                $errors[] = $b['error'] ?? (is_array($b['json']) ? (string) ($b['json']['pesan'] ?? 'Berita tidak dapat dimuat.') : 'Berita tidak dapat dimuat.');
            }
        }

        helper('cuti_display');

        return view('admin/dashboard/index', [
            'summary' => is_array($summary) ? $summary : null,
            'profil'  => $profil,
            'berita'  => is_array($berita) ? $berita : [],
            'errors'  => $errors,
            'token'   => $token !== null,
        ]);
    }
}
