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

if (!isset($_SESSION['csr_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);
    releaseOverdueChatAssignments($db, 5);
    ensureOperationalTables($db);

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

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

    $lockResult = blockIfRequestLockedByOtherCSR($db, $request_id, $_SESSION['csr_id']);
    if (!$lockResult['success']) {
        echo json_encode($lockResult);
        exit;
    }

    $conversation = getOrCreateConversation($db, $request_id, null);
    if (!$conversation) {
        echo json_encode(['success' => false, 'message' => 'Conversation not found.']);
        exit;
    }

    $assignment = getChatAssignmentInfo($db, $request_id, (int)$_SESSION['csr_id']);
    $assignedId = $assignment['assigned_csr_id'] ?? null;
    $status = $assignment['assignment_status'] ?? 'unassigned';

    if (empty($assignment['can_reply']) && empty($assignment['is_mine'])) {
        echo json_encode(['success' => false, 'message' => $assignment['label'] . '. You cannot reply until the chat is assigned to you.']);
        exit;
    }

    if ($assignedId && (int)$assignedId !== (int)$_SESSION['csr_id'] && in_array($status, ['waiting_first_response', 'active'], true)) {
        echo json_encode(['success' => false, 'message' => $assignment['label'] . '. You can view this chat, but you cannot reply.']);
        exit;
    }

    if (!$assignedId && in_array($status, ['unassigned', 'returned_queue'], true)) {
        $claim = claimChatConversation($db, $request_id, (int)$_SESSION['csr_id']);
        if (!$claim['success']) {
            echo json_encode($claim);
            exit;
        }
        $assignment = getChatAssignmentInfo($db, $request_id, (int)$_SESSION['csr_id']);
    }

    if (($assignment['assignment_status'] ?? '') === 'waiting_first_response' && (int)($assignment['assigned_csr_id'] ?? 0) === (int)$_SESSION['csr_id']) {
        $db->prepare("UPDATE chat_conversations SET first_response_at = NOW(), assignment_status = 'active', assignment_note = 'CSR replied', updated_at = NOW() WHERE request_id = :request_id")
           ->execute([':request_id' => $request_id]);
    } else {
        $db->prepare("UPDATE chat_conversations SET assignment_status = 'active', updated_at = NOW() WHERE request_id = :request_id AND assigned_csr_id = :csr_id")
           ->execute([':request_id' => $request_id, ':csr_id' => $_SESSION['csr_id']]);
    }

    $conversation = getOrCreateConversation($db, $request_id, null);
    addChatMessage($db, (int)$conversation['id'], $request_id, 'csr', $_SESSION['csr_id'], $message, 'chat');
    logRequestAction($db, $request_id, $_SESSION['csr_id'], 'csr', 'chat_reply', null, null, mb_substr($message, 0, 200));
    logCSRActivity($db, $_SESSION['csr_id'], 'chat_reply', $request_id, mb_substr($message, 0, 200));
    createCustomerNotification($db, $request_id, 'New CSR Message', 'A CSR replied to your request #' . $request['request_number'], 'info');

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