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

$user_id = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true) ?? $_POST;

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $server_id = $_GET['server_id'] ?? 0;
    if (!$server_id) {
        echo json_encode(['success' => false, 'error' => 'Missing server_id']);
        exit;
    }

    // Verify user is in server
    $stmt = db()->prepare("SELECT * FROM server_members WHERE server_id = ? AND user_id = ?");
    $stmt->execute([$server_id, $user_id]);
    if (!$stmt->fetch()) {
        echo json_encode(['success' => false, 'error' => 'Access denied']);
        exit;
    }

    $stmt = db()->prepare("SELECT * FROM server_badges WHERE server_id = ? ORDER BY created_at DESC");
    $stmt->execute([$server_id]);
    $badges = $stmt->fetchAll();

    echo json_encode([
        'success' => true, 
        'badges' => $badges
    ]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $data['action'] ?? '';
    $server_id = $data['server_id'] ?? 0;

    // Permissions check
    $stmt = db()->prepare("SELECT owner_id FROM servers WHERE id = ?");
    $stmt->execute([$server_id]);
    $server = $stmt->fetch();
    $is_owner = ($server && $server['owner_id'] == $user_id);
    $can_manage = Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_SERVER) || Permissions::hasPermission($user_id, $server_id, Permissions::ADMINISTRATOR);

    if (!$is_owner && !$can_manage) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }

    if ($action === 'create') {
        $name = $data['name'] ?? 'New Badge';
        $image_url = $data['image_url'] ?? '';
        
        if (empty($image_url)) {
            echo json_encode(['success' => false, 'error' => 'Image requise']);
            exit;
        }

        $stmt = db()->prepare("INSERT INTO server_badges (server_id, name, image_url) VALUES (?, ?, ?)");
        $stmt->execute([$server_id, $name, $image_url]);
        echo json_encode(['success' => true, 'badge_id' => db()->lastInsertId()]);
    } elseif ($action === 'update') {
        $badge_id = $data['id'] ?? 0;
        $name = $data['name'] ?? '';
        $image_url = $data['image_url'] ?? '';

        $stmt = db()->prepare("UPDATE server_badges SET name = ?, image_url = ? WHERE id = ? AND server_id = ?");
        $stmt->execute([$name, $image_url, $badge_id, $server_id]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'delete') {
        $badge_id = $data['id'] ?? 0;
        $stmt = db()->prepare("DELETE FROM server_badges WHERE id = ? AND server_id = ?");
        $stmt->execute([$badge_id, $server_id]);
        echo json_encode(['success' => true]);
    } elseif ($action === 'set_user_badges') {
        $target_user_id = $data['user_id'] ?? 0;
        $badge_ids = $data['badge_ids'] ?? [];

        $db = db();
        $db->beginTransaction();
        try {
            $stmt = $db->prepare("DELETE FROM member_badges WHERE user_id = ? AND server_id = ?");
            $stmt->execute([$target_user_id, $server_id]);

            if (!empty($badge_ids)) {
                $stmt = $db->prepare("INSERT INTO member_badges (server_id, user_id, badge_id) VALUES (?, ?, ?)");
                foreach ($badge_ids as $bid) {
                    $check = $db->prepare("SELECT id FROM server_badges WHERE id = ? AND server_id = ?");
                    $check->execute([$bid, $server_id]);
                    if ($check->fetch()) {
                        $stmt->execute([$server_id, $target_user_id, $bid]);
                    }
                }
            }
            $db->commit();
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            $db->rollBack();
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }
    exit;
}
