<?php

declare(strict_types=1);

use Lab\Auth;
use Lab\Controllers\KioskController;
use Lab\Controllers\LicenseController;
use Lab\Controllers\StudioController;
use Lab\Database;
use Lab\License;
use Lab\OrderStore;
use Lab\Output;
use Lab\Photos;
use Lab\Products;
use Lab\Router;

try {
    $bootstrap = is_file(__DIR__ . '/bootstrap.php')
        ? __DIR__ . '/bootstrap.php'
        : __DIR__ . '/../bootstrap.php';
    $config = require $bootstrap;
    $GLOBALS['lab_config'] = $config;
    $pdo = Database::connection($config['db_path']);
    Database::seedProducts($pdo, $config);

    $auth = new Auth($config);
    $products = new Products($pdo);
    $photos = new Photos($config);
    $orders = new OrderStore($pdo, $config, $photos);
    $output = new Output($config, $orders, $products);
    $kiosk = new KioskController($config, $products, $photos, $orders, $output);
    $license = new License($config, $pdo);
    $licenseCtl = new LicenseController($config, $license);
    $studio = new StudioController($config, $auth, $products, $orders, $output, $license);
    $router = new Router();

    $router->get('/', fn () => $kiosk->attract());
    $router->get('/install', fn () => $kiosk->install());
    $router->get('/kiosk', fn () => $kiosk->kiosk());
    $router->get('/web', fn () => $kiosk->web());
    $router->get('/thanks', fn () => $kiosk->thanks());

    $router->get('/api/products', fn () => $kiosk->apiProducts());
    $router->get('/api/cart', fn () => $kiosk->apiCart());
    $router->post('/api/cart', fn () => $kiosk->apiCart());
    $router->post('/api/reset', fn () => $kiosk->apiReset());
    $router->post('/api/upload', fn () => $kiosk->apiUpload());
    $router->post('/api/compose', fn () => $kiosk->apiCompose());
    $router->post('/api/checkout', fn () => $kiosk->apiCheckout());
    $router->get('/api/drives', fn () => $kiosk->apiDrives());
    $router->post('/api/import-drive', fn () => $kiosk->apiImportDrive());
    $router->post('/api/exit', fn () => $kiosk->apiExit());
    $router->post('/api/printers', fn () => $kiosk->apiPrinters());
    $router->post('/api/print-now', fn () => $kiosk->apiPrintNow());
    $router->post('/api/finish-later', fn () => $kiosk->apiFinishLater());
    $router->post('/api/license/activate', fn () => $licenseCtl->apiActivate());
    $router->post('/api/license/check', fn () => $licenseCtl->apiCheck());

    $router->get('/activate', fn () => $licenseCtl->showActivate());
    $router->post('/activate', fn () => $licenseCtl->submitActivate());

    $router->get('/studio/login', fn () => $studio->showLogin());
    $router->post('/studio/login', fn () => $studio->login());
    $router->post('/studio/logout', fn () => $studio->logout());
    $router->get('/studio', fn () => $studio->index());
    $router->get('/studio/report', fn () => $studio->report());
    $router->get('/studio/products', fn () => $studio->products());
    $router->post('/studio/products', fn () => $studio->saveProducts());
    $router->get('/studio/settings', fn () => $studio->settings());
    $router->post('/studio/settings', fn () => $studio->saveSettings());
    $router->post('/studio/browse-folder', fn () => $studio->browseFolder());
    $router->post('/studio/add-printer', fn () => $studio->addPrinter());
    $router->post('/studio/connect-printer', fn () => $studio->connectPrinter());
    $router->get('/studio/licenses', fn () => $studio->licenses());
    $router->post('/studio/licenses', fn () => $studio->saveLicenses());

    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    $uri = \Lab\Helpers::requestPath();

    if (License::isKiosk() && ! License::isOpenPath($uri) && ! $license->localIsActive()) {
        if (str_starts_with($uri, '/api/')) {
            \Lab\Helpers::json(['ok' => false, 'error' => 'Χρειάζεται ενεργοποίηση.', 'code' => 'license'], 403);
        }
        \Lab\View::redirect('/activate');
    }

    if (preg_match('#^/api/thumb/([a-f0-9]+)$#', $uri, $m) && $method === 'GET') {
        $kiosk->thumb($m[1]);
        exit;
    }
    if (preg_match('#^/api/preview/([a-f0-9]+)$#', $uri, $m) && $method === 'GET') {
        $kiosk->preview($m[1]);
        exit;
    }
    if (preg_match('#^/api/original/([a-f0-9]+)$#', $uri, $m) && $method === 'GET') {
        $kiosk->original($m[1]);
        exit;
    }
    if (preg_match('#^/studio/orders/(\d+)$#', $uri, $m) && $method === 'GET') {
        $studio->show((int) $m[1]);
        exit;
    }
    if (preg_match('#^/studio/orders/(\d+)/status$#', $uri, $m) && $method === 'POST') {
        $studio->setStatus((int) $m[1]);
        exit;
    }
    if (preg_match('#^/studio/orders/(\d+)/export$#', $uri, $m) && $method === 'POST') {
        $studio->export((int) $m[1]);
        exit;
    }
    if (preg_match('#^/studio/orders/(\d+)/dnp$#', $uri, $m) && $method === 'POST') {
        $studio->printDnp((int) $m[1]);
        exit;
    }
    if (preg_match('#^/studio/orders/(\d+)/save$#', $uri, $m) && $method === 'POST') {
        $studio->saveFiles((int) $m[1]);
        exit;
    }
    if (preg_match('#^/studio/orders/(\d+)/zip$#', $uri, $m) && $method === 'GET') {
        $studio->zip((int) $m[1]);
        exit;
    }
    if (preg_match('#^/studio/orders/(\d+)/ticket$#', $uri, $m) && $method === 'GET') {
        $studio->ticket((int) $m[1]);
        exit;
    }
    if (preg_match('#^/studio/orders/(\d+)/photo/([^/]+)$#', $uri, $m) && $method === 'GET') {
        $studio->photo((int) $m[1], rawurldecode($m[2]));
        exit;
    }

    $router->dispatch($method, $uri);
} catch (\Throwable $e) {
    http_response_code(500);
    header('Content-Type: text/html; charset=UTF-8');
    $msg = htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
    echo '<!DOCTYPE html><html lang="el"><head><meta charset="utf-8"><title>Σφάλμα</title></head><body style="font-family:sans-serif;padding:2rem">';
    echo '<h1>Προσωρινό σφάλμα</h1><p>' . $msg . '</p></body></html>';
    error_log('Lab fatal: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
}
