<?php
header('Content-Type: application/json');
require_once 'auth/session.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json = json_decode(file_get_contents('php://input'), true);
    $channel_id = $json['channel_id'] ?? 0;
    $user_id = $_SESSION['user_id'];

    if (!$channel_id) {
        echo json_encode(['success' => false, 'error' => 'ID de canal manquant']);
        exit;
    }

    // Fetch channel details to get rules_role_id
    $stmt = db()->prepare("SELECT * FROM channels WHERE id = ? AND type = 'rules'");
    $stmt->execute([$channel_id]);
    $channel = $stmt->fetch();

    if (!$channel) {
        echo json_encode(['success' => false, 'error' => 'Canal de règles introuvable']);
        exit;
    }

    if (empty($channel['rules_role_id'])) {
        echo json_encode(['success' => false, 'error' => 'Aucun rôle n\'est configuré pour ce canal']);
        exit;
    }

    $role_id = $channel['rules_role_id'];

    try {
        db()->beginTransaction();

        // 1. Record acceptance
        $stmtAcc = db()->prepare("INSERT IGNORE INTO rule_acceptances (user_id, channel_id) VALUES (?, ?)");
        $stmtAcc->execute([$user_id, $channel_id]);

        // 2. Assign role
        // Check if user already has this role
        $stmtRoleCheck = db()->prepare("SELECT 1 FROM user_roles WHERE user_id = ? AND role_id = ?");
        $stmtRoleCheck->execute([$user_id, $role_id]);
        
        if (!$stmtRoleCheck->fetch()) {
            $stmtRole = db()->prepare("INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)");
            $stmtRole->execute([$user_id, $role_id]);
        }

        db()->commit();
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        db()->rollBack();
        echo json_encode(['success' => false, 'error' => 'Erreur lors de l\'attribution du rôle : ' . $e->getMessage()]);
    }
    exit;
}

echo json_encode(['success' => false, 'error' => 'Méthode non autorisée']);
