<?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'];
    $userIds = array_unique($data['user_ids']);
    $groupName = trim($data['group_name']);

    if (!$loggedInUserId || empty($userIds) || !$groupName) {
        echo json_encode(['success' => false, 'message' => 'Invalid input data.']);
        exit;
    }

    $pdo->beginTransaction();

    $conversationQuery = "INSERT INTO conversations (name, is_group) VALUES (?, 1)";
    $stmt = $pdo->prepare($conversationQuery);
    $stmt->execute([$groupName]);
    $conversationId = $pdo->lastInsertId();

    $participantQuery = "
        INSERT INTO conversation_participants (conversation_id, user_id)
        SELECT ?, ?
        WHERE NOT EXISTS (
            SELECT 1 FROM conversation_participants 
            WHERE conversation_id = ? AND user_id = ?
        )
    ";
    $stmt = $pdo->prepare($participantQuery);

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

    foreach ($userIds as $userId) {
        $stmt->execute([$conversationId, $userId, $conversationId, $userId]);
    }

    $pdo->commit();

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