<?php

require_once __DIR__ . '/app/Config.php';
require_once __DIR__ . '/app/Database.php';
require_once __DIR__ . '/app/Response.php';
require_once __DIR__ . '/app/Request.php';
require_once __DIR__ . '/app/MailService.php';
require_once __DIR__ . '/app/Auth.php';
require_once __DIR__ . '/app/Settings.php';
require_once __DIR__ . '/app/Profile.php';
require_once __DIR__ . '/app/Activity.php';
require_once __DIR__ . '/app/WorkflowManager.php';
require_once __DIR__ . '/app/ImageGenerator.php';
require_once __DIR__ . '/app/VideoGenerator.php';
require_once __DIR__ . '/app/ChatAI.php';
require_once __DIR__ . '/app/Migration.php';
require_once __DIR__ . '/app/Router.php';

use Peak\Config;
use Peak\Database;
use Peak\Response;
use Peak\Router;
use Peak\Settings;

Config::init();

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Allow-Credentials: true');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

$scriptDirName = dirname($_SERVER['SCRIPT_NAME'] ?? '/');
$uriPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$scriptBasename = basename($_SERVER['SCRIPT_NAME'] ?? 'api.php');

$uriPathRel = $uriPath;
if ($scriptDirName !== '/' && strpos($uriPathRel, $scriptDirName) === 0) {
    $uriPathRel = substr($uriPathRel, strlen($scriptDirName)) ?: '/';
}

if ($uriPathRel === '/' . $scriptBasename && !isset($_SERVER['PATH_INFO']) && !isset($_GET['route'])) {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'ok', 'app' => 'Peak Platform API']);
    exit;
}

if (PHP_SAPI === 'cli') {
    if (($argv[1] ?? '') === 'migrate') { \Peak\Migration::run(); exit; }
    if (($argv[1] ?? '') === 'seed')    { \Peak\Migration::seed(); exit; }
    echo "Usage: php api.php <migrate|seed>\n";
    exit;
}

if (PHP_SAPI !== 'cli') session_start();

$method = $_SERVER['REQUEST_METHOD'];
$uri    = $uriPathRel;

if (PHP_SAPI === 'cli-server' && $uri !== '/' && strpos($uri, '/api') !== 0) {
    $ext = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
    $statics = ['css','js','png','jpg','jpeg','gif','ico','svg','woff2','woff','ttf','eot','webp','avif','pdf','zip','json','mp4','webm'];
    if (in_array($ext, $statics)) return false;
}

$route = '';
if (!empty($_SERVER['PATH_INFO'])) {
    $route = $_SERVER['PATH_INFO'];
} elseif (strpos($uri, '/api/') === 0) {
    $route = substr($uri, 4);
} elseif (strpos($uri, '/api.php/') === 0) {
    $route = substr($uri, 9);
} elseif (isset($_GET['route'])) {
    $route = '/' . ltrim($_GET['route'], '/');
}
$route = '/' . trim($route, '/');
$parts = array_values(array_filter(explode('/', $route), function($p) { return $p !== ''; }));
$resource = $parts[0] ?? '';
$id       = $parts[1] ?? null;

if ($resource !== '') {
    Router::dispatch($method, $resource, $id);
    exit;
}

$publicPath = __DIR__;
$staticUri = $uri;
if ($staticUri === '/' || $staticUri === '') $staticUri = '/index.html';
$filePath = $publicPath . str_replace('/', DIRECTORY_SEPARATOR, $staticUri);
if (is_file($filePath) && $uriPathRel !== '/' . $scriptBasename) {
    $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    $mime = ['css' => 'text/css', 'js' => 'application/javascript', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'ico' => 'image/x-icon', 'svg' => 'image/svg+xml', 'html' => 'text/html', 'json' => 'application/json', 'mp4' => 'video/mp4', 'webm' => 'video/webm'];
    if (isset($mime[$ext])) header('Content-Type: ' . $mime[$ext]);
    if ($ext === 'html') {
        $html = file_get_contents($filePath);
        try {
            $allSettings = Settings::getAll();
            $script = '<script>window.__SETTINGS=' . json_encode($allSettings, JSON_UNESCAPED_UNICODE) . '</script>';
            $html = str_replace('</head>', $script . '</head>', $html);
        } catch (\Throwable) {}
        echo $html;
    } else {
        readfile($filePath);
    }
    exit;
}
http_response_code(404); echo '404 Not Found';
