<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/chat_helper.php';
header('Content-Type: application/json');

if (!isset($_SESSION['customer_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$request_id = (int)($_POST['request_id'] ?? 0);
$message = trim($_POST['message'] ?? '');

if (!$request_id || $message === '') {
    echo json_encode(['success' => false, 'message' => 'Message is required.']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    ensureChatTables($db);

    $stmt = $db->prepare("SELECT id, request_number FROM service_requests WHERE id = :id AND customer_id = :customer_id LIMIT 1");
    $stmt->execute([':id' => $request_id, ':customer_id' => $_SESSION['customer_id']]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$request) {
        echo json_encode(['success' => false, 'message' => 'Request not found.']);
        exit;
    }

    $conversation = getOrCreateConversation($db, $request_id);
    if (!$conversation) {
        echo json_encode(['success' => false, 'message' => 'Unable to create conversation.']);
        exit;
    }

    addChatMessage($db, (int)$conversation['id'], $request_id, 'customer', $_SESSION['customer_id'], $message, 'chat');
    $assignment = handleCustomerChatMessageAssignment($db, $conversation, $request);

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