<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

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

/**
 * Ringkasan laporan (dashboard angka) lewat `/api/admin/laporan`.
 */
class Laporan extends BaseAdminController
{
    public function index(): ResponseInterface|string
    {
        if (($deny = $this->enforceAccess('laporan')) !== null) {
            return $deny;
        }

        $today = date('Y-m-d');
        $dari  = (string) ($this->request->getGet('dari') ?? $today);
        $sampai = (string) ($this->request->getGet('sampai') ?? $today);

        $errors  = [];
        $summary = null;

        $r = $this->apiAdminGet('laporan', ['dari' => $dari, 'sampai' => $sampai]);
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            $summary = $r['json']['data'] ?? null;
        } else {
            $errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat laporan') : 'Gagal memuat laporan');
        }

        return view('admin/laporan/index', [
            'summary' => is_array($summary) ? $summary : null,
            'errors'  => $errors,
            'dari'    => $dari,
            'sampai'  => $sampai,
        ]);
    }

    public function cuti(): ResponseInterface|string
    {
        if (($deny = $this->enforceAccess('laporan')) !== null) {
            return $deny;
        }

        $today  = date('Y-m-d');
        $dari   = (string) ($this->request->getGet('dari') ?? $today);
        $sampai = (string) ($this->request->getGet('sampai') ?? $today);

        $errors = [];
        $rows   = [];
        $meta   = ['dari' => $dari, 'sampai' => $sampai];
        $r      = $this->apiAdminGet('laporan/cuti', ['dari' => $dari, 'sampai' => $sampai]);
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            $d = $r['json']['data'] ?? [];
            $rows = is_array($d['rows'] ?? null) ? $d['rows'] : [];
            $meta = [
                'dari'   => (string) ($d['dari'] ?? $dari),
                'sampai' => (string) ($d['sampai'] ?? $sampai),
            ];
        } else {
            $errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
        }

        return view('admin/laporan/cuti', [
            'rows'   => $rows,
            'errors' => $errors,
            'dari'   => $meta['dari'],
            'sampai' => $meta['sampai'],
        ]);
    }
}
