<?php

declare(strict_types=1);

namespace App\Controllers\Api\Admin;

use CodeIgniter\HTTP\ResponseInterface;

class LaporanController extends BaseAdminApiController
{
    public function index(): ResponseInterface
    {
        $auth = $this->requireAdminApiAccess('laporan');
        if ($auth['response'] !== null) {
            return $auth['response'];
        }
        $cb = $this->cabangKantorAfterAuth($auth['actor']);
        if ($cb['response'] !== null) {
            return $cb['response'];
        }

        $this->auditAuthorized('api.admin.laporan.index', $auth['actor'], [
            'request' => $this->auditRequestParams(),
        ]);

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

        if (strtotime($dari) === false || strtotime($sampai) === false) {
            return $this->respond(['status' => 0, 'pesan' => 'Format tanggal tidak valid'], 400);
        }

        if ($dari > $sampai) {
            [$dari, $sampai] = [$sampai, $dari];
        }

        return $this->respond($this->adminApi->laporanSummary($dari, $sampai, $cb['kid']));
    }

    /**
     * Laporan cuti rentang tanggal (parity CI3 laporan/fcuti — data tabel).
     */
    public function cutiRentang(): ResponseInterface
    {
        $auth = $this->requireAdminApiAccess('laporan');
        if ($auth['response'] !== null) {
            return $auth['response'];
        }
        $cb = $this->cabangKantorAfterAuth($auth['actor']);
        if ($cb['response'] !== null) {
            return $cb['response'];
        }

        $this->auditAuthorized('api.admin.laporan.cuti_rentang', $auth['actor'], [
            'request' => $this->auditRequestParams(),
        ]);

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

        if (strtotime($dari) === false || strtotime($sampai) === false) {
            return $this->respond(['status' => 0, 'pesan' => 'Format tanggal tidak valid'], 400);
        }
        if ($dari > $sampai) {
            [$dari, $sampai] = [$sampai, $dari];
        }

        return $this->respond($this->adminExtra->laporanCutiRentang($dari, $sampai, $cb['kid']));
    }
}
