<?php
// app/controllers/pages.php

declare(strict_types=1);

use ScMedia\Http\Response;
use ScMedia\Http\Router;
use ScMedia\Services\SettingsService;

final class PagesController extends BaseController {
  public static function register(Router $router, Container $container): void {
    $self = new self($container);
    $router->add('GET', '/', fn() => $self->index());
    $router->add('GET', '/settings', fn() => $self->settings());
    $router->add('GET', '/login', fn() => $self->login());
  }

  protected function index(): void {
    $i18n = $this->loadI18n(['common', 'index']);
    $this->renderView(__DIR__ . '/../views/pages/index.php', $i18n);
  }

  protected function settings(): void {
    $i18n = $this->loadI18n(['common', 'settings']);
    $config = $this->config();
    $debugToolsEnabled = (bool)($config['app']['debug_tools_enabled'] ?? false);
    $allowDbReset = (bool)($config['app']['allow_db_reset'] ?? false);
    $this->renderView(__DIR__ . '/../views/pages/settings.php', array_merge($i18n, [
      'debugToolsEnabled' => $debugToolsEnabled,
      'allowDbReset' => $allowDbReset,
    ]));
  }

  protected function login(): void {
    $i18n = $this->loadI18n(['login']);
    $this->renderView(__DIR__ . '/../views/pages/login.php', $i18n);
  }

  private function renderView(string $path, array $vars = []): void {
    if (!is_file($path)) {
      Response::json(['ok' => false, 'error' => 'View not found'], 404);
      return;
    }
    extract($vars, EXTR_SKIP);
    ob_start();
    require $path;
    $html = ob_get_clean();
    Response::html($html);
  }

  private function loadI18n(array $packages = ['common']): array {
    /** @var SettingsService $settings */
    $settings = $this->container->settings();
    $all = $settings->getAll();
    $lang = (string)($all['general']['language'] ?? 'en');
    $cookieLang = isset($_COOKIE['scmedia_lang']) ? (string)$_COOKIE['scmedia_lang'] : '';
    if (preg_match('/^[a-z]{2}$/', $cookieLang)) {
      $lang = $cookieLang;
    } else {
      $authUser = $this->services()['auth_user'] ?? null;
      if (is_array($authUser) && !empty($authUser['id']) && $this->db()) {
        $db = $this->db();
        $row = $db->fetchOne("SELECT ui_prefs_json FROM user_profiles WHERE user_id = :id", [
          ':id' => (int)$authUser['id'],
        ]) ?? [];
        $ui = json_decode((string)($row['ui_prefs_json'] ?? '{}'), true);
        $uiLang = is_array($ui) ? (string)($ui['language'] ?? '') : '';
        if (preg_match('/^[a-z]{2}$/', $uiLang)) {
          $lang = $uiLang;
        }
      }
    }

    $dict = $this->readI18nDict($lang);
    if ($lang !== 'en' && count($dict) === 0) {
      $lang = 'en';
      $dict = $this->readI18nDict($lang);
    }

    $dict = $this->filterI18nPackages($dict, $packages);
    $t = function(string $key, string $fallback = '') use ($dict): string {
      $val = $dict[$key] ?? '';
      return $val !== '' ? $val : ($fallback !== '' ? $fallback : $key);
    };

    return [
      'lang' => $lang,
      'dict' => $dict,
      't' => $t,
      'debugToolsEnabled' => (bool)($this->config()['app']['debug_tools_enabled'] ?? false),
    ];
  }

  private function readI18nDict(string $lang): array {
    $path = __DIR__ . '/../../public/assets/i18n/' . basename($lang) . '.json';
    if (!is_file($path)) return [];
    $raw = file_get_contents($path);
    if ($raw === false) return [];
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
  }

  private function i18nPackages(): array {
    return [
      'common' => [
        'prefixes' => ['common', 'nav', 'queue', 'job'],
        'keys' => ['auth.logout', 'actions.theme', 'settings.language'],
      ],
      'login' => [
        'prefixes' => ['auth'],
        'keys' => ['common.back', 'settings.language'],
      ],
      'account' => [
        'prefixes' => ['account', 'theme', 'settings.ui'],
        'keys' => ['settings.language'],
      ],
      'settings' => [
        'prefixes' => ['settings', 'rules', 'admin', 'filters'],
        'keys' => [],
      ],
      'index' => [
        'prefixes' => [
          'app',
          'actions',
          'types',
          'bulk',
          'grid',
          'status',
          'sources',
          'queue',
          'incoming',
          'media',
          'job',
          'theme',
          'filters',
          'watchdog',
          'scan',
          'table',
        ],
        'keys' => ['settings.language'],
      ],
    ];
  }

  private function filterI18nPackages(array $dict, array $packages): array {
    $map = $this->i18nPackages();
    $out = [];
    $wanted = [];
    foreach ($packages as $p) {
      if (isset($map[$p])) {
        $wanted[] = $map[$p];
      }
    }
    foreach ($wanted as $pkg) {
      foreach (($pkg['prefixes'] ?? []) as $prefix) {
        foreach ($dict as $k => $v) {
          if (str_starts_with($k, $prefix . '.')) {
            $out[$k] = $v;
          }
        }
      }
      foreach (($pkg['keys'] ?? []) as $key) {
        if (array_key_exists($key, $dict)) {
          $out[$key] = $dict[$key];
        }
      }
    }
    return $out;
  }
}
