<?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\License\LicenseManager;
use App\Services\License\OfflineLicenseConsole;
use Throwable;

final class LicenseConsoleController
{
    public function index(): void
    {
        Auth::requireLogin();
        if (!license_admin_enabled()) {
            http_response_code(403);
            echo 'Developer license console is disabled.';
            return;
        }

        $config = require APP_PATH . '/config.php';
        $console = new OfflineLicenseConsole($config);
        $manager = new LicenseManager($config);

        Response::view('pages.admin.license_console', [
            'state' => license_state(),
            'requestDoc' => $console->generateRequestDocument(),
            'registry' => array_reverse($console->loadRegistry(), true),
            'consoleEnabled' => $console->isEnabled(),
            'privateKeyPath' => $console->privateKeyPath(),
            'publicKeyPath' => $console->publicKeyPath(),
            'registryPath' => $console->registryPath(),
            'template' => $manager->activationTemplate(),
        ]);
    }

    public function issue(): void
    {
        Auth::requireLogin();
        if (!license_admin_enabled()) {
            http_response_code(403);
            echo 'Developer license console is disabled.';
            return;
        }

        try {
            Csrf::verify();
            $config = require APP_PATH . '/config.php';
            $console = new OfflineLicenseConsole($config);
            $features = [
                'sales' => Request::post('feature_sales', '0') === '1',
                'inventory' => Request::post('feature_inventory', '0') === '1',
                'reports' => Request::post('feature_reports', '0') === '1',
                'pos' => Request::post('feature_pos', '0') === '1',
            ];
            $result = $console->issue([
                'action' => Request::post('action_type', 'issue'),
                'license_id' => Request::post('license_id', ''),
                'customer' => Request::post('customer', ''),
                'product' => Request::post('product', 'Store ERP'),
                'issued_at' => Request::post('issued_at', date(DATE_ATOM)),
                'expires_at' => Request::post('expires_at', date(DATE_ATOM, strtotime('+1 year'))),
                'fingerprint' => Request::post('fingerprint', ''),
                'status' => Request::post('status', 'active'),
                'reason' => Request::post('reason', ''),
                'notes' => Request::post('notes', ''),
                'features' => $features,
            ]);

            Response::flash('success', 'تم إنشاء ملف الترخيص: ' . $result['file_name']);
            Response::redirect('/system/license-admin?download=' . rawurlencode($result['file_name']));
        } catch (Throwable $e) {
            Response::flash('danger', $e->getMessage());
            Response::redirect('/system/license-admin');
        }
    }

    public function exportRequest(): void
    {
        Auth::requireLogin();
        $config = require APP_PATH . '/config.php';
        $console = new OfflineLicenseConsole($config);
        $result = $console->exportRequestFile();
        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $result['file_name'] . '"');
        readfile($result['file_path']);
    }

    public function download(): void
    {
        Auth::requireLogin();
        if (!license_admin_enabled()) {
            http_response_code(403);
            echo 'Developer license console is disabled.';
            return;
        }
        $config = require APP_PATH . '/config.php';
        $console = new OfflineLicenseConsole($config);
        $file = (string) ($_GET['file'] ?? '');
        $info = $console->readIssuedFile($file);
        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $info['name'] . '"');
        readfile($info['path']);
    }

    public function generateKeypair(): void
    {
        Auth::requireLogin();
        if (!license_admin_enabled()) {
            http_response_code(403);
            echo 'Developer license console is disabled.';
            return;
        }

        try {
            Csrf::verify();
            $config = require APP_PATH . '/config.php';
            $console = new OfflineLicenseConsole($config);
            $result = $console->generateKeypair(Request::post('overwrite', '0') === '1');
            Response::flash('success', $result['created']
                ? 'تم إنشاء زوج المفاتيح بنجاح.'
                : 'المفاتيح موجودة مسبقًا ولم يتم استبدالها.');
        } catch (Throwable $e) {
            Response::flash('danger', $e->getMessage());
        }

        Response::redirect('/system/license-admin');
    }
}
