<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

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

/**
 * Panel pengguna admin (Ion) — API `/api/admin/panel/*`.
 */
class Panel extends BaseAdminController
{
    public function users(): ResponseInterface|string
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

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

        return view('admin/panel/users', ['rows' => $rows, 'errors' => $errors]);
    }

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

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

        return view('admin/panel/groups', ['rows' => $rows, 'errors' => $errors]);
    }

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

        return view('admin/panel/group_create', ['errors' => []]);
    }

    public function groupStore(): ResponseInterface
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        $r = $this->apiAdminPost('panel/groups/create', $this->request->getPost());
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            return redirect()->to(site_url('admin/panel/groups'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
        }
        $msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');

        return redirect()->to(site_url('admin/panel/groups/create'))->withInput()->with('error', $msg);
    }

    public function groupEdit(int $id): ResponseInterface|string
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        $errors = [];
        $row    = null;
        $r      = $this->apiAdminGet('panel/groups');
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            $d    = $r['json']['data'] ?? [];
            $list = is_array($d['rows'] ?? null) ? $d['rows'] : [];
            foreach ($list as $g) {
                if ((int) ($g['id'] ?? 0) === $id) {
                    $row = $g;
                    break;
                }
            }
            if ($row === null) {
                $errors[] = 'Grup tidak ditemukan.';
            }
        } else {
            $errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');
        }

        if ($row === null && $errors === []) {
            $errors[] = 'Grup tidak ditemukan.';
        }

        return view('admin/panel/group_edit', ['id' => $id, 'row' => $row, 'errors' => $errors]);
    }

    public function groupUpdate(int $id): ResponseInterface
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        $r = $this->apiAdminPost('panel/groups/update/' . $id, $this->request->getPost());
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            return redirect()->to(site_url('admin/panel/groups'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
        }
        $msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');

        return redirect()->to(site_url('admin/panel/groups/edit/' . $id))->withInput()->with('error', $msg);
    }

    public function groupDelete(int $id): ResponseInterface
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        $r = $this->apiAdminPost('panel/groups/delete/' . $id, $this->request->getPost());
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            return redirect()->to(site_url('admin/panel/groups'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
        }
        $msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');

        return redirect()->to(site_url('admin/panel/groups'))->with('error', $msg);
    }

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

        $errors       = [];
        $groups       = [];
        $pegawaiRows  = [];
        $r            = $this->apiAdminGet('panel/groups');
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            $d = $r['json']['data'] ?? [];
            $groups = is_array($d['rows'] ?? null) ? $d['rows'] : [];
        } else {
            $errors[] = $r['error'] ?? 'Gagal memuat grup';
        }

        $pegawaiRows = $this->fetchPegawaiRowsForSelect($errors);

        return view('admin/panel/user_create', [
            'groups'       => $groups,
            'pegawai_rows' => $pegawaiRows,
            'errors'       => $errors,
        ]);
    }

    public function userStore(): ResponseInterface
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        $r = $this->apiAdminPost('panel/users/create', $this->request->getPost());
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            return redirect()->to(site_url('admin/panel/users'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
        }
        $msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');

        return redirect()->to(site_url('admin/panel/users/create'))->withInput()->with('error', $msg);
    }

    public function userEdit(int $id): ResponseInterface|string
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        $errors = [];
        $user   = null;
        $r      = $this->apiAdminGet('panel/users/' . $id);
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            $d = $r['json']['data'] ?? null;
            $user = is_array($d) ? $d : null;
        } else {
            $errors[] = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal memuat pengguna') : 'Gagal memuat pengguna');
        }

        $groups = [];
        $gr     = $this->apiAdminGet('panel/groups');
        if ($gr['transport_ok'] && ApiClient::isSuccess($gr['json'])) {
            $gd = $gr['json']['data'] ?? [];
            $groups = is_array($gd['rows'] ?? null) ? $gd['rows'] : [];
        } else {
            $errors[] = $gr['error'] ?? 'Gagal memuat grup';
        }

        $pegawaiRows = $this->fetchPegawaiRowsForSelect($errors);

        return view('admin/panel/user_edit', [
            'id'           => $id,
            'user'         => $user,
            'groups'       => $groups,
            'pegawai_rows' => $pegawaiRows,
            'errors'       => $errors,
        ]);
    }

    public function userUpdate(int $id): ResponseInterface
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        $r = $this->apiAdminPost('panel/users/update/' . $id, $this->request->getPost());
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            return redirect()->to(site_url('admin/panel/users'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
        }
        $msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');

        return redirect()->to(site_url('admin/panel/users/edit/' . $id))->withInput()->with('error', $msg);
    }

    public function userReset(int $id): ResponseInterface|string
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        return view('admin/panel/user_reset', ['id' => $id]);
    }

    public function userResetPassword(int $id): ResponseInterface
    {
        if (($deny = $this->enforceAccess('panel')) !== null) {
            return $deny;
        }

        $r = $this->apiAdminPost('panel/users/reset_password/' . $id, $this->request->getPost());
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            return redirect()->to(site_url('admin/panel/users'))->with('message', (string) ($r['json']['pesan'] ?? 'OK'));
        }
        $msg = $r['error'] ?? (is_array($r['json']) ? (string) ($r['json']['pesan'] ?? 'Gagal') : 'Gagal');

        return redirect()->to(site_url('admin/panel/users/reset/' . $id))->withInput()->with('error', $msg);
    }

    /**
     * Gabungkan semua halaman `GET api/admin/pegawai` — satu request cuma mengembalikan `per_page` baris.
     *
     * @param list<string> $errors
     *
     * @return list<array<string, mixed>>
     */
    private function fetchPegawaiRowsForSelect(array &$errors): array
    {
        $byId    = [];
        $page    = 1;
        $maxPage = 80;

        while ($page <= $maxPage) {
            $pr = $this->apiAdminGet('pegawai', [
                'page'     => (string) $page,
                'per_page' => '500',
                'q'        => '',
            ]);
            if (! $pr['transport_ok'] || ! ApiClient::isSuccess($pr['json'])) {
                if ($page === 1) {
                    $errors[] = $pr['error'] ?? (is_array($pr['json']) ? (string) ($pr['json']['pesan'] ?? 'Gagal memuat daftar pegawai') : 'Gagal memuat daftar pegawai');
                }

                break;
            }

            $pd    = $pr['json']['data'] ?? [];
            $chunk = is_array($pd['rows'] ?? null) ? $pd['rows'] : [];
            foreach ($chunk as $row) {
                if (! is_array($row)) {
                    continue;
                }
                $pid = (int) ($row['id_pegawai'] ?? 0);
                if ($pid > 0) {
                    $byId[$pid] = $row;
                }
            }

            $totalPage = (int) ($pd['total_page'] ?? 1);
            if ($page >= $totalPage || $chunk === []) {
                break;
            }
            $page++;
        }

        $out = array_values($byId);
        usort($out, static function (array $a, array $b): int {
            return strcasecmp((string) ($a['nama_lengkap'] ?? ''), (string) ($b['nama_lengkap'] ?? ''));
        });

        return $out;
    }
}
