<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\DatabaseBackupService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Throwable;

class BackupController extends Controller
{
    public function index(DatabaseBackupService $backups)
    {
        $connection = DB::connection();

        return view('admin.settings.backups', [
            'backups'  => $backups->list(),
            'database' => $connection->getDatabaseName(),
            'driver'   => $connection->getDriverName(),
            'host'     => config('database.connections.' . $connection->getName() . '.host'),
        ]);
    }

    public function store(DatabaseBackupService $backups)
    {
        try {
            $result = $backups->create();
        } catch (Throwable $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', 'بک‌آپ با موفقیت ساخته شد: ' . $result['filename']);
    }

    public function download(string $filename, DatabaseBackupService $backups)
    {
        try {
            $path = $backups->pathFor($filename);
        } catch (Throwable $e) {
            return back()->with('error', $e->getMessage());
        }

        return response()->download($path, basename($path), [
            'Content-Type' => 'application/zip',
        ]);
    }

    public function destroy(string $filename, DatabaseBackupService $backups)
    {
        try {
            $backups->delete($filename);
        } catch (Throwable $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', 'بک‌آپ حذف شد.');
    }
}
