<?php

namespace App\Http\Controllers\SaasAdmin;

use App\Http\Controllers\Controller;
use App\Models\BackupSetting;
use App\Services\BackupService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class BackupController extends Controller
{
    public function index(BackupService $backups): View
    {
        return view('saas-admin.backups.index', [
            'backups' => $backups->list(),
            'settings' => BackupSetting::current(),
        ]);
    }

    public function store(BackupService $backups): RedirectResponse
    {
        $filename = $backups->create();

        return back()->with('success', __('Backup created: :name', ['name' => $filename]));
    }

    public function download(BackupService $backups, string $filename): BinaryFileResponse
    {
        return response()->download($backups->path($filename));
    }

    public function destroy(BackupService $backups, string $filename): RedirectResponse
    {
        $backups->delete($filename);

        return back()->with('success', __('Backup deleted.'));
    }

    public function restore(Request $request, BackupService $backups): RedirectResponse
    {
        $request->validate([
            'backup_file' => ['required', 'file', 'max:512000'],
        ]);

        $backups->restore($request->file('backup_file'));

        return back()->with(
            'success',
            __('Backup restored. A safety copy of the previous database was saved automatically first.')
        );
    }

    public function updateSettings(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'frequency' => ['required', 'in:daily,weekly,monthly'],
        ]);

        BackupSetting::current()->update([
            'is_automated_enabled' => $request->boolean('is_automated_enabled'),
            'frequency' => $validated['frequency'],
        ]);

        return back()->with('success', __('Backup schedule updated.'));
    }
}
