<?php
// ─── GET /api/assets/list.php ────────────────────────────────────────────
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();

$type_id = trim($_GET['type_id'] ?? '');
$status  = trim($_GET['status']  ?? '');
$search  = trim($_GET['search']  ?? '');

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

if ($type_id) { $where[] = 'a.asset_type_id = ?'; $params[] = (int)$type_id; }
if ($status)  { $where[] = 'a.status = ?';         $params[] = $status; }
if ($search)  { $where[] = 'a.name LIKE ?';         $params[] = "%$search%"; }

$rows = $db->rows(
    "SELECT a.*, at.name AS type_name,
            t.name AS team_name
     FROM   assets a
     LEFT JOIN asset_type at ON at.record_id = a.asset_type_id
     LEFT JOIN teams       t  ON FIND_IN_SET(a.name, REPLACE(t.assigned_assets, ', ', ','))
     WHERE  " . implode(' AND ', $where) . "
     ORDER BY at.name, a.name",
    $params
);

// Also return types for filter
$types = $db->rows("SELECT * FROM asset_type ORDER BY name");

Response::ok(['assets' => $rows, 'types' => $types]);