<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

header('Content-Type: application/json');

try {
    $user_id = Auth::check();
    $data = json_decode(file_get_contents("php://input"));

    if (!isset($data->target_user_id)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing target_user_id']);
        exit;
    }

    $target_id = (int)$data->target_user_id;

    // 1. Verificar si ya existe un chat privado entre ellos
    $sql = "
        SELECT m1.chat_id 
        FROM chat_members m1
        JOIN chat_members m2 ON m1.chat_id = m2.chat_id
        JOIN chats c ON c.id = m1.chat_id
        WHERE m1.user_id = ? AND m2.user_id = ? AND c.type = 'private'
        LIMIT 1
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id, $target_id]);
    $existing = $stmt->fetch();

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

    // 2. Si no existe, crear uno nuevo
    $pdo->beginTransaction();

    // Crear Chat
    $stmt = $pdo->prepare("INSERT INTO chats (type) VALUES ('private')");
    $stmt->execute();
    $chat_id = $pdo->lastInsertId();

    // Añadir Miembros
    $stmt = $pdo->prepare("INSERT INTO chat_members (chat_id, user_id) VALUES (?, ?), (?, ?)");
    $stmt->execute([$chat_id, $user_id, $chat_id, $target_id]);

    $pdo->commit();

    echo json_encode(['success' => true, 'chat_id' => $chat_id]);

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
