<?php
declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use Dotenv\Dotenv;
use App\Core\Router;
use App\Core\Response;
use App\Config\Database;

// 0. Global Exception & Error Handlers
set_exception_handler(function ($e) {
    Response::error("Server Error: " . $e->getMessage(), [], 500);
});

set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) return;
    throw new \ErrorException($message, 0, $severity, $file, $line);
});

// 1. Load Environment Variables
try {
    $dotenv = Dotenv::createImmutable(__DIR__);
    $dotenv->load();
} catch (\Exception $e) {
    // If .env is missing, we still want to fly but we might hit DB issues later
}

// 2. Load Config (CORS, Constants)
require_once __DIR__ . '/config/app.php';

// 3. Initialize Router
$router = new Router();
$router->get('/', function () {
    Response::success(['app' => 'BillFlow Pro API', 'version' => '1.0.0'], "Welcome to the BillFlow Pro REST API");
});

// 4. Register Health Check (Special Case)
if (strpos($_SERVER['REQUEST_URI'], '/health') !== false) {
    try {
        Database::getInstance()->query("SELECT 1");
        Response::success(['status' => 'UP', 'database' => 'CONNECTED'], "Internal API Health Check");
    } catch (\Exception $e) {
        Response::error("API Health Failed", ['db' => $e->getMessage()], 500);
    }
}

// 5. Load Domain Routes
require_once __DIR__ . '/routes/auth.php';
require_once __DIR__ . '/routes/customers.php';
require_once __DIR__ . '/routes/vendors.php';
require_once __DIR__ . '/routes/categories.php';
require_once __DIR__ . '/routes/units.php';
require_once __DIR__ . '/routes/settings.php';
require_once __DIR__ . '/routes/audit.php';
require_once __DIR__ . '/routes/inventory.php';
require_once __DIR__ . '/routes/invoices.php';
require_once __DIR__ . '/routes/expenses.php';
require_once __DIR__ . '/routes/payments.php';
require_once __DIR__ . '/routes/credit_notes.php';
require_once __DIR__ . '/routes/debit_notes.php';
require_once __DIR__ . '/routes/dashboard.php';
require_once __DIR__ . '/routes/reports.php';
require_once __DIR__ . '/routes/gst.php';
require_once __DIR__ . '/routes/system.php';
require_once __DIR__ . '/routes/search.php';
require_once __DIR__ . '/routes/currencies.php';
require_once __DIR__ . '/routes/tax_rates.php';

// CSP and Security Headers
header("Content-Security-Policy: default-src 'self' " . APP_URL . " " . FRONTEND_URL . "; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: " . APP_URL . " " . FRONTEND_URL . "; connect-src 'self' " . APP_URL . " " . FRONTEND_URL . ";");
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: strict-origin-when-cross-origin");

if (php_sapi_name() !== 'cli') {
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    $uri = $_SERVER['REQUEST_URI'] ?? '/';
    $router->resolve($method, $uri);
}
