<?php
require_once 'auth/session.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';
    $user_id = $_SESSION['user_id'];
    
    if ($action === 'join') {
        $invite_code = $_POST['invite_code'] ?? '';
        $stmt = db()->prepare("SELECT id FROM servers WHERE invite_code = ?");
        $stmt->execute([$invite_code]);
        $server = $stmt->fetch();
        
        if ($server) {
            $stmt = db()->prepare("INSERT IGNORE INTO server_members (server_id, user_id) VALUES (?, ?)");
            $stmt->execute([$server['id'], $user_id]);
            header('Location: index.php?server_id=' . $server['id']);
            exit;
        } else {
            die("Invalid invite code.");
        }
    }

    if ($action === 'update') {
        $server_id = $_POST['server_id'] ?? 0;
        $name = $_POST['name'] ?? '';
        $icon_url = $_POST['icon_url'] ?? '';
        $theme_color = $_POST['theme_color'] ?? null;
        if ($theme_color === '') $theme_color = null;
        
        require_once 'includes/permissions.php';
        if (Permissions::hasPermission($user_id, $server_id, Permissions::MANAGE_SERVER)) {
            $stmt = db()->prepare("UPDATE servers SET name = ?, icon_url = ?, theme_color = ? WHERE id = ?");
            $stmt->execute([$name, $icon_url, $theme_color, $server_id]);
        }
        
        header('Location: index.php?server_id=' . $server_id);
        exit;
    }

    if ($action === 'delete') {
        $server_id = $_POST['server_id'] ?? 0;
        $stmt = db()->prepare("DELETE FROM servers WHERE id = ? AND owner_id = ?");
        $stmt->execute([$server_id, $user_id]);
        header('Location: index.php');
        exit;
    }

    $name = $_POST['name'] ?? '';
    $icon_url = $_POST['icon_url'] ?? '';
    
    if ($name) {
        try {
            $db = db();
            $db->beginTransaction();
            
            // Create server
            $invite_code = substr(strtoupper(md5(uniqid())), 0, 8);
            $stmt = $db->prepare("INSERT INTO servers (name, owner_id, invite_code, icon_url) VALUES (?, ?, ?, ?)");
            $stmt->execute([$name, $user_id, $invite_code, $icon_url]);
            $server_id = $db->lastInsertId();
            
            // Add owner as member
            $stmt = $db->prepare("INSERT INTO server_members (server_id, user_id) VALUES (?, ?)");
            $stmt->execute([$server_id, $user_id]);
            
            // Create default channel
            $stmt = $db->prepare("INSERT INTO channels (server_id, name, type) VALUES (?, 'general', 'text')");
            $stmt->execute([$server_id]);

            // Create default @everyone role
            $stmt = $db->prepare("INSERT INTO roles (server_id, name, color, permissions, position) VALUES (?, '@everyone', '#99aab5', 0, 0)");
            $stmt->execute([$server_id]);
            
            $db->commit();
            header('Location: index.php?server_id=' . $server_id);
            exit;
        } catch (Exception $e) {
            $db->rollBack();
            die("Error creating server: " . $e->getMessage());
        }
    }
}
header('Location: index.php');
