<?php
ob_start(); // Start output buffering

/**
 * Versement API Entry Point - Dedicated module for versement functionality
 */

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// CORS Headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Security: Prevent Clickjacking
header('X-Frame-Options: DENY');
// Security: Prevent MIME type sniffing
header('X-Content-Type-Options: nosniff');
// Security: Enable XSS Filter in browser
header('X-XSS-Protection: 1; mode=block');
// Security: Content Security Policy
header("Content-Security-Policy: default-src 'none'; frame-ancestors 'none'");

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

// Set JSON response header
header('Content-Type: application/json');

// Load secure database configuration
$databaseConfig = require_once 'config/database_secure.php';

// Database configuration from secure file
define('DB_HOST', $databaseConfig['DB_HOST']);
define('DB_NAME', $databaseConfig['DB_NAME']);
define('DB_USER', $databaseConfig['DB_USER']);
define('DB_PASS', $databaseConfig['DB_PASS']);

// Connect to database
try {
    $db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed: ' . $e->getMessage()]);
    exit;
}

// Load all models and controllers
require_once 'models/TypeVehicule.php';
require_once 'models/Tarif.php';
require_once 'models/BonVers.php';
require_once 'models/Agent.php';
require_once 'controllers/VersementController.php';
require_once 'controllers/AuthController.php';
require_once 'controllers/PointagesController.php';

// === AJOUT VB - NE PAS TOUCHER AUX LIGNES CI-DESSUS ===
require_once 'controllers/VersementControllerVB.php';
// === FIN AJOUT VB ===

// === AJOUT RAPPORT DATE VERS - NE PAS TOUCHER ===
require_once 'controllers/VersementController2.php';
// === FIN AJOUT RAPPORT ===

// Handle pointages routes
function handlePointagesRoutes() {
    global $db;
    $controller = new PointagesController($db);
    $action = $_REQUEST['action'] ?? null;
    
    if ($action) {
        switch ($action) {
            case 'getDashboardData':
                $controller->getDashboardData();
                break;
            case 'getDetails':
                $controller->getDetails();
                break;
            default:
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Invalid pointages action']);
                break;
        }
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'No action specified for pointages']);
    }
}

// Handle auth routes
function handleAuthRoutes() {
    global $db;
    $controller = new AuthController($db);

    $action = $_REQUEST['action'] ?? null;
    
    if ($action) {
        switch ($action) {
            case 'login':
                $controller->login();
                break;
            default:
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Invalid auth action']);
                break;
        }
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'No action specified for auth']);
    }
}

// Security: Verify token for protected routes
function verifyToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? null;

    // Robust check for Authorization header (some servers strip it or rename it)
    if (!$authHeader) {
        if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
            $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
        } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
            $authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
        } elseif (isset($_REQUEST['token'])) {
            // Fallback to query parameter or POST data
            $authHeader = 'Bearer ' . $_REQUEST['token'];
        }
    }

    if (!$authHeader || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Unauthorized: Missing or invalid token format']);
        exit;
    }

    $token = $matches[1];
    
    // In a real production app, you would validate the token against a database or JWT secret.
    // For now, we check if it's a valid base64 string as generated by AuthController.
    // We also verify that it decodes to something containing a colon (our username:time format).
    $decoded = base64_decode($token, true);
    if ($decoded === false || strpos($decoded, ':') === false) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Unauthorized: Invalid token content']);
        exit;
    }
    
    return true;
}

// === AJOUT VB - NE PAS TOUCHER AUX LIGNES CI-DESSUS ===
// Handle VB API routes (no token required)
function handleVersementVBRoutes() {
    global $db;
    $controller = new VersementControllerVB($db);
    $action = $_REQUEST['action'] ?? null;

    if ($action) {
        switch ($action) {
            case 'getBonsVersByDateRange':
                $controller->getBonsVersByDateRange();
                break;
            default:
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Invalid VB action']);
                break;
        }
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'No action specified for VB']);
    }
}
// === FIN AJOUT VB ===

// Handle versement routes
function handleVersementRoutes() {
    global $db;
    
    // Security: Verify token for all versement routes
    verifyToken();

    $controller = new VersementController($db);
    $action = $_REQUEST['action'] ?? null;
    
    if ($action) {
        switch ($action) {
            case 'getTypeVehicules':
                $controller->getTypeVehicules();
                break;
            case 'getOperateurs':
                $controller->getOperateurs();
                break;
            case 'getBuses':
                $controller->getBuses();
                break;
            case 'getTarif':
                $controller->getTarif();
                break;
            case 'checkPeriode':
                $controller->checkPeriode();
                break;
            case 'createBonVers':
                $controller->createBonVers();
                break;
            case 'saveVersement': // Added for Android compatibility
                $controller->createBonVers();
                break;
            case 'printBonVers':
                $controller->printBonVers();
                break;
            case 'getRapportVersement':
                $controller->getRapportVersement();
                break;
            default:
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Invalid action']);
                break;
        }
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'No action specified for versement']);
    }
}

// Handle API requests
$route = $_REQUEST['route'] ?? null;

if ($route) {
    switch ($route) {
        case 'versement':
            handleVersementRoutes();
            break;
        case 'versement2':
            handleVersement2Routes();
            break;
        case 'auth':
            handleAuthRoutes();
            break;
        case 'pointages':
            handlePointagesRoutes();
            break;
        // === AJOUT VB - NE PAS TOUCHER AUX LIGNES CI-DESSUS ===
        case 'versementVB':
            handleVersementVBRoutes();
            break;
        // === FIN AJOUT VB ===
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid route']);
            break;
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No route specified']);
}

// === NOUVELLE ROUTE POUR RAPPORT DATE VERS ===
function handleVersement2Routes() {
    global $db;
    
    // Pas de vérification de token pour ce controller (ou vérifier si nécessaire)
    $controller = new VersementController2($db);
    $action = $_REQUEST['action'] ?? null;
    
    if ($action) {
        switch ($action) {
            case 'getRapportVersement':
                $controller->getRapportVersement();
                break;
            default:
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Invalid action']);
                break;
        }
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'No action specified for versement2']);
    }
}
// === FIN NOUVELLE ROUTE ===

// End output buffering and check for unexpected output
$output = ob_get_clean(); // Get all buffered output and clean the buffer

// If there's any output that's not a valid JSON, log it
if (!empty($output) && json_decode($output) === null && strpos($output, '{') === false) {
    file_put_contents('php_error_log.txt', date('Y-m-d H:i:s') . " - Unexpected Output:\n" . $output . "\n", FILE_APPEND);
} else if (!empty($output)) {
    // If it's valid JSON but still unexpected, log it too
    file_put_contents('php_response_log.txt', date('Y-m-d H:i:s') . " - Full Response:\n" . $output . "\n", FILE_APPEND);
    echo $output; // Output the JSON if it's valid
}
?>