<?php
require_once __DIR__ . "/../../config/db.php";

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit("Méthode non autorisée");
}

$id    = (int)($_POST['id'] ?? 0);
$nom   = trim($_POST['nom'] ?? '');
$desc  = trim($_POST['description'] ?? '');
$perms = $_POST['permissions'] ?? [];

if ($id <= 0 || $nom === '') {
    http_response_code(400);
    exit("Paramètres invalides");
}

try {
    $conn->beginTransaction();

    /*  Mise à jour du rôle */
    $stmt = $conn->prepare("
        UPDATE roles 
        SET nom = ?, description = ?
        WHERE id = ?
    ");
    $stmt->execute([$nom, $desc, $id]);

    /*  Suppression des anciennes permissions */
    $conn->prepare("
        DELETE FROM role_permissions 
        WHERE role_id = ?
    ")->execute([$id]);

    /*  Réinsertion des permissions sélectionnées */
    if (!empty($perms) && is_array($perms)) {

        $stmtPerm = $conn->prepare("
            SELECT id FROM permissions WHERE code = ?
        ");

        $stmtInsert = $conn->prepare("
            INSERT INTO role_permissions (role_id, permission_id)
            VALUES (?, ?)
        ");

        foreach ($perms as $code) {
            $stmtPerm->execute([$code]);
            $permission_id = $stmtPerm->fetchColumn();

            if ($permission_id) {
                $stmtInsert->execute([$id, $permission_id]);
            }
        }
    }

    $conn->commit();

    header("Location: /eagle_client_istanbulcups/index.php?page=roles&success=1");
    exit;

} catch (Exception $e) {
    if ($conn->inTransaction()) {
        $conn->rollBack();
    }
    http_response_code(500);
    exit("Erreur : " . $e->getMessage());
}
