<?php
// Buffer all output from the start so stray whitespace in any included file
// (e.g. a trailing  newline) can be discarded before sending TwiML XML.
// Twilio rejects any leading space/newline before <?xml.
ob_start();
date_default_timezone_set('Africa/Lagos');
// Allow only specific domains (e.g., http://example.com) to access the API
$allowedOrigins = ['http://localhost', 'localhost'];

// Get the Origin of the request
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
// Check if the Origin is in the allowed list
// if (!in_array($origin, $allowedOrigins)) {

//     exit('Invalid Origin');
// }else{
//     header("Access-Control-Allow-Origin: $origin");
// }

// Always allow these headers (ensure these headers match what you expect to receive)
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Origin: *");
// Check the request method and the endpoint (based on URL)
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode('/', $uri);
$uri = '/'.end( $uri );

// Twilio webhook routes must return text/xml (or text/plain) — they set their own
// Content-Type. Only default to JSON for the API routes, otherwise LiteSpeed/LSPHP
// locks these responses to application/json and Twilio rejects the TwiML.
$nonJsonRoutes = ['/voice-outgoing', '/calls-twiml', '/calls-status', '/recording-status', '/voice'];
if (!in_array($uri, $nonJsonRoutes, true)) {
    header("Content-Type: application/json");
}
// echo $uri;
// Handle preflight requests (OPTIONS method)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    // Allowed methods
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Origin: *");
    // Allow credentials (if necessary, for authentication or cookies)
    // header("Access-Control-Allow-Credentials: true");

    // Exit for OPTIONS requests
    exit(0);
}

// Manual .env file parsing
$envFile = __DIR__ . '/.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue; // Skip comments
        
        list($name, $value) = explode('=', $line, 2);
        $name = trim($name);
        $value = trim($value);
        
        if (!array_key_exists($name, $_SERVER)) {
            putenv(sprintf('%s=%s', $name, $value));
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
    }
}


if ($method === 'GET' && $uri === '/test') {
    echo json_encode([
        "success" => true,
        "message" => "Welcome To IPS API V1"
    ]);
    exit();
}


// Proceed with your main application logic (e.g., routing)
require_once 'routes/public.php';
require_once 'routes/audit.php';
require_once 'routes/auth.php';  
require_once 'routes/users.php';
require_once 'routes/performance.php';
require_once 'routes/invoices.php';
require_once 'routes/conversation.php';
require_once 'routes/call-analytics.php';
// require_once 'routes/call_logs_routes.php';
require_once 'routes/follow-ups.php';
require_once 'routes/escalations.php';
require_once 'routes/twiliocall.php';
require_once 'routes/appointments.php';
require_once 'routes/communications.php';
require_once 'routes/settings.php';
require_once 'routes/closure-request.php';
require_once 'routes/team-management.php';
require_once 'routes/contacts.php';
require_once 'routes/contact-calls.php';
require_once 'routes/test_communications.php';
