<?php
// ─── GET /api/leads/list.php ─────────────────────────────────────────────
// Returns work_requests rows with optional filters.
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

Auth::require();
$db = DB::get();

$jc_no  = trim($_GET['jc_no']  ?? '');
$area   = trim($_GET['area']   ?? '');
$type   = trim($_GET['type']   ?? '');   // LEAD | JOBCARD | '' (all)
$status = trim($_GET['status'] ?? '');

$where  = ['1=1'];
$params = [];

if ($jc_no !== '') {
    $where[]  = 'wr.jc_no = ?';
    $params[] = (int) $jc_no;
}
if ($area !== '') {
    $where[]  = 'wr.address LIKE ?';
    $params[] = '%' . $area . '%';
}
if ($type !== '') {
    $where[]  = 'wr.type = ?';
    $params[] = strtoupper($type);
}
if ($status !== '') {
    $where[]  = 'wr.status = ?';
    $params[] = $status;
}

$sql = "SELECT wr.record_id, wr.jc_no, wr.type, wr.contact_number,
               wr.other_number, wr.alternate_number, wr.address,
               wr.additional_notes, wr.status, wr.team_id,
               wr.date_created,
               u.username   AS created_by,
               t.name       AS team_name
        FROM   work_requests wr
        LEFT JOIN users u ON u.record_id = wr.user_id
        LEFT JOIN teams t ON t.record_id = wr.team_id
        WHERE  " . implode(' AND ', $where) . "
        ORDER BY wr.jc_no DESC
        LIMIT 200";

$rows = $db->rows($sql, $params);

Response::ok($rows);