<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Services\BackupService;
use Throwable;

final class BackupController
{
    public function handleIndex(): void
    {
        Auth::requireLogin();
        require_permission('admin.backup.create');
        $service = new BackupService(DB::pdo());

        try {
            if (Request::isPost()) {
                Csrf::verify();
                $action = (string)Request::post('action', '');
                if ($action === 'create') {
                    $path = $service->create(trim((string)Request::post('note', '')));
                    Response::flash('success', 'تم إنشاء النسخة: ' . basename($path));
                    Response::redirect('/admin/backups');
                    return;
                }
                if ($action === 'download') {
                    $this->download($service, (string)Request::post('file', ''));
                    return;
                }
                if ($action === 'delete') {
                    $service->delete((string)Request::post('file', ''));
                    Response::flash('success', 'تم حذف النسخة');
                    Response::redirect('/admin/backups');
                    return;
                }
            }
        } catch (Throwable $e) {
            Response::flash('danger', 'خطأ: ' . $e->getMessage());
            Response::redirect('/admin/backups');
            return;
        }

        Response::view('pages/admin/backups', ['files' => $service->files()]);
    }

    public function handleRestore(): void
    {
        Auth::requireLogin();
        require_permission('admin.backup.restore');
        $service = new BackupService(DB::pdo());

        if (Request::isPost() && (string)Request::post('action', '') === 'restore') {
            try {
                Csrf::verify();
                [$ok, $msg] = $service->restore($_POST, $_FILES);
                Response::flash($ok ? 'success' : 'danger', $msg);
            } catch (Throwable $e) {
                Response::flash('danger', $e->getMessage());
            }
            Response::redirect('/admin/backups/restore');
            return;
        }

        Response::view('pages/admin/restore_backup', ['files' => array_column($service->files('*.sql'), 'name')]);
    }

    private function download(BackupService $service, string $file): void
    {
        $path = $service->safePath($file);
        header('Content-Type: application/sql');
        header('Content-Disposition: attachment; filename="' . basename($path) . '"');
        header('Content-Length: ' . filesize($path));
        readfile($path);
        exit;
    }
}
