<?php
// POST /api/stock/issue.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireRole([1, 4]);
$db   = getDB();

$stockItemId     = (int)post('stock_item_id', 0);
$fromLocationId  = (int)post('from_location_id', 0);
$quantity        = (float)post('quantity', 0);
$issueTo         = post('issue_to', ''); // jobcard, project, person

if (!$stockItemId || !$fromLocationId || $quantity <= 0) apiError('Stock item, location and quantity required.', 422);

// Check available quantity
$stmt = $db->prepare("SELECT quantity FROM stock_inventory WHERE stock_item_id = ? AND location_id = ?");
$stmt->execute([$stockItemId, $fromLocationId]);
$inv = $stmt->fetch();

if (!$inv || $inv['quantity'] < $quantity) {
    apiError(sprintf('Insufficient stock. Available: %s', $inv ? $inv['quantity'] : 0), 422);
}

// Deduct
$db->prepare("UPDATE stock_inventory SET quantity = quantity - ? WHERE stock_item_id = ? AND location_id = ?")
   ->execute([$quantity, $stockItemId, $fromLocationId]);

$typeMap = ['jobcard' => 'issue_jobcard', 'project' => 'issue_project', 'person' => 'issue_person'];
$txType  = $typeMap[$issueTo] ?? 'issue_jobcard';

$db->prepare("
    INSERT INTO stock_transactions (stock_item_id, transaction_type, quantity, from_location, job_card_id, project_id, employee_id, notes, user_id)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
")->execute([
    $stockItemId, $txType, -$quantity, $fromLocationId,
    post('job_card_id') ?: null,
    post('project_id') ?: null,
    post('employee_id') ?: null,
    post('notes'),
    $user['id']
]);

apiSuccess([], 'Stock issued.');
