<?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;

    // ======================== 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;

    // ======================== LISTE DES ROLES ========================
    case 'roles':
        $stmt = $pdo->prepare("SELECT RoleId, designation FROM RolesVB ORDER BY RoleId");
        $stmt->execute();
        
        while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            echo implode('|', $row) . "\n";
        }
        break;

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

$pdo = null;
?>