<?php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <h3 class="mb-4 text-success">New Sale</h3>

    <form id="saleForm">

        <!-- CUSTOMER -->
        <div class="form-group">
            <label>Customer Name (optional)</label>
            <input type="text" class="form-control" name="customer_name" placeholder="Type customer name">
        </div>

        <!-- INVOICE -->
        <div class="form-group">
            <label>Invoice Number</label>
            <input type="text" class="form-control" name="invoice_no" id="invoice_no" readonly>
        </div>

        <!-- PRODUCT SEARCH -->
        <div class="card p-3 mb-4">
            <h5>Add Product</h5>

            <div class="form-group">
                <label>Search Product</label>
                <input type="text" id="productSearch" class="form-control" placeholder="Type product name...">
                <div id="productResults" class="list-group mt-1" style="display:none; max-height:180px; overflow-y:auto;"></div>
            </div>

            <div class="form-row">
                <div class="form-group col-md-4">
                    <label>Selected Product</label>
                    <input type="text" id="selectedProductName" class="form-control" readonly>
                    <input type="hidden" id="selectedProductId">
                </div>

                <div class="form-group col-md-4">
                    <label>Batch (auto)</label>
                    <input type="text" id="batchInfo" class="form-control" readonly>
                    <input type="hidden" id="batchId">
                </div>

                <div class="form-group col-md-2">
                    <label>Price</label>
                    <input type="number" class="form-control" id="unitPrice" readonly>
                </div>

                <div class="form-group col-md-2">
                    <label>Available</label>
                    <input type="text" class="form-control" id="qtyAvailable" readonly>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group col-md-3">
                    <label>Quantity</label>
                    <input type="number" id="qty" class="form-control" min="1" value="1">
                </div>

                <div class="form-group col-md-3">
                    <label>Discount</label>
                    <input type="number" id="discount" class="form-control" value="0">
                </div>

                <div class="form-group col-md-3">
                    <label>&nbsp;</label><br>
                    <button type="button" id="addItemBtn" class="btn btn-primary btn-block">Add Item</button>
                </div>
            </div>
        </div>

        <!-- ITEMS TABLE -->
        <table class="table table-bordered" id="itemsTable">
            <thead class="thead-light">
                <tr>
                    <th>Product</th>
                    <th>Batch</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Discount</th>
                    <th>Total</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>

        <!-- PAYMENT -->
        <div class="form-group">
            <label>Amount Paid</label>
            <input type="number" class="form-control" name="paid" value="0">
        </div>

        <!-- GRAND TOTAL -->
        <div class="form-group">
            <h4>Total: <span id="grandTotal">0.00</span></h4>
        </div>

        <button type="submit" class="btn btn-success btn-lg">Save Sale</button>
    </form>
</div>

<?php require_once '../includes/footer.php'; ?>

<script>
$(document).ready(function(){

    // GLOBAL VARIABLES
    let items = [];

    // PRODUCT SEARCH
    $("#productSearch").keyup(function() {
        let query = $(this).val();
        if (query.length < 2) {
            $("#productResults").hide();
            return;
        }
        $.ajax({
            url: "search_product.php",
            type: "POST",
            data: { query: query },
            success: function(data) {
                $("#productResults").html(data).show();
            }
        });
    });

    // SELECT PRODUCT FROM SEARCH
    $(document).on("click", ".product-item", function() {
        let product_id = $(this).data("id");
        let name = $(this).text();

        $("#selectedProductName").val(name);
        $("#selectedProductId").val(product_id);
        $("#productResults").hide();
        $("#productSearch").val("");

        // GET DEFAULT BATCH
        $.ajax({
            url: "get_default_batch.php",
            type: "POST",
            dataType: "json",
            data: { product_id: product_id },
            success: function(res) {
                if (res.status === "success") {
                    $("#batchInfo").val(res.batch_no + " (exp: " + res.expiry + ")");
                    $("#batchId").val(res.batch_id);
                    $("#unitPrice").val(res.price);
                    $("#qtyAvailable").val(res.qty);
                } else {
                    alert(res.message);
                }
            },
            error: function(xhr, status, error) {
                console.error(error);
                alert("Error fetching batch info.");
            }
        });
    });

    // ADD ITEM TO LIST
    $("#addItemBtn").click(function() {
        let product_id = $("#selectedProductId").val();
        let batch_id = $("#batchId").val();
        let name = $("#selectedProductName").val();
        let qty = parseInt($("#qty").val());
        let price = parseFloat($("#unitPrice").val());
        let discount = parseFloat($("#discount").val());
        let available = parseInt($("#qtyAvailable").val());

        if (!product_id || !batch_id) return alert("Select a product and batch first");
        if (qty <= 0) return alert("Enter quantity");
        if (qty > available) return alert("Not enough stock");

        // ADD ITEM TO ARRAY
        let item = { product_id, batch_id, qty, unit_price: price, discount };
        items.push(item);

        // ADD TO TABLE
        let total = (qty * price) - discount;
        if(total < 0) total = 0;

        let row = `
            <tr>
                <td>${name}</td>
                <td>${batch_id}</td>
                <td>${qty}</td>
                <td>${price.toFixed(2)}</td>
                <td>${discount.toFixed(2)}</td>
                <td class="lineTotal">${total.toFixed(2)}</td>
                <td><button type="button" class="btn btn-danger btn-sm removeItem">X</button></td>
            </tr>
        `;
        $("#itemsTable tbody").append(row);

        calculateTotal();
        clearProductFields();
    });

    // REMOVE ITEM
    $(document).on("click", ".removeItem", function() {
        let index = $(this).closest("tr").index();
        items.splice(index,1);
        $(this).closest("tr").remove();
        calculateTotal();
    });

    // CALCULATE GRAND TOTAL
    function calculateTotal(){
        let sum = 0;
        $(".lineTotal").each(function(){
            sum += parseFloat($(this).text());
        });
        $("#grandTotal").text(sum.toFixed(2));
    }

    // CLEAR PRODUCT INPUTS
    function clearProductFields(){
        $("#selectedProductName").val('');
        $("#selectedProductId").val('');
        $("#batchInfo").val('');
        $("#batchId").val('');
        $("#unitPrice").val('');
        $("#qtyAvailable").val('');
        $("#qty").val('');
        $("#discount").val('0');
    }

    // SUBMIT SALE
    $("#saleForm").submit(function(e){
        e.preventDefault();

        if(items.length === 0) return alert("Add at least one product");

        let postData = {
            invoice_no: $("input[name='invoice_no']").val(),
            customer_name: $("input[name='customer_name']").val(),
            paid: parseFloat($("input[name='paid']").val()) || 0,
            items: items
        };

        $.ajax({
            url: "save_sale.php",
            type: "POST",
            data: postData,
            dataType: "json",
            success: function(res){
                if(res.status === "success"){
                    alert(res.message);
                    window.location.reload();
                } else {
                    alert(res.message);
                }
            },
            error: function(xhr, status, error){
                console.error(xhr.responseText);
                alert("An error occurred while saving the sale.");
            }
        });
    });

});
</script>

