<?php
session_start();
if (!isset($_SESSION['username'])) {
    header("Location: index.php");
    exit();
}
include 'connect.php';
?>

<!DOCTYPE html>
<html>
<head>
    <title>Adjust Stock</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script src="js/jquery-3.6.0.min.js"></script>

    <!-- jQuery UI for autocomplete -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

    <style>
        /* Mobile-friendly autocomplete item */
        .ui-menu-item-wrapper {
            font-size: 14px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding: 2px 5px;
        }
    </style>
</head>
<body>

<div class="container mt-4">
    <h3>Adjust Stock</h3>
    <form action="save_adjustment.php" method="POST">
        <div class="mb-3">
            <label>Product</label>
            <input type="text" id="product_name" class="form-control" placeholder="Type product name..." required>
            <input type="hidden" name="product_id" id="product_id">
        </div>

        <div class="mb-3">
            <label>Current Stock</label>
            <input type="text" id="current_stock" class="form-control" readonly>
        </div>

        <div class="mb-3">
            <label>Adjust Quantity</label>
            <input type="number" name="adjust_qty" id="adjust_qty" class="form-control" required placeholder="e.g -3 for expired">
        </div>

        <div class="mb-3">
            <label>Reason</label>
            <input type="text" name="reason" class="form-control" placeholder="Expired / Stolen / Broken">
        </div>

        <button type="submit" class="btn btn-primary">Save Adjustment</button>
    </form>
</div>

<script>
$(document).ready(function(){
    // Autocomplete for product selection
    $("#product_name").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "autocomplete_products.php",
                type: "POST",
                dataType: "json",
                data: { term: request.term },
                success: function(data) {
                    response(data);
                }
            });
        },
        minLength: 1,
        select: function(event, ui) {
            $("#product_id").val(ui.item.id);
            $("#current_stock").val(ui.item.stock);

            // Set max allowed negative adjustment
            $("#adjust_qty").attr("min", -ui.item.stock);
        }
    }).autocomplete("instance")._renderItem = function(ul, item) {
        return $("<li>")
            .append(
                $("<div>").css({
                    display: 'flex',
                    justifyContent: 'space-between',
                    width: '100%',
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    padding: '2px 5px'
                }).html(`<span>${item.label}</span><span style="font-size:12px;color:gray;">${item.code} | Tshs. ${item.price}</span>`)
            )
            .appendTo(ul);
    };

    // Prevent typing a value that reduces stock below zero
    $("#adjust_qty").on("input", function() {
        let currentStock = parseInt($("#current_stock").val()) || 0;
        let val = parseInt($(this).val()) || 0;

        if(val < -currentStock) {
            $(this).val(-currentStock); // automatically limit
        }
    });

    // Final validation on form submit
    $("form").on("submit", function(e) {
        let currentStock = parseInt($("#current_stock").val()) || 0;
        let adjustQty = parseInt($("#adjust_qty").val()) || 0;

        if(adjustQty < 0 && Math.abs(adjustQty) > currentStock) {
            alert("Cannot reduce stock below zero! Current stock is " + currentStock);
            e.preventDefault();
        }
    });
});
</script>

</body>
</html>
