<?php
declare(strict_types=1);

$app = require __DIR__ . '/../config/app.php';
$sp  = require __DIR__ . '/../config/spotify_secrets.php';

define('SPOTIFY_CLIENT_ID',     (string)($sp['client_id'] ?? ''));
define('SPOTIFY_CLIENT_SECRET', (string)($sp['client_secret'] ?? ''));
define('SPOTIFY_REDIRECT_URI',  (string)($sp['redirect_uri'] ?? ''));

$basePath = rtrim((string)($app['base_path'] ?? ''), '/');
$GLOBALS['APP_CFG']   = $app;
$GLOBALS['BASE_PATH'] = $basePath;

function url_path(string $path): string {
  $base = rtrim((string)($GLOBALS['BASE_PATH'] ?? ''), '/');
  $path = '/' . ltrim($path, '/');
  return $base === '' ? $path : $base . $path;
}

function is_https(): bool {
  if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') return true;
  if (!empty($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443) return true;
  if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') return true;
  return false;
}

if (session_status() === PHP_SESSION_NONE) {
  session_set_cookie_params([
    'lifetime' => 0,
    'path'     => $basePath ? $basePath . '/' : '/',
    'secure'   => is_https(),
    'httponly' => true,
    'samesite' => 'Lax',
  ]);
  session_start();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/flash.php';
require_once __DIR__ . '/csrf.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/media.php';
