<?php
require_once 'db_connection.php';

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

try {
    $data = json_decode(file_get_contents('php://input'), true);

    $loggedInUserId = $data['logged_in_user_id'];
    $selectedUserId = $data['selected_user_id'];

    if (!$loggedInUserId || !$selectedUserId) {
        echo json_encode(['success' => false, 'message' => 'Invalid user IDs']);
        exit;
    }

    $checkQuery = "
        SELECT c.id 
        FROM conversations c
        JOIN conversation_participants cp1 ON c.id = cp1.conversation_id
        JOIN conversation_participants cp2 ON c.id = cp2.conversation_id
        WHERE cp1.user_id = ? AND cp2.user_id = ? AND c.name IS NULL
    ";
    $stmt = $pdo->prepare($checkQuery);
    $stmt->execute([$loggedInUserId, $selectedUserId]);
    $existingConversation = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existingConversation) {
        echo json_encode(['success' => false, 'message' => 'Conversation already exists', 'conversation_id' => $existingConversation['id']]);
        exit;
    }

    $pdo->beginTransaction();

    $conversationQuery = "INSERT INTO conversations (name) VALUES (NULL)";
    $pdo->exec($conversationQuery);
    $conversationId = $pdo->lastInsertId();

    $addUserQuery = "INSERT INTO conversation_participants (conversation_id, user_id) VALUES (?, ?)";
    $stmt = $pdo->prepare($addUserQuery);
    $stmt->execute([$conversationId, $loggedInUserId]);

    $stmt->execute([$conversationId, $selectedUserId]);

    $pdo->commit();

    echo json_encode(['success' => true, 'conversation_id' => $conversationId]);
} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['success' => false, 'message' => 'Error creating chat: ' . $e->getMessage()]);
}
