<?php
require_once __DIR__ . '/mj_v304_bootstrap.php';

function mjv304_create_seller_lead(array $data): int {
    $sellerUserId = (int)($data['seller_user_id'] ?? 0);
    $sourceType   = strtolower(trim((string)($data['source_type'] ?? 'listing')));
    if (!in_array($sourceType, ['deal','listing','company'], true)) { $sourceType = 'listing'; }
    $sourceTitle  = trim((string)($data['source_title'] ?? ''));
    $customerName = trim((string)($data['customer_name'] ?? ''));
    $customerEmail= trim((string)($data['customer_email'] ?? ''));
    $customerPhone= trim((string)($data['customer_phone'] ?? ''));
    $message      = trim((string)($data['customer_message'] ?? ''));

    $sourceId = !empty($data['source_id']) ? (int)$data['source_id'] : null;
    $existingLead = null;
    try {
        $existingLead = mjv304_fetch_one("SELECT id FROM seller_leads WHERE seller_user_id=? AND source_type=? AND source_id <=> ? AND LOWER(COALESCE(customer_email,''))=LOWER(?) AND COALESCE(customer_phone,'')=? AND created_at >= DATE_SUB(NOW(), INTERVAL 10 MINUTE) ORDER BY id DESC LIMIT 1", [
            $sellerUserId, $sourceType, $sourceId, $customerEmail, $customerPhone
        ]);
    } catch (Throwable $ignore) {}
    if ($existingLead) {
        $leadId = (int)$existingLead['id'];
    } else {
        mjv304_execute("INSERT INTO seller_leads
            (seller_user_id,source_type,source_id,source_title,country,customer_name,customer_email,customer_phone,customer_message,status,priority,is_read,ip_address,user_agent,created_at,last_activity_at)
            VALUES (?,?,?,?,?,?,?,?,?,'new','normal',0,?,?,NOW(),NOW())", [
                $sellerUserId,
                $sourceType,
                $sourceId,
                $sourceTitle ?: null,
                trim((string)($data['country'] ?? '')) ?: null,
                $customerName ?: null,
                $customerEmail ?: null,
                $customerPhone ?: null,
                $message ?: null,
                $_SERVER['REMOTE_ADDR'] ?? null,
                substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255),
            ]);
        $leadId = (int)mjv304_db()->lastInsertId();
    }

    try {
        $hasCreated = mjv304_fetch_value("SELECT id FROM seller_lead_activities WHERE lead_id=? AND activity_type='created' LIMIT 1", [$leadId]);
        if (!$hasCreated) {
            mjv304_execute("INSERT INTO seller_lead_activities (lead_id,user_id,user_type,activity_type,note,new_status,created_at) VALUES (?,?, 'system', 'created', ?, 'new', NOW())", [
                $leadId, $sellerUserId, 'New '.$sourceType.' enquiry created'
            ]);
        }
    } catch (Throwable $ignore) {}

    $label = ucfirst($sourceType) . ' enquiry';
    mjv304_notify('user', $sellerUserId, 'New '.$label, trim(($customerName ?: 'Customer') . ($sourceTitle ? ' asked about '.$sourceTitle : '')), 'lead', 'my-leads.php?lead_id='.$leadId, ['lead_id'=>$leadId,'source_type'=>$sourceType,'source_id'=>(int)($sourceId ?? 0)]);
    mjv304_admin_notify('New seller lead', $label . ($sourceTitle ? ': '.$sourceTitle : ''), 'lead', 'admin/leads.php?lead_id='.$leadId, ['lead_id'=>$leadId,'seller_user_id'=>$sellerUserId,'source_type'=>$sourceType,'source_id'=>(int)($sourceId ?? 0)]);
    return $leadId;
}

function mjv304_update_lead_status(int $leadId, string $status, int $actorId, string $actorType = 'user', string $note = ''): void {
    $status = strtolower(trim($status));
    $valid = array_keys(mjv304_status_options());
    if (!in_array($status, $valid, true)) { throw new InvalidArgumentException('Invalid lead status.'); }
    $lead = mjv304_fetch_one("SELECT * FROM seller_leads WHERE id=?", [$leadId]);
    if (!$lead) { throw new RuntimeException('Lead not found.'); }
    $oldStatus = (string)$lead['status'];
    mjv304_execute("UPDATE seller_leads SET status=?, is_read=1, last_activity_at=NOW(), updated_at=NOW() WHERE id=?", [$status, $leadId]);
    mjv304_execute("INSERT INTO seller_lead_activities (lead_id,user_id,user_type,activity_type,note,old_status,new_status,created_at) VALUES (?,?,?,?,?,?,?,NOW())", [
        $leadId, $actorId, $actorType, 'status', $note ?: ('Status changed to '.$status), $oldStatus, $status
    ]);
}

function mjv304_add_lead_note(int $leadId, int $actorId, string $actorType, string $note, ?string $followupAt = null): void {
    $note = trim($note);
    if ($note === '' && !$followupAt) { return; }
    mjv304_execute("INSERT INTO seller_lead_activities (lead_id,user_id,user_type,activity_type,note,followup_at,created_at) VALUES (?,?,?,?,?,?,NOW())", [
        $leadId, $actorId, $actorType, $followupAt ? 'followup' : 'note', $note ?: 'Follow-up date updated', $followupAt ?: null
    ]);
    $sql = "UPDATE seller_leads SET last_activity_at=NOW(), updated_at=NOW()";
    $params = [];
    if ($followupAt) { $sql .= ", followup_at=?"; $params[] = $followupAt; }
    $sql .= " WHERE id=?"; $params[] = $leadId;
    mjv304_execute($sql, $params);
}

function mjv304_lead_source_url(array $lead): string {
    $type = strtolower((string)($lead['source_type'] ?? ''));
    $id = (int)($lead['source_id'] ?? 0);
    if ($id <= 0) { return '#'; }
    if ($type === 'deal' || $type === 'deal_enquiry') { return 'deal.php?id='.$id; }
    if ($type === 'company' || $type === 'company_enquiry') { return 'company.php?id='.$id; }
    return 'listing.php?id='.$id;
}

function mjv304_query_leads(array $filters, bool $admin = false): array {
    $where = ['1=1']; $params = [];
    if (!$admin) { $where[] = 'seller_user_id=?'; $params[] = (int)($filters['seller_user_id'] ?? mjv304_current_user_id()); }
    if (!empty($filters['seller_user_id']) && $admin) { $where[] = 'seller_user_id=?'; $params[] = (int)$filters['seller_user_id']; }
    if (!empty($filters['status'])) { $where[] = 'status=?'; $params[] = $filters['status']; }
    if (!empty($filters['type'])) { $where[] = 'source_type=?'; $params[] = $filters['type']; }
    if (!empty($filters['country'])) { $where[] = 'country LIKE ?'; $params[] = '%'.$filters['country'].'%'; }
    if (!empty($filters['q'])) {
        $where[] = '(customer_name LIKE ? OR customer_email LIKE ? OR customer_phone LIKE ? OR source_title LIKE ? OR customer_message LIKE ?)';
        for ($i=0; $i<5; $i++) { $params[] = '%'.$filters['q'].'%'; }
    }
    if (!empty($filters['from'])) { $where[] = 'DATE(created_at) >= ?'; $params[] = $filters['from']; }
    if (!empty($filters['to'])) { $where[] = 'DATE(created_at) <= ?'; $params[] = $filters['to']; }
    if (!empty($filters['lead_id'])) { $where[] = 'id=?'; $params[] = (int)$filters['lead_id']; }
    $page = max(1, (int)($filters['page'] ?? 1));
    $limit = min(100, max(10, (int)($filters['limit'] ?? 25)));
    $offset = ($page - 1) * $limit;
    $whereSql = implode(' AND ', $where);
    $total = (int)mjv304_fetch_value("SELECT COUNT(*) FROM seller_leads WHERE $whereSql", $params);
    $rows = mjv304_fetch_all("SELECT * FROM seller_leads WHERE $whereSql ORDER BY created_at DESC, id DESC LIMIT $limit OFFSET $offset", $params);
    return ['rows'=>$rows,'total'=>$total,'page'=>$page,'limit'=>$limit,'pages'=>max(1, (int)ceil($total / $limit))];
}
