<?php

namespace App\Modules\Pilkades\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Services\DatabaseBackupService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class BackupController extends Controller
{
    public function __construct(protected DatabaseBackupService $backupService) {}

    public function index(): View
    {
        $backups = $this->backupService->listBackups();

        return view('pilkades::super-admin.backup.index', compact('backups'));
    }

    public function store(): RedirectResponse
    {
        $this->backupService->createBackup();

        return back()->with('success', 'Backup database berhasil dibuat.');
    }

    public function download(string $filename): Response
    {
        $path = $this->backupService->backupDirectory().DIRECTORY_SEPARATOR.basename($filename);

        abort_unless(is_file($path), 404);

        return response()->download($path);
    }
}
