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

    $role_id = $channel['rules_role_id'];

    try {
        db()->beginTransaction();

        // 1. Remove acceptance record
        $stmtAcc = db()->prepare("DELETE FROM rule_acceptances WHERE user_id = ? AND channel_id = ?");
        $stmtAcc->execute([$user_id, $channel_id]);

        // 2. Remove role if it was configured
        if ($role_id) {
            $stmtRole = db()->prepare("DELETE FROM user_roles WHERE user_id = ? AND role_id = ?");
            $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 du retrait : ' . $e->getMessage()]);
    }
    exit;
}

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