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

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Messaging.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $userId = (int)$_SESSION['user_id'];
    $participantIds = array_map('intval', (array)($_POST['participant_ids'] ?? []));
    $participantIds = array_values(array_unique(array_filter($participantIds, fn($id) => $id > 0 && $id !== $userId)));
    $title = trim((string)($_POST['title'] ?? ''));

    if (empty($participantIds)) {
        echo json_encode(['success' => false, 'message' => 'Select at least one recipient.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $messaging = new Messaging($conn);

    if (count($participantIds) === 1 && $title === '') {
        $conversationId = $messaging->getOrCreateDirectConversation($userId, $participantIds[0]);
    } else {
        if ($title === '') {
            echo json_encode(['success' => false, 'message' => 'Group conversations require a title.']);
            exit;
        }
        $conversationId = $messaging->createGroupConversation($userId, $title, $participantIds);
    }

    echo json_encode(['success' => true, 'conversation_id' => $conversationId]);
} catch (InvalidArgumentException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} catch (Throwable $e) {
    error_log('Starting conversation failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to start conversation.']);
}
