<?php

declare(strict_types=1);

namespace Lab\Controllers;

use Lab\Flash;
use Lab\Helpers;
use Lab\License;
use Lab\View;

final class LicenseController
{
    public function __construct(
        private array $config,
        private License $license,
    ) {}

    public function showActivate(): void
    {
        if (! License::isKiosk()) {
            View::redirect('/');
        }
        View::render('activate', [
            'title' => 'Ενεργοποίηση',
            'deviceName' => $this->license->deviceName(),
            'deviceShort' => substr($this->license->deviceId(), 0, 8),
        ]);
    }

    public function submitActivate(): void
    {
        if (! License::isKiosk()) {
            View::redirect('/');
        }
        if (! Helpers::verifyCsrf($_POST['csrf_token'] ?? null)) {
            Flash::set('error', 'Η ενέργεια απορρίφθηκε.');
            View::redirect('/activate');
        }
        $result = $this->license->remote('/api/license/activate', [
            'key' => (string) ($_POST['key'] ?? ''),
            'device_id' => $this->license->deviceId(),
            'device_name' => $this->license->deviceName(),
        ]);
        if (! empty($result['ok'])) {
            try {
                $this->license->writeLocal($result, $this->license->deviceId());
            } catch (\Throwable $e) {
                Flash::set('error', $e->getMessage());
                View::redirect('/activate');
            }
            View::redirect('/');
        }
        Flash::set('error', (string) ($result['error'] ?? 'Η ενεργοποίηση απέτυχε.'));
        View::redirect('/activate');
    }

    public function apiActivate(): void
    {
        $data = Helpers::readJson();
        if ($data === []) {
            $data = $_POST;
        }
        $result = $this->license->activate(
            (string) ($data['key'] ?? ''),
            (string) ($data['device_id'] ?? ''),
            (string) ($data['device_name'] ?? ''),
        );
        Helpers::json($result, ! empty($result['ok']) ? 200 : 403);
    }

    public function apiCheck(): void
    {
        $data = Helpers::readJson();
        if ($data === []) {
            $data = $_POST;
        }
        $result = $this->license->check(
            (string) ($data['key'] ?? ''),
            (string) ($data['device_id'] ?? ''),
            (string) ($data['token'] ?? ''),
            (string) ($data['device_name'] ?? ''),
        );
        Helpers::json($result, ! empty($result['ok']) ? 200 : 403);
    }
}
