<?php

/**
 * Direct API entry point. Use this when Laravel routing fails in subdirectories.
 * Request: .../api.php/health, .../api.php/voice/session, .../api.php/voice/process (POST)
 */

use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

// Get path: PATH_INFO (e.g. /health) or from REQUEST_URI after api.php
$path = $_SERVER['PATH_INFO'] ?? '';
if ($path === '' && isset($_SERVER['REQUEST_URI'])) {
    $uri = $_SERVER['REQUEST_URI'];
    if (($q = strpos($uri, '?')) !== false) {
        $uri = substr($uri, 0, $q);
    }
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    $prefix = str_replace('\\', '/', dirname($script)) . '/api.php';
    if (strpos($uri, $prefix) === 0) {
        $path = substr($uri, strlen($prefix)) ?: '/';
    }
}
$path = '/' . trim($path, '/');
$_SERVER['REQUEST_URI'] = '/api' . $path . (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');

if (file_exists($maintenance = __DIR__ . '/../storage/framework/maintenance.php')) {
    require $maintenance;
}

$autoload = __DIR__ . '/../vendor/autoload.php';
if (!file_exists($autoload)) {
    http_response_code(503);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Composer install required']);
    exit;
}
require $autoload;

$app = require_once __DIR__ . '/../bootstrap/app.php';
$app->handleRequest(Request::capture());
