<?php
$pageTitle = 'Stock In';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../auth/session.php';

require_login();
require_permission($pdo, 'inventory.manage');

$branchId = current_branch_id();
$userId = (int)($_SESSION['user_id'] ?? 0);
$errors = [];
$old = [
    'product_id' => '',
    'qty' => '',
    'remarks' => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $old = [
        'product_id' => trim($_POST['product_id'] ?? ''),
        'qty' => trim($_POST['qty'] ?? ''),
        'remarks' => trim($_POST['remarks'] ?? ''),
    ];

    if ($old['product_id'] === '' || !ctype_digit($old['product_id'])) {
        $errors[] = 'Please select a valid product.';
    }

    if ($old['qty'] === '' || filter_var($old['qty'], FILTER_VALIDATE_INT) === false || (int)$old['qty'] <= 0) {
        $errors[] = 'Quantity must be greater than zero.';
    }

    if (!$errors) {
        $productId = (int)$old['product_id'];
        $qty = (int)$old['qty'];
        $remarks = $old['remarks'] !== '' ? $old['remarks'] : 'Stock in';

        try {
            $pdo->beginTransaction();

            $productStmt = $pdo->prepare('SELECT id FROM products WHERE branch_id = ? AND id = ? FOR UPDATE');
            $productStmt->execute([$branchId, $productId]);

            if (!$productStmt->fetchColumn()) {
                throw new RuntimeException('Selected product was not found for this branch.');
            }

            $updateStmt = $pdo->prepare('UPDATE products SET stock_qty = stock_qty + ? WHERE branch_id = ? AND id = ?');
            $updateStmt->execute([$qty, $branchId, $productId]);

            $movementStmt = $pdo->prepare('
                INSERT INTO inventory_movements(branch_id, product_id, type, qty, remarks, user_id)
                VALUES(?, ?, "stock_in", ?, ?, ?)
            ');
            $movementStmt->execute([$branchId, $productId, $qty, $remarks, $userId]);

            $pdo->commit();
            redirect_to('inventory/index.php?stocked=1');
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $errors[] = 'Stock-in could not be saved. ' . $e->getMessage();
        }
    }
}

$productsStmt = $pdo->prepare('
    SELECT id, name, sku, barcode, stock_qty
    FROM products
    WHERE branch_id = ?
    ORDER BY name
');
$productsStmt->execute([$branchId]);
$products = $productsStmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-3">
    <div>
        <h4 class="mb-0">Stock In</h4>
        <small class="text-muted">Increase stock and log the inventory movement.</small>
    </div>
    <a class="btn btn-outline-secondary" href="<?= app_url('inventory/index.php') ?>">
        <i class="bi bi-arrow-left"></i> Back to Inventory
    </a>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <strong>Stock-in was not saved.</strong>
        <ul class="mb-0">
            <?php foreach ($errors as $error): ?>
                <li><?= htmlspecialchars($error) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="table-card">
    <?php if ($products): ?>
        <form method="post" action="<?= app_url('inventory/stock_in.php') ?>">
            <div class="mb-3">
                <label class="form-label">Search Product</label>
                <input class="form-control" id="productSearch" type="search" placeholder="Search by name, SKU, or barcode">
            </div>

            <div class="mb-3">
                <label class="form-label">Product</label>
                <select name="product_id" id="productSelect" class="form-select" required>
                    <option value="">Select product</option>
                    <?php foreach ($products as $product): ?>
                        <?php $searchText = strtolower($product['name'] . ' ' . ($product['sku'] ?? '') . ' ' . ($product['barcode'] ?? '')); ?>
                        <option
                            value="<?= (int)$product['id'] ?>"
                            data-search="<?= htmlspecialchars($searchText) ?>"
                            <?= $old['product_id'] === (string)$product['id'] ? 'selected' : '' ?>
                        >
                            <?= htmlspecialchars($product['name']) ?>
                            <?= $product['sku'] ? ' · SKU: ' . htmlspecialchars($product['sku']) : '' ?>
                            <?= $product['barcode'] ? ' · Barcode: ' . htmlspecialchars($product['barcode']) : '' ?>
                            · Current: <?= (int)$product['stock_qty'] ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="mb-3">
                <label class="form-label">Quantity</label>
                <input class="form-control" type="number" name="qty" min="1" value="<?= htmlspecialchars($old['qty']) ?>" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Reason / Reference</label>
                <input class="form-control" name="remarks" maxlength="255" value="<?= htmlspecialchars($old['remarks']) ?>" placeholder="Supplier delivery, invoice number, or note">
            </div>

            <button class="btn btn-primary">
                <i class="bi bi-save"></i> Save Stock In
            </button>
        </form>
    <?php else: ?>
        <div class="text-center text-muted py-4">
            No products found for this branch.
        </div>
    <?php endif; ?>
</div>

<script>
document.getElementById('productSearch')?.addEventListener('input', function (event) {
    const query = event.target.value.toLowerCase();
    document.querySelectorAll('#productSelect option[data-search]').forEach(function (option) {
        option.hidden = !option.dataset.search.includes(query);
    });
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
