<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user  = requireRole([1, 2, 4, 5]);
$db    = getDB();

// ── Setting checks ────────────────────────────────────────────
function getStockSetting(PDO $db, string $key, string $default = '0'): string {
    $s = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = ? LIMIT 1");
    $s->execute([$key]);
    $r = $s->fetchColumn();
    return $r !== false ? $r : $default;
}
// Slip required?
if ((int)getStockSetting($db, 'stock_slip_required', '0') === 1) {
    $slipIdCheck = post('slip_id');
    if (!$slipIdCheck || (int)$slipIdCheck <= 0) {
        apiError('A linked slip is required to book stock in. Please attach a slip first.', 422);
    }
}

// lines arrives as JSON string from URLSearchParams
$rawLines = $_POST['lines'] ?? '';
if (is_string($rawLines) && strlen($rawLines) > 0) {
    $lines = json_decode($rawLines, true) ?: [];
} elseif (is_array($rawLines)) {
    $lines = $rawLines;
} else {
    $lines = [];
}
if (empty($lines)) apiError('No items provided.', 422);

$refNo  = post('reference_no', '') ?: 'RCV-' . date('YmdHis');
$notes  = post('notes', '');
$slipId = post('slip_id') !== '' ? (int)post('slip_id') : null;

// Get or create default location
function getDefaultLocation($db): int {
    $loc = $db->query("SELECT id FROM stock_locations WHERE is_active=1 ORDER BY id LIMIT 1")->fetch();
    if (!$loc) {
        $db->exec("INSERT INTO stock_locations (name, description) VALUES ('Main Warehouse', 'Default storage location')");
        return (int)$db->lastInsertId();
    }
    return (int)$loc['id'];
}

try {
    $locId = getDefaultLocation($db);
    $db->beginTransaction();

    foreach ($lines as $line) {
        $itemId   = (int)($line['item_id'] ?? 0);
        $qty      = (float)($line['qty'] ?? 0);
        $unitCost = isset($line['unit_cost']) && $line['unit_cost'] !== '' ? (float)$line['unit_cost'] : null;
        $supplier = $line['supplier'] ?? '';
        if (!$itemId || $qty <= 0) continue;

        // Update item unit cost if provided
        if ($unitCost !== null && $unitCost > 0) {
            $db->prepare("UPDATE stock_items SET unit_cost=? WHERE id=?")->execute([$unitCost, $itemId]);
        } else {
            $ucRow = $db->prepare("SELECT unit_cost FROM stock_items WHERE id=?")->execute([$itemId]);
            $uc    = $db->query("SELECT unit_cost FROM stock_items WHERE id=$itemId")->fetch();
            $unitCost = $uc ? (float)$uc['unit_cost'] : null;
        }

        // Record transaction — use minimal columns that always exist
        $db->prepare("
            INSERT INTO stock_transactions
                (stock_item_id, transaction_type, quantity, unit_cost, user_id, reference_no, notes, transaction_date)
            VALUES (?, 'receive', ?, ?, ?, ?, ?, NOW())
        ")->execute([$itemId, $qty, $unitCost, $user['id'], $refNo, $notes]);
        $txId = (int)$db->lastInsertId();
        // Attach slip_id and supplier if those columns exist (added in migration_v2)
        try {
            if ($slipId)    $db->prepare("UPDATE stock_transactions SET slip_id=?    WHERE id=?")->execute([$slipId, $txId]);
            if ($supplier)  $db->prepare("UPDATE stock_transactions SET supplier=?   WHERE id=?")->execute([$supplier, $txId]);
        } catch (Exception $ignored) {}

        // Upsert inventory
        $check = $db->prepare("SELECT id FROM stock_inventory WHERE stock_item_id=? AND location_id=?");
        $check->execute([$itemId, $locId]);
        if ($check->fetch()) {
            $db->prepare("UPDATE stock_inventory SET quantity = quantity + ? WHERE stock_item_id=? AND location_id=?")
               ->execute([$qty, $itemId, $locId]);
        } else {
            $db->prepare("INSERT INTO stock_inventory (stock_item_id, location_id, quantity) VALUES (?,?,?)")
               ->execute([$itemId, $locId, $qty]);
        }
    }

    $db->commit();
    apiSuccess(['reference' => $refNo], 'Stock received.');

} catch (PDOException $e) {
    if ($db->inTransaction()) $db->rollBack();
    apiError('Database error: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    apiError('Error: ' . $e->getMessage(), 500);
}