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

$period = trim($_GET['period'] ?? 'month'); // today | week | month

$today       = date('Y-m-d');
$week_start  = date('Y-m-d', strtotime('monday this week'));
$month_start = date('Y-m-01');

$from = match($period) {
    'today' => $today,
    'week'  => $week_start,
    default => $month_start,
};

$rows = $db->rows(
    "SELECT t.datetime_created, t.order_no, t.stock_no, t.item_name, t.quantity,
            s.stock_type_id,
            st.name AS type_name,
            bs.team_assigned_id,
            tm.name AS team_name
     FROM   stock_trans t
     LEFT JOIN stock      s  ON s.stock_no      = t.stock_no
     LEFT JOIN stock_types st ON st.record_id   = s.stock_type_id
     LEFT JOIN book_stock bs  ON bs.order_no    = t.order_no
     LEFT JOIN teams      tm  ON tm.record_id   = bs.team_assigned_id
     WHERE  t.status = 'USED'
       AND  DATE(t.datetime_created) >= ?
     ORDER BY t.datetime_created DESC",
    [$from]
);

Response::ok(['rows' => $rows, 'period' => $period, 'from' => $from]);