<?php
declare(strict_types=1);

namespace App\Modules\Settings;

use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Core\I18n\Translator;
use App\Core\Security\Csrf;
use App\Core\Support\Flash;
use App\Core\View\Template;
use App\Modules\Auth\AuthService;
use App\Modules\Printing\PrintApiKeyRepository;
use App\Modules\Printing\PrintJobRepository;

final class PrintSettingsController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly PrintApiKeyRepository $apiKeys,
        private readonly PrintJobRepository $printJobs
    ) {
    }

    public function index(Request $request): Response
    {
        $keys = $this->apiKeys->listAll();

        $statusFilter = trim((string) $request->input('print_status', ''));
        $validStatuses = ['pending', 'completed', 'failed'];
        $filterValue = in_array($statusFilter, $validStatuses, true) ? $statusFilter : null;
        $recentJobs = $this->printJobs->getRecentJobs(50, $filterValue);

        $html = $this->template->render('settings/printing', [
            'title' => 'Drukowanie',
            'activeMenu' => 'settings',
            'activeSettings' => 'printing',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'apiKeys' => $keys,
            'printJobs' => $recentJobs,
            'printStatusFilter' => $statusFilter,
            'errorMessage' => (string) Flash::get('settings_error', ''),
            'successMessage' => (string) Flash::get('settings_success', ''),
            'newApiKey' => (string) Flash::get('settings_new_api_key', ''),
        ], 'layouts/app');

        return Response::html($html);
    }

    public function createKey(Request $request): Response
    {
        if (!Csrf::validate((string) $request->input('_token', ''))) {
            Flash::set('settings_error', 'Nieprawidłowy token CSRF');
            return Response::redirect('/settings/printing');
        }

        $name = trim((string) $request->input('name', ''));
        if ($name === '') {
            Flash::set('settings_error', 'Nazwa klucza jest wymagana');
            return Response::redirect('/settings/printing');
        }

        $rawKey = bin2hex(random_bytes(32));
        $keyHash = hash('sha256', $rawKey);
        $keyPrefix = substr($rawKey, 0, 8);

        $this->apiKeys->create($name, $keyHash, $keyPrefix);

        Flash::set('settings_success', 'Klucz API utworzony. Skopiuj go teraz — nie będzie ponownie wyświetlony.');
        Flash::set('settings_new_api_key', $rawKey);

        return Response::redirect('/settings/printing');
    }

    public function deleteKey(Request $request): Response
    {
        if (!Csrf::validate((string) $request->input('_token', ''))) {
            Flash::set('settings_error', 'Nieprawidłowy token CSRF');
            return Response::redirect('/settings/printing');
        }

        $id = (int) $request->input('id', 0);
        if ($id <= 0) {
            Flash::set('settings_error', 'Nieprawidłowy ID klucza');
            return Response::redirect('/settings/printing');
        }

        $this->apiKeys->delete($id);
        Flash::set('settings_success', 'Klucz API został usunięty');

        return Response::redirect('/settings/printing');
    }
    public function deleteJob(Request $request): Response
    {
        if (!Csrf::validate((string) $request->input('_token', ''))) {
            Flash::set('settings_error', 'Nieprawidlowy token CSRF');
            return Response::redirect('/settings/printing');
        }

        $id = (int) $request->input('id', 0);
        if ($id <= 0) {
            Flash::set('settings_error', 'Nieprawidlowy ID wpisu kolejki');
            return Response::redirect('/settings/printing');
        }

        if ($this->printJobs->deleteById($id)) {
            Flash::set('settings_success', 'Wpis kolejki wydruku zostal usuniety');
        } else {
            Flash::set('settings_error', 'Nie znaleziono wpisu kolejki do usuniecia');
        }

        return Response::redirect('/settings/printing');
    }
}
