<?php
// POST /api/stock/jobcard_items.php
// Returns items currently booked out to a job card (issues minus prior returns).
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user = requireRole([1, 2, 3, 4, 5]);
$db   = getDB();

$jobCardId = (int)post('job_card_id', 0);
if (!$jobCardId) apiError('Job card ID required.', 422);

$stmt = $db->prepare("
    SELECT
        st.stock_item_id                                                     AS item_id,
        si.name                                                              AS item_name,
        si.sku,
        si.unit,
        si.unit_cost,
        COALESCE(SUM(CASE WHEN st.transaction_type = 'issue_jobcard' THEN st.quantity ELSE 0 END), 0)
      - COALESCE(SUM(CASE WHEN st.transaction_type = 'return'         THEN st.quantity ELSE 0 END), 0)
                                                                             AS net_issued
    FROM stock_transactions st
    JOIN stock_items si ON si.id = st.stock_item_id
    WHERE st.job_card_id = ?
      AND st.transaction_type IN ('issue_jobcard', 'return')
    GROUP BY st.stock_item_id, si.name, si.sku, si.unit, si.unit_cost
    HAVING net_issued > 0.0001
    ORDER BY si.name
");
$stmt->execute([$jobCardId]);
$items = $stmt->fetchAll();

apiSuccess(['items' => $items]);