<?php
declare(strict_types=1);

if (basename(__FILE__) !== 'install.php') {
  http_response_code(404);
  exit;
}

$root = __DIR__;
$codeRoot = $root . '/code';
$messages = [];

function installer_status(string $label, string $level, string $value, string $detail = ''): void {
  global $messages;
  if (!in_array($level, ['ok', 'warn', 'fail'], true)) $level = 'ok';
  $messages[] = [
    'label' => $label,
    'level' => $level,
    'value' => $value,
    'detail' => $detail,
  ];
}

function installer_path(string $path): string {
  global $root;
  $path = str_replace('\\', '/', $path);
  $rootPath = rtrim(str_replace('\\', '/', $root), '/') . '/';
  return str_starts_with($path, $rootPath) ? substr($path, strlen($rootPath)) : $path;
}

function installer_dir_writable(string $dir): bool {
  clearstatcache(true, $dir);
  if (!is_dir($dir)) return false;
  $probe = rtrim($dir, '/\\') . '/.install-write-test-' . getmypid() . '-' . str_replace('.', '', uniqid('', true));
  $ok = @file_put_contents($probe, "ok\n", LOCK_EX) !== false;
  if ($ok) @unlink($probe);
  return $ok;
}

function installer_mkdir(string $dir, string $label): void {
  if (!is_dir($dir)) @mkdir($dir, 0777, true);
  if (!is_dir($dir)) {
    installer_status($label, 'fail', 'Saknas', installer_path($dir) . ' - kunde inte skapa mappen');
    return;
  }
  @chmod($dir, 0777);
  clearstatcache(true, $dir);
  if (installer_dir_writable($dir)) {
    installer_status($label, 'ok', 'Ja', installer_path($dir));
    return;
  }
  installer_status($label, 'fail', 'Ej skrivbar', installer_path($dir) . ' - PHP/webservern kan inte skriva här');
}

function installer_has_failures(array $messages): bool {
  foreach ($messages as $message) {
    if (($message['level'] ?? '') === 'fail') return true;
  }
  return false;
}

function installer_app_url(): string {
  $dir = rtrim(str_replace('\\', '/', dirname((string)($_SERVER['SCRIPT_NAME'] ?? ''))), '/');
  return (($dir === '' || $dir === '.') ? '' : $dir) . '/';
}

function installer_render_html(array $messages): void {
  $ok = !installer_has_failures($messages);
  $appUrl = installer_app_url();
  header('Content-Type: text/html; charset=utf-8');
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  echo '<!doctype html><html lang="sv"><head><meta charset="utf-8">';
  echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
  echo '<title>Install</title><style>';
  echo 'body{margin:0;min-height:100vh;display:grid;place-items:center;background:#05030a;color:#f7f4ff;font:16px Arial,sans-serif}';
  echo 'main{width:min(680px,92vw);border:1px solid #7d29ff;padding:24px;background:#0d0718;box-shadow:0 20px 60px #000}';
  echo 'h1{margin:0 0 8px;font-size:24px}.lead{margin:0 0 18px;color:#cabee0;line-height:1.45}';
  echo '.checks{display:grid;gap:8px;margin:0 0 18px}.row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:12px;align-items:center;border:1px solid #2b1745;background:#080410;padding:10px 12px}';
  echo '.label{font-weight:700}.detail{grid-column:1/-1;color:#9d8eb6;font-size:13px;overflow-wrap:anywhere}.value{font-weight:800;text-transform:uppercase;letter-spacing:.04em}.ok .value{color:#51f09b}.warn .value{color:#ffd36b}.fail .value{color:#ff6b88}';
  echo '.actions{display:flex;gap:10px;flex-wrap:wrap}.btn{display:inline-flex;align-items:center;justify-content:center;min-height:42px;color:#fff;background:#6811d9;border:1px solid #a244ff;padding:0 16px;text-decoration:none;font-weight:800}.retry{background:#191020;border-color:#573075}';
  echo '</style></head><body><main>';
  echo '<h1>' . ($ok ? 'Installation klar' : 'Installation behöver kollas') . '</h1>';
  echo '<p class="lead">' . ($ok ? 'Det här gjordes innan sidan öppnas. Klicka vidare när allt ser rätt ut.' : 'Rätta de röda raderna och ladda om installern.') . '</p>';
  echo '<div class="checks">';
  foreach ($messages as $message) {
    $level = htmlspecialchars((string)($message['level'] ?? 'ok'), ENT_QUOTES, 'UTF-8');
    $label = htmlspecialchars((string)($message['label'] ?? ''), ENT_QUOTES, 'UTF-8');
    $value = htmlspecialchars((string)($message['value'] ?? ''), ENT_QUOTES, 'UTF-8');
    $detail = htmlspecialchars((string)($message['detail'] ?? ''), ENT_QUOTES, 'UTF-8');
    echo '<div class="row ' . $level . '"><div class="label">' . $label . '</div><div class="value">' . $value . '</div>';
    if ($detail !== '') echo '<div class="detail">' . $detail . '</div>';
    echo '</div>';
  }
  echo '</div><div class="actions">';
  if ($ok) echo '<a class="btn" href="' . htmlspecialchars($appUrl, ENT_QUOTES, 'UTF-8') . '">Gå vidare till sidan</a>';
  echo '<a class="btn retry" href="install.php">Ladda om installern</a>';
  echo '</div>';
  echo '</main></body></html>';
}

if (!is_dir($codeRoot)) {
  installer_status('Kodmapp finns', 'fail', 'Nej', 'code');
  if (PHP_SAPI === 'cli') {
    echo "Kodmapp finns: Nej (code)\n";
    exit(1);
  }
  installer_render_html($messages);
  exit;
}

installer_status('Kodmapp finns', 'ok', 'Ja', 'code');
installer_mkdir($codeRoot . '/.data', 'Data-mapp');
installer_mkdir($codeRoot . '/.manager-saves', 'Save-mapp');
installer_mkdir($codeRoot . '/.manager-saves/.meta', 'Save meta-mapp');
installer_mkdir($codeRoot . '/.manager-save-backups', 'Backup-mapp');
installer_mkdir($codeRoot . '/uploads/manager-chat', 'Chat uploads');
installer_mkdir($codeRoot . '/reports', 'Reports-mapp');

$stateFile = $codeRoot . '/.data/state.json';
$legacyStateFile = $codeRoot . '/.state.json';
if (!is_file($stateFile)) {
  if (is_file($legacyStateFile) && is_readable($legacyStateFile)) {
    @copy($legacyStateFile, $stateFile);
    @chmod($stateFile, 0666);
    $stateReady = is_file($stateFile) && is_readable($stateFile) && is_writable($stateFile);
    installer_status('State-fil', $stateReady ? 'ok' : 'fail', $stateReady ? 'Migrerad' : 'Nej', installer_path($stateFile));
  } else {
    $state = [
      'schemaVersion' => 2,
      'users' => [],
      'matches' => [],
      'managerSeasons' => [],
      'managerCurrentId' => null,
      'managerCurrentByUser' => [],
      'managerPlayerIdVersion' => 0,
      'managerCpuFormationVersion' => 0,
      'managerHumanSnapshotVersion' => 0,
      'managerYear' => 2026,
      'teamTrophies' => [],
      'managerLog' => [],
      'managerInvites' => [],
      'managerChats' => [],
      'managerPrivateChats' => [],
      'managerMarket' => [],
      'managerBrowseOffers' => [],
      'managerTransferOffers' => [],
      'managerTransferNotices' => [],
      'managerBrowseSold' => [],
    ];
    @file_put_contents($stateFile, json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL, LOCK_EX);
    @chmod($stateFile, 0666);
    $stateReady = is_file($stateFile) && is_readable($stateFile) && is_writable($stateFile);
    installer_status('State-fil', $stateReady ? 'ok' : 'fail', $stateReady ? 'Skapad' : 'Nej', installer_path($stateFile));
  }
} else {
  @chmod($stateFile, 0666);
  $stateReady = is_readable($stateFile) && is_writable($stateFile);
  installer_status('State-fil', $stateReady ? 'ok' : 'fail', $stateReady ? 'Finns' : 'Nej', installer_path($stateFile));
}

if (!defined('YSP_CODE_ROOT')) define('YSP_CODE_ROOT', $codeRoot);
require_once $codeRoot . '/.lib/db.php';
$sqliteAvailable = ysp_db_available();
installer_status('Finns SQLite', $sqliteAvailable ? 'ok' : 'warn', $sqliteAvailable ? 'Ja' : 'Nej', 'PDO sqlite');
$db = $sqliteAvailable ? ysp_db() : null;
installer_status('SQLite databas', $db ? 'ok' : 'warn', $db ? 'Klar' : 'Hoppas över', $db ? installer_path(ysp_db_path()) : 'Spelet kan använda JSON-fallback.');

if (PHP_SAPI === 'cli') {
  foreach ($messages as $message) {
    $line = (string)($message['label'] ?? '') . ': ' . (string)($message['value'] ?? '');
    if (($message['detail'] ?? '') !== '') $line .= ' (' . (string)$message['detail'] . ')';
    echo $line . PHP_EOL;
  }
  exit;
}

installer_render_html($messages);
