<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

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

/**
 * Utilitas backup DB — file di <code>writable/admin_db_backup/</code>.
 */
class Util extends BaseAdminController
{
    public function backup(): ResponseInterface|string
    {
        if (($deny = $this->enforceAccess('utilitas')) !== null) {
            return $deny;
        }

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

        return view('admin/util/backup', [
            'payload' => is_array($data) ? $data : null,
            'errors'  => $errors,
        ]);
    }

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

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

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

    public function backupDelete(string $file): ResponseInterface
    {
        if (($deny = $this->enforceAccess('utilitas')) !== null) {
            return $deny;
        }

        $r = $this->apiAdminPost('backup/delete/' . rawurlencode($file), []);
        if ($r['transport_ok'] && ApiClient::isSuccess($r['json'])) {
            return redirect()->to(site_url('admin/util/backup'))->with('message', 'File dihapus');
        }
        $msg = $r['error'] ?? 'Gagal hapus';

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

    public function backupDownload(string $file): ResponseInterface
    {
        if (($deny = $this->enforceAccess('utilitas')) !== null) {
            return $deny;
        }

        $extra = new AdminExtraApiService();
        $path  = $extra->backupFilePath($file);
        if ($path === null) {
            return redirect()->to(site_url('admin/util/backup'))->with('error', 'File tidak ditemukan');
        }

        $dl = $this->response->download($path, null);
        if ($dl === null) {
            return redirect()->to(site_url('admin/util/backup'))->with('error', 'Gagal menyiapkan unduhan');
        }

        return $dl->setFileName(basename($path));
    }
}
