<?php
require_once __DIR__ . '/../includes/mj_v304_bootstrap.php';
require_once __DIR__ . '/../includes/mj_v304_leads_helper.php';
require_once __DIR__ . '/../includes/mj_v30429_helpers.php';
header('Content-Type: application/json; charset=utf-8');
function mj429_json(array $d): void { echo json_encode($d, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }
try {
    mj429_ensure_schema();
    $isAdmin = mjv304_is_admin();
    $actorId = mjv304_current_user_id();
    if (!$actorId) { throw new RuntimeException('Please login again.'); }
    $leadId = (int)($_POST['lead_id'] ?? 0);
    if ($leadId <= 0) { throw new RuntimeException('Lead not found.'); }
    $lead = $isAdmin ? mjv304_fetch_one('SELECT * FROM seller_leads WHERE id=?',[$leadId]) : mjv304_fetch_one('SELECT * FROM seller_leads WHERE id=? AND seller_user_id=?',[$leadId,$actorId]);
    if (!$lead) { throw new RuntimeException('Lead not found or not allowed.'); }
    $action = strtolower(trim((string)($_POST['action'] ?? '')));
    $note = trim((string)($_POST['note'] ?? ''));
    if ($action === 'update_status') {
        $status = strtolower(trim((string)($_POST['status'] ?? 'new')));
        mjv304_update_lead_status($leadId, $status, $actorId, $isAdmin ? 'admin' : 'user', $note);
    } elseif ($action === 'add_note') {
        if ($note === '') { throw new RuntimeException('Please type a note.'); }
        mjv304_add_lead_note($leadId, $actorId, $isAdmin ? 'admin' : 'user', $note, null);
    } elseif ($action === 'set_followup') {
        $follow = trim((string)($_POST['followup_at'] ?? ''));
        if ($follow === '') { throw new RuntimeException('Please choose follow-up date/time.'); }
        $follow = str_replace('T',' ', $follow);
        if (strlen($follow) === 16) { $follow .= ':00'; }
        mjv304_add_lead_note($leadId, $actorId, $isAdmin ? 'admin' : 'user', $note ?: 'Follow-up scheduled', $follow);
    } elseif ($action === 'mark_read') {
        if ($isAdmin) { mjv304_execute('UPDATE seller_leads SET is_read=1, updated_at=NOW() WHERE id=?',[$leadId]); }
        else { mjv304_execute('UPDATE seller_leads SET is_read=1, updated_at=NOW() WHERE id=? AND seller_user_id=?',[$leadId,$actorId]); }
    } else { throw new RuntimeException('Unknown action.'); }
    $fresh = mjv304_fetch_one('SELECT * FROM seller_leads WHERE id=?',[$leadId]) ?: [];
    $status = (string)($fresh['status'] ?? 'new');
    $opts = mjv304_status_options();
    mj429_json(['ok'=>true,'message'=>'Lead updated successfully.','lead'=>['id'=>$leadId,'status'=>$status,'status_label'=>$opts[$status] ?? ucfirst($status),'followup_at'=>(string)($fresh['followup_at'] ?? '')]]);
} catch (Throwable $e) {
    mj429_json(['ok'=>false,'error'=>$e->getMessage()]);
}
