<?php
/**
 * Main API Entry Point
 * Bus Check-in System API
 */

// Security: Disable error reporting in production
if (getenv('APP_ENV') !== 'development') {
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    error_reporting(0);
} else {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}

// Set timezone to match server timezone (UTC+1)
date_default_timezone_set('Europe/Paris'); // UTC+1 timezone

// Load environment variables from .env file
if (file_exists('.env')) {
    $envLines = file('.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($envLines as $line) {
        if (strpos($line, '=') !== false && strpos($line, '#') !== 0) {
            list($key, $value) = explode('=', $line, 2);
            putenv(trim($key) . '=' . trim($value));
        }
    }
}

// Include security middleware first
require_once 'middleware/InputValidator.php';
require_once 'middleware/SecurityLogger.php';

// Rate limiting check
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';
if (!InputValidator::checkRateLimit($clientIP, 100, 60)) { // 100 requests per minute
    SecurityLogger::logRateLimitExceeded($clientIP, 100, 60);
    http_response_code(429);
    echo json_encode([
        'success' => false,
        'message' => 'Too many requests. Please try again later.',
        'retry_after' => 60
    ]);
    exit();
}

// Security: Secure CORS configuration
$allowedOrigins = [
    'https://transub.dz',
    'https://www.transub.dz',
    'https://api.transub.dz',
    'http://localhost:3000', // For development
    'http://localhost:8080'  // For development
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins) || getenv('APP_ENV') === 'development') {
    header("Access-Control-Allow-Origin: $origin");
} else {
    header("Access-Control-Allow-Origin: https://transub.dz");
}

header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-API-Key");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 86400"); // 24 hours
header('Content-Type: application/json; charset=utf-8');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Security: Input sanitization for all requests
$_GET = array_map(function($value) {
    return is_array($value) ? array_map('htmlspecialchars', $value) : htmlspecialchars($value);
}, $_GET);

// Security: Check for suspicious patterns in request
foreach ($_GET as $key => $value) {
    if (InputValidator::checkSQLInjection($value)) {
        SecurityLogger::logSQLInjectionAttempt($value, 'GET parameter: ' . $key);
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }

    if (InputValidator::checkXSS($value)) {
        SecurityLogger::logXSSAttempt($value, 'GET parameter: ' . $key);
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid request parameters'
        ]);
        exit();
    }
}

// Include required files
require_once 'config/Database.php';
require_once 'models/Agent.php';
require_once 'models/Bus.php';
require_once 'models/Checkin.php';
require_once 'models/Operator.php';
require_once 'models/Ligne.php';
require_once 'models/TypeVehicule.php';
require_once 'models/Tarif.php';
require_once 'models/BonVers.php';
require_once 'middleware/Auth.php';

// Get request method and URI
$request_method = $_SERVER['REQUEST_METHOD'];
$request_uri = $_SERVER['REQUEST_URI'];

// Remove query parameters from URI
$request_uri = strtok($request_uri, '?');

// Remove base path (adjusted for your server)
$base_path = '/apipointagebus';
if (strpos($request_uri, $base_path) === 0) {
    $request_uri = substr($request_uri, strlen($base_path));
}

// Handle direct access to index.php (for cPanel deployment)
if (strpos($request_uri, '/index.php') !== false) {
    // Extract path after index.php
    $index_pos = strpos($request_uri, '/index.php');
    $after_index = substr($request_uri, $index_pos + 10); // 10 = length of '/index.php'
    if (!empty($after_index)) {
        $request_uri = $after_index;
    } else {
        $request_uri = '/';
    }
}

// Split URI into parts
$uri_parts = explode('/', trim($request_uri, '/'));
$endpoint = $uri_parts[0] ?? '';

// Route requests
try {
    switch ($endpoint) {
        case 'auth':
            require_once 'controllers/AuthController.php';
            $controller = new AuthController();
            handleAuthRoutes($controller, $uri_parts, $request_method);
            break;

        case 'buses':
            require_once 'controllers/BusController.php';
            $controller = new BusController();
            handleBusRoutes($controller, $uri_parts, $request_method);
            break;

        case 'checkins':
            require_once 'controllers/CheckinController.php';
            $controller = new CheckinController();
            handleCheckinRoutes($controller, $uri_parts, $request_method);
            break;

        case 'dashboard':
            require_once 'controllers/DashboardController_simple.php';
            $controller = new DashboardController();
            handleDashboardRoutes($controller, $uri_parts, $request_method);
            break;

        case 'operators':
            require_once 'controllers/OperatorController.php';
            $controller = new OperatorController();
            handleOperatorRoutes($controller, $uri_parts, $request_method);
            break;

        case 'lignes':
            require_once 'controllers/LigneController.php';
            $controller = new LigneController();
            handleLigneRoutes($controller, $uri_parts, $request_method);
            break;

        case 'versement':
            require_once 'controllers/VersementController.php';
            $controller = new VersementController();
            handleVersementRoutes($controller, $uri_parts, $request_method);
            break;

        case 'pointages-boumerdes':
            require_once 'controllers/PointagesBoumerdesController.php';
            $controller = new PointagesBoumerdesController();
            handlePointagesBoumerdesRoutes($controller, $uri_parts, $request_method);
            break;

        case 'health':
            // Health check endpoint
            echo json_encode([
                'status' => 'ok',
                'timestamp' => date('Y-m-d H:i:s'),
                'service' => 'Bus Check-in API'
            ]);
            break;

        default:
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'message' => 'Endpoint not found',
                'available_endpoints' => ['auth', 'buses', 'checkins', 'dashboard', 'versement', 'health']
            ]);
            break;
    }
} catch (Exception $e) {
    error_log("API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error',
        'error' => $e->getMessage()
    ]);
}

// Route handlers
function handleAuthRoutes($controller, $uri_parts, $method) {
    $action = $uri_parts[1] ?? 'login';

    switch ($action) {
        case 'login':
            if ($method === 'POST') {
                $controller->login();
            } else {
                methodNotAllowed();
            }
            break;

        case 'logout':
            if ($method === 'POST') {
                $controller->logout();
            } else {
                methodNotAllowed();
            }
            break;

        case 'verify':
            if ($method === 'GET') {
                $controller->verifyToken();
            } else {
                methodNotAllowed();
            }
            break;

        default:
            endpointNotFound();
            break;
    }
}

function handleBusRoutes($controller, $uri_parts, $method) {
    $action = $uri_parts[1] ?? 'index';

    switch ($action) {
        case 'index':
        case 'list':
            if ($method === 'GET') {
                $controller->getAll();
            } else {
                methodNotAllowed();
            }
            break;

        case 'scan':
            if ($method === 'POST') {
                $controller->scanQR();
            } else {
                methodNotAllowed();
            }
            break;

        default:
            // Check if it's an ID (numeric)
            if (is_numeric($action)) {
                if ($method === 'GET') {
                    $controller->getById($action);
                } elseif ($method === 'PUT') {
                    $controller->update($action);
                } elseif ($method === 'DELETE') {
                    $controller->delete($action);
                } else {
                    methodNotAllowed();
                }
            } else {
                endpointNotFound();
            }
            break;
    }
}

function handleCheckinRoutes($controller, $uri_parts, $method) {
    $action = $uri_parts[1] ?? 'index';

    switch ($action) {
        case 'index':
        case 'list':
            if ($method === 'GET') {
                $controller->getAll();
            } else {
                methodNotAllowed();
            }
            break;

        case 'create':
            if ($method === 'POST') {
                $controller->create();
            } else {
                methodNotAllowed();
            }
            break;

        default:
            // Check if it's an ID (numeric)
            if (is_numeric($action)) {
                if ($method === 'GET') {
                    $controller->getById($action);
                } elseif ($method === 'DELETE') {
                    $controller->delete($action);
                } else {
                    methodNotAllowed();
                }
            } else {
                endpointNotFound();
            }
            break;
    }
}

function handleDashboardRoutes($controller, $uri_parts, $method) {
    $action = $uri_parts[1] ?? 'summary';

    switch ($action) {
        case 'summary':
            if ($method === 'GET') {
                $controller->getSummary();
            } else {
                methodNotAllowed();
            }
            break;

        case 'daily':
            if ($method === 'GET') {
                $date = $_GET['date'] ?? date('Y-m-d');
                $controller->getDailyReport($date);
            } else {
                methodNotAllowed();
            }
            break;

        case 'absent':
            if ($method === 'GET') {
                $date = $_GET['date'] ?? date('Y-m-d');
                $controller->getAbsentBuses($date);
            } else {
                methodNotAllowed();
            }
            break;

        case 'alerts':
            if ($method === 'GET') {
                $controller->getOutOfZoneAlerts();
            } else {
                methodNotAllowed();
            }
            break;

        case 'stats':
            if ($method === 'GET') {
                $controller->getDashboardData();
            } else {
                methodNotAllowed();
            }
            break;

        case 'active-buses':
            if ($method === 'GET') {
                $controller->getActiveBuses();
            } else {
                methodNotAllowed();
            }
            break;

        case 'scanned-buses':
            if ($method === 'GET') {
                $controller->getScannedBuses();
            } else {
                methodNotAllowed();
            }
            break;

        case 'absent-buses':
            if ($method === 'GET') {
                $controller->getAbsentBuses();
            } else {
                methodNotAllowed();
            }
            break;

        default:
            endpointNotFound();
            break;
    }
}

function handleOperatorRoutes($controller, $uri_parts, $method) {
    $action = $uri_parts[1] ?? 'index';

    switch ($action) {
        case 'index':
        case 'list':
            if ($method === 'GET') {
                $controller->getAll();
            } elseif ($method === 'POST') {
                $controller->create();
            } else {
                methodNotAllowed();
            }
            break;

        default:
            // Check if it's an ID (numeric)
            if (is_numeric($action)) {
                if ($method === 'GET') {
                    $controller->getById($action);
                } elseif ($method === 'PUT') {
                    $controller->update($action);
                } elseif ($method === 'DELETE') {
                    $controller->delete($action);
                } else {
                    methodNotAllowed();
                }
            } else {
                endpointNotFound();
            }
            break;
    }
}

function handleLigneRoutes($controller, $uri_parts, $method) {
    $action = $uri_parts[1] ?? 'index';

    switch ($action) {
        case 'index':
        case 'list':
            if ($method === 'GET') {
                $controller->getAll();
            } elseif ($method === 'POST') {
                $controller->create();
            } else {
                methodNotAllowed();
            }
            break;

        default:
            // Check if it's an ID (numeric)
            if (is_numeric($action)) {
                if ($method === 'GET') {
                    $controller->getById($action);
                } elseif ($method === 'PUT') {
                    $controller->update($action);
                } elseif ($method === 'DELETE') {
                    $controller->delete($action);
                } else {
                    methodNotAllowed();
                }
            } else {
                endpointNotFound();
            }
            break;
    }
}

function handleVersementRoutes($controller, $uri_parts, $method) {
    $action = $uri_parts[1] ?? 'index';

    switch ($action) {
        case 'type-vehicules':
            if ($method === 'GET') {
                $controller->getTypeVehicules();
            } else {
                methodNotAllowed();
            }
            break;

        case 'operateurs':
            if ($method === 'GET') {
                $controller->getOperateurs();
            } else {
                methodNotAllowed();
            }
            break;

        case 'buses':
            if ($method === 'GET') {
                $controller->getBuses();
            } else {
                methodNotAllowed();
            }
            break;

        case 'tarif':
            if ($method === 'GET') {
                $controller->getTarif();
            } else {
                methodNotAllowed();
            }
            break;

        case 'check-periode':
            if ($method === 'GET') {
                $controller->checkPeriode();
            } else {
                methodNotAllowed();
            }
            break;

        case 'create':
            if ($method === 'POST') {
                $controller->createBonVers();
            } else {
                methodNotAllowed();
            }
            break;

        case 'print':
            if ($method === 'POST') {
                $controller->printBonVers();
            } else {
                methodNotAllowed();
            }
            break;

        default:
            endpointNotFound();
            break;
    }
}

function handlePointagesBoumerdesRoutes($controller, $uri_parts, $method) {
    $action = $uri_parts[1] ?? 'dashboard';

    switch ($action) {
        case 'dashboard':
            if ($method === 'GET') {
                $controller->getDashboardData();
            } else {
                methodNotAllowed();
            }
            break;

        default:
            endpointNotFound();
            break;
    }
}

function methodNotAllowed() {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Method not allowed'
    ]);
}

function endpointNotFound() {
    http_response_code(404);
    echo json_encode([
        'success' => false,
        'message' => 'Endpoint not found'
    ]);
}
?>
