<?php
/**
 * Simple Router & Entry Point
 */

require_once __DIR__ . '/../app/bootstrap/init.php';

// Global Request Logging (non-sensitive)
error_log("Incoming Request: " . ($_SERVER['REQUEST_METHOD'] ?? 'GET') . " " . ($_SERVER['REQUEST_URI'] ?? '/'));

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$route = $_GET['route'] ?? str_replace('/api/', '', $uri);
$route = trim($route, '/');

error_log("Router: Resolved route '{$route}'");

// Route map: route => [allowed_method, module_file]
$routes = [
    'v1/auth/login'   => ['POST', 'auth/login.php'],
    'v1/auth/refresh' => ['POST', 'auth/refresh.php'],
    'v1/auth/logout'  => ['POST', 'auth/logout.php'],
    'v1/users'        => ['GET',  'users/index.php'],
    'v1/users/create' => ['POST', 'users/create.php'],
    'v1/users/update' => ['POST', 'users/update.php'],
    'v1/users/delete' => ['POST', 'users/delete.php'],
    'v1/companies'    => ['GET',  'companies/index.php'],
    'v1/companies/create' => ['POST', 'companies/create.php'],
    'v1/companies/update' => ['POST', 'companies/update.php'],
    'v1/companies/delete' => ['POST', 'companies/delete.php'],
    'v1/invoices'         => ['GET',  'invoices/index.php'],
    'v1/invoices/view'    => ['GET',  'invoices/view.php'],
    'v1/invoices/file'    => ['GET',  'invoices/file.php'],
    'v1/invoices/approve' => ['POST', 'invoices/approve.php'],
    'v1/invoices/upload'  => ['POST', 'invoices/upload.php'],
    'v1/invoices/download_xml' => ['GET', 'invoices/download_xml.php'],
    'v1/invoices/submit-jofotara' => ['POST', 'invoices/submit_jofotara.php'],
    'v1/companies/stats'   => ['GET', 'companies/stats.php'],
    'v1/companies/connect' => ['POST', 'companies/connect_jofotara.php'],
    'v1/dashboard/stats' => ['GET', 'dashboard/stats.php'],
    'v1/dashboard/recent-activity' => ['GET', 'dashboard/recent_activity.php'],
    'v1/tenants'         => ['GET', 'tenants/index.php'],
    'v1/tenants/create'  => ['POST', 'tenants/create.php'],
    'v1/tenants/update'  => ['POST', 'tenants/update.php'],
    'v1/tenants/stats'   => ['GET', 'tenants/stats.php'],
    'v1/subscriptions/plans'   => ['GET', 'subscriptions/plans.php'],
    'v1/subscriptions/current' => ['GET', 'subscriptions/current.php'],
    'v1/subscriptions/assign'  => ['POST', 'subscriptions/assign.php'],
    'v1/subscriptions/usage'   => ['GET', 'subscriptions/usage.php'],
    
    // Mobile Auth & Device Routes
    'v1/auth/mobile/request-otp'   => ['POST', 'auth/mobile_request_otp.php'],
    'v1/auth/mobile/verify-otp'    => ['POST', 'auth/mobile_verify_otp.php'],
    'v1/auth/mobile/register-device' => ['POST', 'auth/register_device.php'],
    
    // Batch Scanning Routes
    'v1/batches/create'       => ['POST', 'batches/create.php'],
    'v1/batches/upload-image' => ['POST', 'batches/upload_image.php'],
    'v1/batches/finalize'     => ['POST', 'batches/finalize.php'],
    'v1/batches/status'       => ['GET',  'batches/status.php'],
    
    // Payment System (CliQ-based)
    'v1/payments/create'           => ['POST', 'payments/create.php'],
    'v1/payments/verify-reference' => ['POST', 'payments/verify_reference.php'],
    'v1/payments/bot-webhook'      => ['POST', 'payments/bot_webhook.php'],
    'v1/payments/list'             => ['GET',  'payments/list.php'],
    'v1/payments/my-requests'      => ['GET',  'payments/my_requests.php'],
    'v1/payments/review'           => ['POST', 'payments/review.php'],
    'v1/payments/stats'            => ['GET',  'payments/stats.php'],

    // Voice Assistant Proxies
    'v1/voice/transcribe'        => ['POST', 'voice/transcribe.php'],
    'v1/voice/parse-intent'      => ['POST', 'voice/parse_intent.php'],
    'v1/voice/parse-intent-grok' => ['POST', 'voice/grok_intent.php'],
];

if (isset($routes[$route])) {
    [$allowedMethod, $moduleFile] = $routes[$route];
    
    // H1 Fix: Enforce HTTP Method
    if ($_SERVER['REQUEST_METHOD'] !== $allowedMethod) {
        header("Allow: {$allowedMethod}");
        json_error("Method Not Allowed. Use {$allowedMethod}.", 405);
    }
    
    $file = APP_PATH . '/modules_app/' . $moduleFile;
    if (file_exists($file)) {
        require_once $file;
    } else {
        json_error("Endpoint file missing: {$route}", 500);
    }
} else {
    if (str_starts_with($route, 'v1/')) {
        json_error("Not Found: {$route}", 404);
    } else {
        include __DIR__ . '/shell.php';
        exit;
    }
}
