<?php

declare(strict_types=1);

namespace App\Controllers\Api\Admin;

use CodeIgniter\HTTP\ResponseInterface;

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

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

        $today = date('Y-m-d');
        $dari  = (string) ($this->request->getGet('tanggal_dari') ?? $today);
        $sampai = (string) ($this->request->getGet('tanggal_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];
        }

        $page    = (int) ($this->request->getGet('page') ?? 1);
        $perPage = (int) ($this->request->getGet('per_page') ?? 30);
        $q       = (string) ($this->request->getGet('q') ?? '');

        return $this->respond($this->adminApi->presensiList($dari, $sampai, $page, $perPage, $q, $cb['kid']));
    }

    public function show(?string $id = null): ResponseInterface
    {
        $auth = $this->requireAdminApiAccess('presensi');
        if ($auth['response'] !== null) {
            return $auth['response'];
        }
        $cb = $this->cabangKantorAfterAuth($auth['actor']);
        if ($cb['response'] !== null) {
            return $cb['response'];
        }

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

        $idInt = (int) ($id ?? 0);
        if ($idInt <= 0) {
            return $this->respond(['status' => 0, 'pesan' => 'ID tidak valid'], 400);
        }

        return $this->respond($this->adminApi->presensiShow($idInt, $cb['kid']));
    }
}
