<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\BackupDataTable;
use App\Http\Controllers\Controller;
use App\Repositories\BackupRepository;
use App\Services\BackupService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class BackupController extends Controller
{
    protected BackupService $service;

    protected BackupRepository $repo;

    public function __construct(BackupService $service, BackupRepository $repo)
    {
        $this->service = $service;
        $this->repo = $repo;
        $this->middleware('can:backup.manage');
    }

    public function index(BackupDataTable $dataTable)
    {
        return $dataTable->render('admin.backups');
    }

    public function data()
    {
        $dt = new BackupDataTable;

        return $dt->ajax();
    }

    public function store(Request $request)
    {
        $backup = $this->service->createAndDispatch();

        return response()->json(['success' => true, 'data' => $backup]);
    }

    public function download($id)
    {
        $backup = $this->repo->find((int) $id);
        if (! $backup) {
            return abort(404);
        }

        $path = 'backups/'.$backup->filename;
        if (! Storage::exists($path)) {
            return abort(404);
        }

        return response()->download(storage_path('app/'.$path));
    }

    public function destroy($id)
    {
        $backup = $this->repo->find((int) $id);
        if (! $backup) {
            return response()->json(['success' => false], 404);
        }

        $this->repo->update($backup->id, ['status' => 'deleted']);
        Storage::delete('backups/'.$backup->filename);

        return response()->json(['success' => true]);
    }
}
