<?php
/**
 * Fouad AI Photo Editor - API Router
 */

$configFile = dirname(__DIR__) . '/config.php';
if (!file_exists($configFile)) {
    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'التطبيق غير مثبت. شغّل install.php أولاً.']);
    exit;
}
require_once $configFile;
require_once dirname(__DIR__) . '/includes/Database.php';
require_once dirname(__DIR__) . '/includes/Auth.php';
require_once dirname(__DIR__) . '/includes/ZaiApi.php';

// CORS
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) header('Access-Control-Allow-Origin: ' . $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; }

// Parse URI
$route = $_GET['route'] ?? '';
$route = '/' . trim($route, '/');

$routes = [
    '/auth'     => 'auth.php',
    '/banner'   => 'banner.php',
    '/upload'   => 'upload.php',
    '/projects' => 'projects.php',
    '/project'  => 'project.php',
    '/generate' => 'generate.php',
    '/edit'     => 'edit.php',
    '/analyze'  => 'analyze.php',
];

$file = $routes[$route] ?? null;
if ($file && file_exists(__DIR__ . '/' . $file)) {
    require_once __DIR__ . '/' . $file;
} else {
    http_response_code(404);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'الرابط غير موجود']);
}