<?php
require_once __DIR__.'/../includes/functions.php';
header('Content-Type: application/json');
try {
    $u = current_user();
    if (!$u) { throw new Exception('Please login first.'); }
    verify_csrf();
    mj_realtime_chat_ensure_schema();
    $chatId = (int)($_POST['chat_id'] ?? 0);
    $action = strtolower(trim((string)($_POST['action'] ?? '')));
    if ($chatId <= 0) { throw new Exception('Missing conversation.'); }
    $chat = one('SELECT * FROM mj_chats WHERE id=? LIMIT 1', [$chatId]);
    if (!$chat) { throw new Exception('Conversation not found.'); }
    $role = mj_chat_assert_participant($chat, (int)$u['id']);
    $prefix = $role === 'seller' ? 'seller' : 'buyer';
    $okMsg = 'Conversation updated.';
    if ($action === 'pin') { q('UPDATE mj_chats SET `'.$prefix.'_pinned`=1 WHERE id=?', [$chatId]); $okMsg='Conversation pinned.'; }
    elseif ($action === 'unpin') { q('UPDATE mj_chats SET `'.$prefix.'_pinned`=0 WHERE id=?', [$chatId]); $okMsg='Conversation unpinned.'; }
    elseif ($action === 'archive') { q('UPDATE mj_chats SET `'.$prefix.'_archived`=1 WHERE id=?', [$chatId]); $okMsg='Conversation archived.'; }
    elseif ($action === 'restore') { q('UPDATE mj_chats SET `'.$prefix.'_archived`=0 WHERE id=?', [$chatId]); $okMsg='Conversation restored.'; }
    elseif ($action === 'mark_unread') { q('UPDATE mj_chats SET `'.$prefix.'_mark_unread`=1 WHERE id=?', [$chatId]); $okMsg='Marked as unread.'; }
    elseif ($action === 'mute_today') { q('UPDATE mj_chats SET `'.$prefix.'_muted_until`=DATE_ADD(NOW(), INTERVAL 1 DAY) WHERE id=?', [$chatId]); $okMsg='Muted for today.'; }
    elseif ($action === 'mute_hour') { q('UPDATE mj_chats SET `'.$prefix.'_muted_until`=DATE_ADD(NOW(), INTERVAL 1 HOUR) WHERE id=?', [$chatId]); $okMsg='Muted for 1 hour.'; }
    elseif ($action === 'unmute') { q('UPDATE mj_chats SET `'.$prefix.'_muted_until`=NULL WHERE id=?', [$chatId]); $okMsg='Conversation unmuted.'; }
    elseif ($action === 'report') { q('UPDATE mj_chats SET status="reported", reported_at=NOW() WHERE id=?', [$chatId]); $okMsg='Chat reported. Our team will review it.'; }
    else { throw new Exception('Invalid action.'); }
    echo json_encode(['ok'=>true,'message'=>$okMsg]);
} catch (Throwable $e) { echo json_encode(['ok'=>false,'error'=>$e->getMessage()]); }
