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

$current_user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $target_user_id = $_POST['user_id'] ?? 0;
    
    if ($target_user_id == $current_user_id) {
        echo json_encode(['success' => false, 'error' => 'You cannot message yourself']);
        exit;
    }

    try {
        // Check if DM channel already exists between these two users
        $stmt = db()->prepare("
            SELECT c.id 
            FROM channels c
            JOIN channel_members cm1 ON c.id = cm1.channel_id
            JOIN channel_members cm2 ON c.id = cm2.channel_id
            WHERE c.type = 'dm' AND cm1.user_id = ? AND cm2.user_id = ?
        ");
        $stmt->execute([$current_user_id, $target_user_id]);
        $existing = $stmt->fetch();

        if ($existing) {
            echo json_encode(['success' => true, 'channel_id' => $existing['id']]);
            exit;
        }

        // Create new DM channel
        $stmt = db()->prepare("INSERT INTO channels (server_id, name, type) VALUES (NULL, 'dm', 'dm')");
        $stmt->execute();
        $channel_id = db()->lastInsertId();

        // Add both users to the channel
        $stmt = db()->prepare("INSERT INTO channel_members (channel_id, user_id) VALUES (?, ?), (?, ?)");
        $stmt->execute([$channel_id, $current_user_id, $channel_id, $target_user_id]);

        echo json_encode(['success' => true, 'channel_id' => $channel_id]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Fetch all DM channels for current user
    try {
        $stmt = db()->prepare("
            SELECT c.id, u.display_name as other_user, u.username as login_name, u.avatar_url, u.status, u.id as other_user_id
            FROM channels c
            JOIN channel_members cm1 ON c.id = cm1.channel_id
            JOIN channel_members cm2 ON c.id = cm2.channel_id
            JOIN users u ON cm2.user_id = u.id
            WHERE c.type = 'dm' AND cm1.user_id = ? AND cm2.user_id != ?
        ");
        $stmt->execute([$current_user_id, $current_user_id]);
        $dms = $stmt->fetchAll();

        echo json_encode(['success' => true, 'dms' => $dms]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
}
