<?php
/**
 * API HSE Transub - Point d'entrée principal
 * 
 * Ce fichier reçoit les requêtes HTTP et les routing vers les endpoints appropriés
 * Connexion aux bases de données via localhost (pas de port 3306)
 */

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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key');

// Gérer les requêtes OPTIONS (preflight CORS)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Charger la configuration
$config = require __DIR__ . '/config.php';

// Obtenir la méthode HTTP et les données
$method = $_SERVER['REQUEST_METHOD'];
$requestUri = $_SERVER['REQUEST_URI'];
$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
$headers = getallheaders();

// Parser l'URI pour obtenir l'endpoint
$path = parse_url($requestUri, PHP_URL_PATH);
$path = str_replace('/apihse/api.php', '', $path);
$path = trim($path, '/');

// Vérifier la clé API
$apiKey = $headers['X-API-Key'] ?? $input['api_key'] ?? $_GET['api_key'] ?? '';
if ($apiKey !== $config['api_key']) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized', 'message' => 'Clé API invalide']);
    exit;
}

// Database helper
function getDb($dbName) {
    global $config;
    if (!isset($config['databases'][$dbName])) {
        return null;
    }
    $db = $config['databases'][$dbName];
    try {
        $pdo = new PDO(
            "mysql:host={$db['host']};dbname={$db['name']};charset={$db['charset']}",
            $db['username'],
            $db['password'],
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
        return $pdo;
    } catch (PDOException $e) {
        // Log error for debugging
        error_log("Database connection failed for {$dbName}: " . $e->getMessage());
        return null;
    }
}

// Router les requêtes
try {
    $response = routeRequest($method, $path, $input);
    echo json_encode($response);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'error' => 'Server error: ' . $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
}

function routeRequest($method, $path, $input) {
    $parts = explode('/', $path);
    $endpoint = $parts[0] ?? '';
    $id = $parts[1] ?? null;
    
    switch ($endpoint) {
        // Authentification
        case 'auth':
            return handleAuth($method, $parts[1] ?? '', $input);
            
        // Incidents
        case 'incidents':
            return handleIncidents($method, $id, $input);
            
        // Inspections
        case 'inspections':
            return handleInspections($method, $id, $input);
            
        // Risques
        case 'risques':
            return handleRisques($method, $id, $input);
            
        // Actions correctives
        case 'actions':
            return handleActions($method, $id, $input);
            
        // Équipements
        case 'equipements':
            return handleEquipements($method, $id, $input);
            
        // Formations
        case 'formations':
            return handleFormations($method, $id, $input);
            
        // Sites (GGR)
        case 'sites':
            return handleSites($method, $id, $input);
            
        // Bus (GestionParc)
        case 'bus':
            return handleBus($method, $id, $input);
            
        // Salariés (GRH)
        case 'salaries':
            return handleSalaries($method, $id, $input);
            
        // Transport - Driver Safety
        case 'driver-safety':
            return handleDriverSafety($method, $id, $input);
            
        // Transport - Bus Checklists
        case 'bus-checklists':
            return handleBusChecklists($method, $id, $input);
            
        // Transport - Accidents Bus
        case 'accidents-bus':
            return handleAccidentsBus($method, $id, $input);
            
        // Transport - Incidents Voyageurs
        case 'incidents-voyageurs':
            return handleIncidentsVoyageurs($method, $id, $input);
            
        // Transport - Crowd Safety
        case 'crowd-safety':
            return handleCrowdSafety($method, $id, $input);
            
        // Transport - Inspection Quais
        case 'inspection-quais':
            return handleInspectionQuais($method, $id, $input);
            
        // Transport - Fatigue Conducteur
        case 'fatigue-conducteur':
            return handleFatigueConducteur($method, $id, $input);
            
        // Transport - Événements Majeurs
        case 'evenements-majeurs':
            return handleEvenementsMajeurs($method, $id, $input);
            
        // Transport - Bus Anomalies
        case 'bus-anomalies':
            return handleBusAnomalies($method, $id, $input);
            
        // Health check
        case 'health':
            return ['success' => true, 'message' => 'API HSE Transub is running'];
            
        default:
            return ['success' => false, 'error' => 'Endpoint not found', 'available_endpoints' => [
                'auth', 'incidents', 'inspections', 'risques', 'actions', 
                'equipements', 'formations', 'sites', 'bus', 'salaries',
                'driver-safety', 'bus-checklists', 'accidents-bus', 
                'incidents-voyageurs', 'crowd-safety', 'inspection-quais',
                'fatigue-conducteur', 'evenements-majeurs', 'bus-anomalies'
            ]];
    }
}

// ============================================
// HANDLERS - Incidents
// ============================================
function handleIncidents($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM incidents WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Incident not found'];
            }
            $page = $input['page'] ?? 1;
            $limit = $input['limit'] ?? 50;
            $offset = ($page - 1) * $limit;
            
            $stmt = $db->query("SELECT * FROM incidents ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
            $data = $stmt->fetchAll();
            
            $countStmt = $db->query("SELECT COUNT(*) as total FROM incidents");
            $total = $countStmt->fetch()['total'];
            
            return ['success' => true, 'data' => $data, 'pagination' => [
                'page' => $page, 'limit' => $limit, 'total' => $total, 'pages' => ceil($total / $limit)
            ]];
            
        case 'POST':
            $fields = array_keys($input);
            $values = array_values($input);
            $sql = "INSERT INTO incidents (" . implode(', ', $fields) . ") VALUES (:" . implode(', :', $fields) . ")";
            $stmt = $db->prepare($sql);
            $stmt->execute($input);
            return ['success' => true, 'message' => 'Incident créé', 'id' => $db->lastInsertId()];
            
        case 'PUT':
            if (!$id) return ['success' => false, 'error' => 'ID required'];
            $sets = [];
            foreach (array_keys($input) as $key) {
                $sets[] = "{$key} = :{$key}";
            }
            $sql = "UPDATE incidents SET " . implode(', ', $sets) . " WHERE id = :id";
            $input['id'] = $id;
            $stmt = $db->prepare($sql);
            $stmt->execute($input);
            return ['success' => true, 'message' => 'Incident mis à jour'];
            
        case 'DELETE':
            if (!$id) return ['success' => false, 'error' => 'ID required'];
            $stmt = $db->prepare("DELETE FROM incidents WHERE id = ?");
            $stmt->execute([$id]);
            return ['success' => true, 'message' => 'Incident supprimé'];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// HANDLERS - Inspections
// ============================================
function handleInspections($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM inspections WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Inspection not found'];
            }
            $stmt = $db->query("SELECT * FROM inspections ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        case 'POST':
            $stmt = $db->prepare("INSERT INTO inspections (titre, description, type, site_id, statut, date_prevue, date_realisee, inspecteur_id, resultat, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['titre'] ?? '',
                $input['description'] ?? '',
                $input['type'] ?? 'routine',
                $input['site_id'] ?? null,
                $input['statut'] ?? 'planifiee',
                $input['date_prevue'] ?? null,
                $input['date_realisee'] ?? null,
                $input['inspecteur_id'] ?? null,
                $input['resultat'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Inspection créée', 'id' => $db->lastInsertId()];
            
        case 'PUT':
            if (!$id) return ['success' => false, 'error' => 'ID required'];
            $sets = [];
            foreach (array_keys($input) as $key) {
                $sets[] = "{$key} = :{$key}";
            }
            $sql = "UPDATE inspections SET " . implode(', ', $sets) . " WHERE id = :id";
            $input['id'] = $id;
            $stmt = $db->prepare($sql);
            $stmt->execute($input);
            return ['success' => true, 'message' => 'Inspection mise à jour'];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// HANDLERS - Risques
// ============================================
function handleRisques($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM risques WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Risque not found'];
            }
            $stmt = $db->query("SELECT * FROM risques ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        case 'POST':
            $stmt = $db->prepare("INSERT INTO risques (categorie, description, probabilite, gravite, niveau_risque, localisation, cause, consequence, mesure_prevention, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['categorie'] ?? '',
                $input['description'] ?? '',
                $input['probabilite'] ?? 1,
                $input['gravite'] ?? 1,
                $input['niveau_risque'] ?? 'faible',
                $input['localisation'] ?? '',
                $input['cause'] ?? '',
                $input['consequence'] ?? '',
                $input['mesure_prevention'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Risque créé', 'id' => $db->lastInsertId()];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// HANDLERS - Actions Correctives
// ============================================
function handleActions($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM actions_correctives WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Action not found'];
            }
            $stmt = $db->query("SELECT * FROM actions_correctives ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        case 'POST':
            $stmt = $db->prepare("INSERT INTO actions_correctives (incident_id, titre, description, responsable_id, date_limite, priorite, statut, created_at) VALUES (?, ?, ?, ?, ?, ?, 'en_cours', NOW())");
            $stmt->execute([
                $input['incident_id'] ?? null,
                $input['titre'] ?? '',
                $input['description'] ?? '',
                $input['responsable_id'] ?? null,
                $input['date_limite'] ?? null,
                $input['priorite'] ?? 'moyenne'
            ]);
            return ['success' => true, 'message' => 'Action créée', 'id' => $db->lastInsertId()];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// HANDLERS - Équipements
// ============================================
function handleEquipements($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM equipements_securite WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Équipement not found'];
            }
            $stmt = $db->query("SELECT * FROM equipements_securite ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        case 'POST':
            $stmt = $db->prepare("INSERT INTO equipements_securite (nom, type, reference, site_id, quantite, etat, date_achat, date_expiration, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['nom'] ?? '',
                $input['type'] ?? '',
                $input['reference'] ?? '',
                $input['site_id'] ?? null,
                $input['quantite'] ?? 0,
                $input['etat'] ?? 'bon',
                $input['date_achat'] ?? null,
                $input['date_expiration'] ?? null
            ]);
            return ['success' => true, 'message' => 'Équipement créé', 'id' => $db->lastInsertId()];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// HANDLERS - Formations
// ============================================
function handleFormations($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM formations WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Formation not found'];
            }
            $stmt = $db->query("SELECT * FROM formations ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        case 'POST':
            $stmt = $db->prepare("INSERT INTO formations (titre, description, type, duree, date_prevue, lieu, formateur, statut, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'planifiee', NOW())");
            $stmt->execute([
                $input['titre'] ?? '',
                $input['description'] ?? '',
                $input['type'] ?? '',
                $input['duree'] ?? 0,
                $input['date_prevue'] ?? null,
                $input['lieu'] ?? '',
                $input['formateur'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Formation créée', 'id' => $db->lastInsertId()];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// Sites (GGR) - Table: Sites, Primary Key: SiteID, Column: Nom_Site
function handleSites($method, $id, $input) {
    $db = getDb('ggr');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed for GGR'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM `Sites` WHERE SiteID = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Site not found'];
            }
            $stmt = $db->query("SELECT * FROM `Sites` ORDER BY Nom_Site");
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// Bus (GestionParc) - Table: Bus, Column: Matricule (instead of immatriculation)
function handleBus($method, $id, $input) {
    $db = getDb('parc');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed for GestionParc'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM `Bus` WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Bus not found'];
            }
            $stmt = $db->query("SELECT * FROM `Bus` ORDER BY Matricule");
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// HANDLERS - Salariés (GRH)
// ============================================
function handleSalaries($method, $id, $input) {
    $db = getDb('grh');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM salaries WHERE id = ?");
                $stmt->execute([$id]);
                $result = $stmt->fetch();
                return $result ? ['success' => true, 'data' => $result] : ['success' => false, 'error' => 'Salarié not found'];
            }
            $stmt = $db->query("SELECT * FROM salaries ORDER BY nom");
            return ['success' => true, 'data' => $stmt->fetchAll()];
            
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// HANDLERS - Transport
// ============================================
function handleDriverSafety($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM driver_safety ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO driver_safety (conducteur_id, bus_id, score_securite, conduite_defensive, respect_code_route, tenue_volant, comportement, observations, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['conducteur_id'] ?? null,
                $input['bus_id'] ?? null,
                $input['score_securite'] ?? 0,
                $input['conduite_defensive'] ?? '',
                $input['respect_code_route'] ?? '',
                $input['tenue_volant'] ?? '',
                $input['comportement'] ?? '',
                $input['observations'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Driver Safety enregistré', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

function handleBusChecklists($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM bus_checklists ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO bus_checklists (bus_id, conducteur_id, type_checklist, pneus, freins, lumieres, retrovisers, klaxon, extincteur, trousse_secours, reservoire_eau, etat_general, observations, conducteur_signature, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['bus_id'] ?? null,
                $input['conducteur_id'] ?? null,
                $input['type_checklist'] ?? 'pretrip',
                $input['pneus'] ?? 'ok',
                $input['freins'] ?? 'ok',
                $input['lumieres'] ?? 'ok',
                $input['retrovisers'] ?? 'ok',
                $input['klaxon'] ?? 'ok',
                $input['extincteur'] ?? 'ok',
                $input['trousse_secours'] ?? 'ok',
                $input['reservoire_eau'] ?? 'ok',
                $input['etat_general'] ?? 'bon',
                $input['observations'] ?? '',
                $input['conducteur_signature'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Checklist enregistré', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

function handleAccidentsBus($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM accidents_bus ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO accidents_bus (bus_id, conducteur_id, lieu, date_heure, type_accident, degats_materiels, blesses, morts, causes, circonstances, mesures_urgentes, pv_police, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['bus_id'] ?? null,
                $input['conducteur_id'] ?? null,
                $input['lieu'] ?? '',
                $input['date_heure'] ?? null,
                $input['type_accident'] ?? '',
                $input['degats_materiels'] ?? '',
                $input['blesses'] ?? 0,
                $input['morts'] ?? 0,
                $input['causes'] ?? '',
                $input['circonstances'] ?? '',
                $input['mesures_urgentes'] ?? '',
                $input['pv_police'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Accident enregistré', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

function handleIncidentsVoyageurs($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM incidents_voyageurs ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO incidents_voyageurs (bus_id, ligne_id, date_heure, type_incident, description, nombre_victimes,措施, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['bus_id'] ?? null,
                $input['ligne_id'] ?? null,
                $input['date_heure'] ?? null,
                $input['type_incident'] ?? '',
                $input['description'] ?? '',
                $input['nombre_victimes'] ?? 0,
                $input['mesures'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Incident voyageur enregistré', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

function handleCrowdSafety($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM crowd_safety ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO crowd_safety (site_id, date_heure, affluence_estimee, niveau_risque, mesures_mises_en_place, observations, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['site_id'] ?? null,
                $input['date_heure'] ?? null,
                $input['affluence_estimee'] ?? 0,
                $input['niveau_risque'] ?? 'faible',
                $input['mesures_mises_en_place'] ?? '',
                $input['observations'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Crowd Safety enregistré', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

function handleInspectionQuais($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM inspection_quais ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO inspection_quais (site_id, inspecteur_id, date_inspection, etat_sol, etat_mur, eclairage, signaletique, dispositifs_securite, acces_handicapes, observations, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['site_id'] ?? null,
                $input['inspecteur_id'] ?? null,
                $input['date_inspection'] ?? null,
                $input['etat_sol'] ?? '',
                $input['etat_mur'] ?? '',
                $input['eclairage'] ?? '',
                $input['signaletique'] ?? '',
                $input['dispositifs_securite'] ?? '',
                $input['acces_handicapes'] ?? '',
                $input['observations'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Inspection quai enregistrée', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

function handleFatigueConducteur($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM fatigue_conducteur ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO fatigue_conducteur (conducteur_id, bus_id, date_heure, niveau_fatigue, heures_conduite, pauses_respectees, symptomes, evaluation, recommandations, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['conducteur_id'] ?? null,
                $input['bus_id'] ?? null,
                $input['date_heure'] ?? null,
                $input['niveau_fatigue'] ?? 'faible',
                $input['heures_conduite'] ?? 0,
                $input['pauses_respectees'] ?? true,
                $input['symptomes'] ?? '',
                $input['evaluation'] ?? '',
                $input['recommandations'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Fatigue conducteur enregistrée', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

function handleEvenementsMajeurs($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM evenements_majeurs ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO evenements_majeurs (type_evenement, date_heure, lieu, description, nombre_victimes, degats_materiels, mesures_prises, responsable_suivi, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $input['type_evenement'] ?? '',
                $input['date_heure'] ?? null,
                $input['lieu'] ?? '',
                $input['description'] ?? '',
                $input['nombre_victimes'] ?? 0,
                $input['degats_materiels'] ?? '',
                $input['mesures_prises'] ?? '',
                $input['responsable_suivi'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Événement majeur enregistré', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

function handleBusAnomalies($method, $id, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($method) {
        case 'GET':
            $stmt = $db->query("SELECT * FROM bus_anomalies ORDER BY created_at DESC");
            return ['success' => true, 'data' => $stmt->fetchAll()];
        case 'POST':
            $stmt = $db->prepare("INSERT INTO bus_anomalies (bus_id, conducteur_id, type_anomalie, description, gravite, photo_url, traitee, created_at) VALUES (?, ?, ?, ?, ?, ?, false, NOW())");
            $stmt->execute([
                $input['bus_id'] ?? null,
                $input['conducteur_id'] ?? null,
                $input['type_anomalie'] ?? '',
                $input['description'] ?? '',
                $input['gravite'] ?? 'faible',
                $input['photo_url'] ?? ''
            ]);
            return ['success' => true, 'message' => 'Anomalie bus enregistrée', 'id' => $db->lastInsertId()];
        default:
            return ['success' => false, 'error' => 'Method not allowed'];
    }
}

// ============================================
// AUTHENTIFICATION
// ============================================
function handleAuth($method, $action, $input) {
    $db = getDb('hse');
    if (!$db) return ['success' => false, 'error' => 'Database connection failed'];
    
    switch ($action) {
        case 'login':
            $email = $input['email'] ?? '';
            $password = $input['password'] ?? '';
            
            $stmt = $db->prepare("SELECT u.*, r.name as role_name, r.slug as role_slug FROM users u LEFT JOIN roles r ON u.role_id = r.id WHERE u.email = ? AND u.is_active = 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch();
            
            if ($user && password_verify($password, $user['password'])) {
                // Generate JWT token (simple base64 for demo - use Firebase/JWT in production)
                $token = base64_encode(json_encode([
                    'user_id' => $user['id'],
                    'email' => $user['email'],
                    'role' => $user['role_slug'],
                    'exp' => time() + 3600
                ]));
                
                return [
                    'success' => true,
                    'message' => 'Connexion réussie',
                    'data' => [
                        'user' => [
                            'id' => $user['id'],
                            'name' => $user['name'],
                            'email' => $user['email'],
                            'role' => $user['role_slug']
                        ],
                        'authorisation' => [
                            'token' => $token,
                            'type' => 'bearer'
                        ]
                    ]
                ];
            }
            return ['success' => false, 'error' => 'Email ou mot de passe incorrect'];
            
        case 'register':
            $name = $input['name'] ?? '';
            $email = $input['email'] ?? '';
            $password = $input['password'] ?? '';
            
            // Check if email exists
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                return ['success' => false, 'error' => 'Email déjà utilisé'];
            }
            
            // Create user
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db->prepare("INSERT INTO users (name, email, password, role_id, is_active, created_at) VALUES (?, ?, ?, 6, 1, NOW())");
            $stmt->execute([$name, $email, $hashedPassword]);
            
            return ['success' => true, 'message' => 'Utilisateur créé avec succès'];
            
        case 'me':
            // Get current user from token
            $token = $input['token'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? '';
            $token = str_replace('Bearer ', '', $token);
            
            try {
                $tokenData = json_decode(base64_decode($token), true);
                if (!$tokenData || ($tokenData['exp'] ?? 0) < time()) {
                    return ['success' => false, 'error' => 'Token invalide ou expiré'];
                }
                
                $stmt = $db->prepare("SELECT u.*, r.name as role_name, r.slug as role_slug FROM users u LEFT JOIN roles r ON u.role_id = r.id WHERE u.id = ?");
                $stmt->execute([$tokenData['user_id']]);
                $user = $stmt->fetch();
                
                if ($user) {
                    return ['success' => true, 'data' => $user];
                }
                return ['success' => false, 'error' => 'Utilisateur non trouvé'];
            } catch (Exception $e) {
                return ['success' => false, 'error' => 'Token invalide'];
            }
            
        default:
            return ['success' => false, 'error' => 'Action not found'];
    }
}