<?php
// ─── GET /api/stock/list.php ─────────────────────────────────────────────
// Returns all stock items with live balance calculated from stock_trans.
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   = trim($_GET['type']   ?? '');
$search = trim($_GET['search'] ?? '');

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

if ($type !== '')   { $where[] = 's.stock_type_id = ?'; $params[] = (int) $type; }
if ($search !== '') { $where[] = '(s.item_name LIKE ? OR s.stock_no LIKE ?)';
                      $params[] = "%$search%"; $params[] = "%$search%"; }

$rows = $db->rows(
    "SELECT s.*,
            st.name AS type_name,
            sp.name AS supplier_name,
            COALESCE((
              SELECT SUM(CASE
                WHEN t.status IN ('BOOKED OUT','USED') THEN -t.quantity
                ELSE t.quantity
              END)
              FROM stock_trans t
              WHERE t.stock_no = s.stock_no
            ), 0) AS balance
     FROM   stock s
     LEFT JOIN stock_types st ON st.record_id = s.stock_type_id
     LEFT JOIN suppliers   sp ON sp.record_id = s.supplier_id
     WHERE  " . implode(' AND ', $where) . "
     ORDER BY st.name, s.item_name",
    $params
);

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

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