<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Flash;
use App\Core\Request;
use App\Core\Response;
use App\Services\BackupService;

/** Pencadangan & pemulihan basis data. */
class BackupController extends Controller
{
    protected string $module = 'backup';

    public function index(): void
    {
        $this->view('pencadangan/index', [
            'judul' => 'Pencadangan Data',
            'subjudul' => 'Buat, unduh, dan pulihkan cadangan basis data',
            'files' => BackupService::listFiles(),
            'logs' => Database::i()->all(
                'SELECT b.*, u.name AS created_by_name FROM backup_logs b
                   LEFT JOIN users u ON u.id = b.created_by ORDER BY b.created_at DESC LIMIT 50'),
            'dir' => BackupService::dir(),
            'maksBerkas' => \App\Core\Settings::int('backup.simpan_maks_berkas', 10),
        ]);
    }

    public function create(): void
    {
        @set_time_limit(900);
        $res = BackupService::create('manual');
        if ($res['sukses']) {
            Flash::success('Pencadangan berhasil dibuat: ' . $res['file'] . ' (' . ukuranBerkas($res['ukuran'])
                . ', metode ' . $res['metode'] . ').');
        } else {
            Flash::error('Pencadangan gagal. Periksa izin tulis pada folder storage/backups.');
        }
        $this->redirect('/pencadangan');
    }

    public function download(): void
    {
        $name = basename((string)Request::get('berkas', ''));
        $path = BackupService::dir() . '/' . $name;
        if (!str_ends_with($name, '.sql') || !is_file($path)) Response::abort(404, 'Berkas pencadangan tidak ditemukan.');
        \App\Core\Audit::log('backup', 'export', null, null, 'Berkas pencadangan diunduh: ' . $name);
        Response::download($path, $name, 'application/sql');
    }

    public function destroy(): void
    {
        $name = basename((string)Request::post('berkas', ''));
        if (BackupService::delete($name)) Flash::success('Berkas pencadangan dihapus.');
        else Flash::error('Berkas pencadangan tidak ditemukan.');
        $this->redirect('/pencadangan');
    }

    public function restore(): void
    {
        if (!Auth::isSuper()) Response::abort(403, 'Hanya Super Administrator yang dapat memulihkan basis data.');
        $name = basename((string)Request::post('berkas', ''));
        $konfirmasi = (string)Request::post('konfirmasi', '');
        if ($konfirmasi !== 'PULIHKAN') {
            Flash::error('Ketik PULIHKAN pada kolom konfirmasi untuk melanjutkan pemulihan.');
            $this->redirect('/pencadangan');
        }
        @set_time_limit(1800);
        $res = BackupService::restore($name);
        if ($res['sukses']) Flash::success($res['pesan']);
        else Flash::error($res['pesan']);
        $this->redirect('/pencadangan');
    }
}
