<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Configuration Base de Données
$servername = "localhost";
$username = "transubd_transub_user";
$password = "Tr@nsub2@24";
$database = "transubd_GGR";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$database;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("ERROR: Connexion impossible");
}

$request = isset($_GET['request']) ? trim($_GET['request']) : '';

switch($request) {
    
    // ======================== CONNEXION ========================
    case 'login':
        $json = file_get_contents('php://input');
        $data = json_decode($json, true);
        
        $user = $data['username'] ?? '';
        $pass = $data['password'] ?? '';
        $site = $data['site'] ?? '';
        
        $stmt = $pdo->prepare("SELECT * FROM Utilisateurs WHERE BINARY code_utilisateur = ? AND BINARY mot_de_passe = ? AND TRIM(SiteID) = TRIM(?)");
        $stmt->execute([trim($user), trim($pass), trim($site)]);
        
        if ($stmt->rowCount() > 0) {
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $token = base64_encode(implode('|', [
                $row['code_utilisateur'],
                $row['NomPrenom'],
                $row['SiteID'],
                $row['role']
            ]));
            echo "OK|".$token;
        } else {
            echo "ERROR";
        }
        break;

    // ======================== SITES ========================
    case 'sites':
        $stmt = $pdo->query("SELECT SiteID, Nom_Site, Nom_SiteAR, Localisation_Site FROM Sites ORDER BY Nom_Site");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo implode('|', $row) . "\n";
        }
        break;

    // ======================== BUS ========================
    case 'bus':
        $site = $_GET['site'] ?? '';
        $stmt = $pdo->prepare("SELECT BusID, Modele, SiteID FROM BusGares WHERE TRIM(SiteID) = TRIM(?) ORDER BY BusID");
        $stmt->execute([$site]);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo $row['BusID'] . '|' . $row['Modele'] . '|' . $row['SiteID'] . "\n";
        }
        break;

    // ======================== LIGNES ========================
    case 'lignes':
        $stmt = $pdo->query("SELECT LigneID, Designation FROM Lignes ORDER BY Designation");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo $row['LigneID'] . '|' . $row['Designation'] . "\n";
        }
        break;

    // ======================== ARRETS ========================
    case 'arrets':
        $stmt = $pdo->query("SELECT ArretID, Designation FROM Arrets ORDER BY Designation");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo $row['ArretID'] . '|' . $row['Designation'] . "\n";
        }
        break;

    // ======================== OPERATEURS ========================
    case 'operateurs':
        $site = $_GET['site'] ?? '';
        $sql = "SELECT OperateurID, NomOperateur, SiteID FROM Operateurs ";
        if (!empty($site)) {
            $sql .= "WHERE TRIM(SiteID) = TRIM(?) ";
        }
        $sql .= "ORDER BY NomOperateur";
        
        $stmt = $pdo->prepare($sql);
        if (!empty($site)) {
            $stmt->execute([$site]);
        } else {
            $stmt->execute();
        }
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo $row['OperateurID'] . '|' . $row['NomOperateur'] . '|' . $row['SiteID'] . "\n";
        }
        break;

    // ======================== UTILISATEURS ========================
    case 'users':
        $site = $_GET['site'] ?? '';
        $sql = "SELECT code_utilisateur, Nom, Prenom, NomPrenom, role, SiteID, statut FROM Utilisateurs ";
        if (!empty($site)) {
            $sql .= "WHERE TRIM(SiteID) = TRIM(?) ";
        }
        $sql .= "ORDER BY NomPrenom";
        
        $stmt = $pdo->prepare($sql);
        if (!empty($site)) {
            $stmt->execute([$site]);
        } else {
            $stmt->execute();
        }
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo implode('|', $row) . "\n";
        }
        break;

    // ======================== UPDATE SITE ========================
    case 'update_site':
        $siteID = trim($_POST['siteID'] ?? '');
        $nomSite = trim($_POST['nomSite'] ?? '');
        $nomSiteAR = trim($_POST['nomSiteAR'] ?? '');
        $localisation = trim($_POST['localisation'] ?? '');
        $user = trim($_POST['user'] ?? '');

        $stmt = $pdo->prepare("UPDATE Sites SET Nom_Site = ?, Nom_SiteAR = ?, Localisation_Site = ?, Cree_Par = ?, Date_Creation = NOW() WHERE TRIM(SiteID) = TRIM(?)");
        $stmt->execute([$nomSite, $nomSiteAR, $localisation, $user, $siteID]);
        
        if ($stmt->rowCount() > 0) {
            echo "OK";
        } else {
            echo "ERROR";
        }
        break;

    // ======================== CREATE SITE ========================
    case 'create_site':
        $siteID = trim($_POST['siteID'] ?? '');
        $nomSite = trim($_POST['nomSite'] ?? '');
        $nomSiteAR = trim($_POST['nomSiteAR'] ?? '');
        $localisation = trim($_POST['localisation'] ?? '');
        $user = trim($_POST['user'] ?? '');

        $stmt = $pdo->prepare("INSERT INTO Sites (SiteID, Nom_Site, Nom_SiteAR, Localisation_Site, Cree_Par, Date_Creation) VALUES (?,?,?,?,?,NOW())");
        $stmt->execute([$siteID, $nomSite, $nomSiteAR, $localisation, $user]);
        
        if ($stmt->rowCount() > 0) {
            echo "OK";
        } else {
            echo "ERROR";
        }
        break;

    // ======================== DELETE SITE ========================
    case 'delete_site':
        $siteID = trim($_POST['siteID'] ?? '');
        $stmt = $pdo->prepare("DELETE FROM Sites WHERE TRIM(SiteID) = TRIM(?)");
        $stmt->execute([$siteID]);
        
        if ($stmt->rowCount() > 0) {
            echo "OK";
        } else {
            echo "ERROR";
        }
        break;

    // ======================== PERMISSIONS ROLES ========================
    case 'role_permissions':
        $roleName = trim($_GET['role'] ?? '');
        
        $stmt = $pdo->prepare("SELECT * FROM RolesVB WHERE TRIM(designation) = TRIM(?) LIMIT 1");
        $stmt->execute([$roleName]);
        
        if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo implode('|', $row);
        }
        break;

    // ======================== GET USER SITE ========================
    case 'get_user_site':
        $username = trim($_GET['username'] ?? '');
        $stmt = $pdo->prepare("SELECT SiteID FROM Utilisateurs WHERE TRIM(code_utilisateur) = TRIM(?) LIMIT 1");
        $stmt->execute([$username]);
        if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo $row['SiteID'];
        }
        break;

    default:
        echo "API SMART GARE - ACTIVE";
        break;
}

$pdo = null;
?>