<?php
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/mj_v3041_access_notifications_location.php';
header('Content-Type: application/json');
try {
    $u = current_user();
    if (!$u) { throw new Exception('Please login to send a message.'); }
    verify_csrf();
    mj263_schema();
    mj_trust_bundle_ensure_schema();
    mj_realtime_chat_ensure_schema();

    $chatId = (int)($_POST['chat_id'] ?? 0);
    $listingId = (int)($_POST['listing_id'] ?? 0);
    $companyId = (int)($_POST['company_id'] ?? 0);
    $sellerId = (int)($_POST['seller_id'] ?? 0);
    $buyerId = (int)($_POST['buyer_id'] ?? 0);
    $msg = trim((string)($_POST['message'] ?? ''));

    if ($msg === '') { throw new Exception('Please type a message before sending.'); }
    if ((function_exists('mb_strlen') ? mb_strlen($msg) : strlen($msg)) > 2000) { throw new Exception('Message is too long. Please keep it under 2000 characters.'); }

    if ($chatId > 0) {
        $chat = one('SELECT * FROM mj_chats WHERE id=? LIMIT 1', [$chatId]);
        if (!$chat) { throw new Exception('Conversation not found.'); }
    } else {
        if (!$sellerId && $listingId) {
            $l = one('SELECT user_id,company_id FROM mj_listings WHERE id=? LIMIT 1', [$listingId]);
            if ($l) { $sellerId = (int)($l['user_id'] ?? 0); if (!$companyId) { $companyId = (int)($l['company_id'] ?? 0); } }
        }
        if (!$sellerId && $companyId) {
            $co = one('SELECT user_id FROM mj_companies WHERE id=? LIMIT 1', [$companyId]);
            $sellerId = (int)($co['user_id'] ?? 0);
        }
        if (!$sellerId) { throw new Exception('Seller not found.'); }
        $buyerId = ((int)$u['id'] === $sellerId) ? ($buyerId ?: (int)$u['id']) : (int)$u['id'];
        $chat = one('SELECT * FROM mj_chats WHERE IFNULL(listing_id,0)=? AND IFNULL(company_id,0)=? AND buyer_id=? AND seller_id=? LIMIT 1', [$listingId,$companyId,$buyerId,$sellerId]);
        if (!$chat) {
            q('INSERT INTO mj_chats(listing_id,company_id,buyer_id,seller_id,created_at) VALUES(?,?,?,?,NOW())', [$listingId?:null,$companyId?:null,$buyerId,$sellerId]);
            $chat = one('SELECT * FROM mj_chats WHERE id=? LIMIT 1', [db()->lastInsertId()]);
        }
    }

    $role = mj_chat_assert_participant($chat, (int)$u['id']);
    $receiverId = ((int)$u['id'] === (int)$chat['seller_id']) ? (int)$chat['buyer_id'] : (int)$chat['seller_id'];
    $risk = mj_chat_risk_score($msg);
    q('INSERT INTO mj_chat_messages(chat_id,sender_id,message,risk_score,is_read,created_at) VALUES(?,?,?,?,0,NOW())', [(int)$chat['id'], (int)$u['id'], $msg, $risk]);
    $messageId = (int)db()->lastInsertId();
    q('UPDATE mj_chats SET last_message=?, last_message_at=NOW(), buyer_archived=0, seller_archived=0 WHERE id=?', [$msg, (int)$chat['id']]);
    if (!empty($chat['listing_id'])) { try { mj263_track_event((int)$chat['listing_id'], 'chat_message', 'sent'); } catch (Throwable $e) {} }
    $leadId = 0;
    try { if (function_exists('mj_leads_record_chat_message')) { $leadId = mj_leads_record_chat_message($chat, (int)$u['id'], $receiverId, $msg); } } catch (Throwable $e) {}
    $notifyUrl = $leadId ? 'my-leads.php?source=chat&lead='.$leadId : mj_chat_url($chat);
    try { mj263_notify($receiverId, null, 'chat_message', 'New chat/customer message', mb_strimwidth($msg,0,140,'...'), $notifyUrl, 'normal', false); } catch (Throwable $e) {}
    try { if (function_exists('mjv3041_notify_user')) { mjv3041_notify_user($receiverId, 'New chat message', mb_strimwidth($msg,0,140,'...'), 'chat', $notifyUrl, ['chat_id'=>(int)$chat['id'],'message_id'=>$messageId,'lead_id'=>$leadId]); mjv3041_notify_admins('New chat message', 'A customer/seller sent a marketplace chat message.', 'chat', 'admin/leads.php?source=chat', ['chat_id'=>(int)$chat['id'],'message_id'=>$messageId]); } } catch (Throwable $e) {}

    $m = one('SELECT m.*,u.name sender_name FROM mj_chat_messages m LEFT JOIN mj_users u ON u.id=m.sender_id WHERE m.id=? LIMIT 1', [$messageId]);
    echo json_encode(['ok'=>true, 'chat_id'=>(int)$chat['id'], 'message'=>mj_chat_format_message($m, (int)$u['id']), 'risk_score'=>$risk, 'unread_count'=>mj_chat_unread_count((int)$u['id'])]);
} catch (Throwable $e) {
    echo json_encode(['ok'=>false, 'error'=>$e->getMessage()]);
}
