<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

/**
 * Pagination
 */
$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = max(1, min(100, (int)($_GET['limit'] ?? 20)));
$offset = ($page - 1) * $limit;

/**
 * Filters
 */
$status         = $_GET['status'] ?? null;
$priority       = $_GET['priority'] ?? null;
$productPurpose = $_GET['product_purpose'] ?? null;
$sourceType     = $_GET['source_type'] ?? null;
$assignedTo     = $_GET['assigned_to'] ?? null;
$dateFrom       = $_GET['date_from'] ?? null;
$dateTo         = $_GET['date_to'] ?? null;
$search         = $_GET['search'] ?? null;

$where  = [];
$params = [];

/**
 * Apply filters
 */
if ($status) {
    $where[] = "l.status = :status";
    $params['status'] = $status;
}

if ($priority) {
    $where[] = "l.priority = :priority";
    $params['priority'] = $priority;
}

if ($productPurpose) {
    $where[] = "l.product_purpose = :product_purpose";
    $params['product_purpose'] = $productPurpose;
}

if ($sourceType) {
    $where[] = "l.source_type = :source_type";
    $params['source_type'] = $sourceType;
}

if ($assignedTo) {
    $where[] = "l.assigned_to = :assigned_to";
    $params['assigned_to'] = (int)$assignedTo;
}

if ($dateFrom) {
    $where[] = "DATE(l.created_at) >= :date_from";
    $params['date_from'] = $dateFrom;
}

if ($dateTo) {
    $where[] = "DATE(l.created_at) <= :date_to";
    $params['date_to'] = $dateTo;
}

if ($search) {
    $where[] = "(l.name LIKE :search OR l.phone LIKE :search OR l.email LIKE :search)";
    $params['search'] = '%' . trim($search) . '%';
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

/**
 * Count total
 */
$countSql = "SELECT COUNT(*) FROM leads l $whereSql";
$stmt = $db->prepare($countSql);
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();

/**
 * Fetch FULL lead data
 */
$sql = "
SELECT
    l.id,
    l.name,
    l.phone,
    l.email,
    l.pincode,
    l.city,
    l.state,
    l.message,

    l.product_purpose,

    l.status,
    l.priority,
    l.assigned_to,
    l.assigned_at,

    l.source_type,
    l.source_id,
    l.source_slug,
    l.source_url,
    l.referrer_url,

    l.utm_source,
    l.utm_medium,
    l.utm_campaign,

    l.ip_address,
    l.user_agent,

    l.created_at,
    l.updated_at,

    e.first_name AS assigned_first_name,
    e.last_name  AS assigned_last_name

FROM leads l
LEFT JOIN employees e ON e.id = l.assigned_to
$whereSql
ORDER BY l.created_at DESC
LIMIT :limit OFFSET :offset
";

$stmt = $db->prepare($sql);

/**
 * Bind filters
 */
foreach ($params as $key => $value) {
    $stmt->bindValue(':' . $key, $value);
}

$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);

$stmt->execute();
$leads = $stmt->fetchAll();

/**
 * Response
 */
Response::success('Leads fetched successfully', [
    'list' => $leads,
    'pagination' => [
        'total' => $total,
        'page'  => $page,
        'limit'=> $limit,
        'pages'=> (int)ceil($total / $limit)
    ]
]);
