<?php
declare(strict_types=1);

require_once __DIR__ . '/storage.php';

function eaq_base_url(): string {
  // install/index.php fica em /<base>/install/index.php => base = dirname(dirname(SCRIPT_NAME))
  $scriptName = $_SERVER['SCRIPT_NAME'] ?? '/';
  $dir = dirname($scriptName);           // .../install or .../app
  $base = dirname($dir);                // .../<base>
  if ($base === '' || $base === DIRECTORY_SEPARATOR) return '';
  return $base;
}

function eaq_config_path(): string {
  return __DIR__ . '/../config/config.php';
}

function eaq_load_config(): array {
  $path = eaq_config_path();
  if (!file_exists($path)) return [];
  $cfg = require $path;
  return is_array($cfg) ? $cfg : [];
}

function eaq_installed_flag_path(): string {
  return __DIR__ . '/../config/installed.flag';
}

function eaq_is_installed(): bool {
  return file_exists(eaq_installed_flag_path());
}

function eaq_db_mode(array $cfg): string {
  return $cfg['db']['mode'] ?? 'mock';
}

function eaq_pdo(array $cfg): ?PDO {
  $mode = eaq_db_mode($cfg);
  if ($mode !== 'mysql') return null;
  $db = $cfg['db'] ?? [];
  $host = $db['host'] ?? '';
  $port = $db['port'] ?? '3306';
  $name = $db['database'] ?? '';
  $user = $db['username'] ?? '';
  $pass = $db['password'] ?? '';
  if ($host === '' || $name === '') return null;

  $dsn = "mysql:host={$host};port={$port};dbname={$name};charset=utf8mb4";
  $pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  ]);
  return $pdo;
}

function eaq_redirect(string $path): void {
  header('Location: ' . $path);
  exit;
}

$config = eaq_load_config();
$baseUrl = $config['base_url'] ?? eaq_base_url();

// Bloqueia acesso ao /app antes de instalar.
if (!eaq_is_installed()) {
  eaq_redirect($baseUrl . '/install/');
}

