<?php
// POST /api/jobcards/sync_stock_cost.php
// Re-stamps unit_cost on all pending stock_transactions for a job card
// from the current value in stock_items.unit_cost
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user      = requireRole([1, 2, 5]);
$db        = getDB();
$jobCardId = (int)post('job_card_id', 0);

if (!$jobCardId) apiError('Job card ID required.', 422);

try {
    // Get all non-return transactions for this job that can be re-costed
    $stmt = $db->prepare("
        SELECT st.id, st.stock_item_id, st.unit_cost AS old_cost, si.unit_cost AS new_cost, si.name
        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')
    ");
    $stmt->execute([$jobCardId]);
    $rows = $stmt->fetchAll();

    if (empty($rows)) {
        apiSuccess(['updated' => 0], 'No stock transactions on this job card.');
    }

    $updated  = 0;
    $skipped  = 0;
    $changes  = [];

    foreach ($rows as $row) {
        $newCost = $row['new_cost'] !== null ? (float)$row['new_cost'] : null;
        $oldCost = $row['old_cost'] !== null ? (float)$row['old_cost'] : null;

        if ($newCost === null) { $skipped++; continue; } // item has no cost set — skip
        if ($newCost == $oldCost) { $skipped++; continue; } // no change needed

        $db->prepare("UPDATE stock_transactions SET unit_cost = ? WHERE id = ?")
           ->execute([$newCost, $row['id']]);

        $changes[] = [
            'item'     => $row['name'],
            'old_cost' => $oldCost,
            'new_cost' => $newCost,
        ];
        $updated++;
    }

    $msg = $updated > 0
        ? "Updated $updated transaction(s). " . ($skipped > 0 ? "$skipped already current." : '')
        : 'All costs already up to date.';

    apiSuccess(['updated' => $updated, 'skipped' => $skipped, 'changes' => $changes], $msg);

} catch (Exception $e) {
    apiError('Sync failed: ' . $e->getMessage(), 500);
}