<?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(){

    // AUTO-GENERATE INVOICE
    $.get('ajax_get_invoice.php', function(res){
        $('#invoice_no').val(JSON.parse(res).invoice);
    });

    // PRODUCT SEARCH
    $('#productSearch').keyup(function(){
        let term = $(this).val();
        if(term.length < 2) return $('#productResults').hide();

        $.get('ajax_search_products.php', { term: term }, function(res){
            let products = JSON.parse(res);
            if(products.length===0) { $('#productResults').hide(); return; }
            let html = products.map(p => `<a href="#" class="list-group-item product-item" data-id="${p.id}">${p.text}</a>`).join('');
            $('#productResults').html(html).show();
        });
    });

    // SELECT PRODUCT
    $(document).on('click', '.product-item', function(e){
        e.preventDefault();
        let id = $(this).data('id');
        let name = $(this).text();

        $('#selectedProductName').val(name);
        $('#selectedProductId').val(id);
        $('#productResults').hide();
        $('#productSearch').val('');

        // GET DEFAULT BATCH
        $.get('get_default_batch.php', { product_id: id }, function(res){
            let data = JSON.parse(res);
            if(data.status==='success'){
                $('#batchInfo').val(data.batch_no + ' (exp:'+data.expiry+')');
                $('#batchId').val(data.batch_id);
                $('#unitPrice').val(data.price);
                $('#qtyAvailable').val(data.qty);
            } else {
                alert(data.message);
                $('#batchInfo,#batchId,#unitPrice,#qtyAvailable').val('');
            }
        });
    });

    // ADD ITEM TO TABLE
    $('#addItemBtn').click(function(){
        let pid = $('#selectedProductId').val();
        let pname = $('#selectedProductName').val();
        let batch_id = $('#batchId').val();
        let batch_info = $('#batchInfo').val();
        let qty = parseInt($('#qty').val());
        let price = parseFloat($('#unitPrice').val());
        let discount = parseFloat($('#discount').val());
        let available = parseInt($('#qtyAvailable').val());

        if(!pid) return alert('Select product first');
        if(qty<=0) return alert('Enter quantity');
        if(qty>available) return alert('Not enough stock');

        let total = (qty*price)-discount; if(total<0) total=0;

        let row = `<tr>
            <td>${pname}<input type="hidden" name="items[][product_id]" value="${pid}"></td>
            <td>${batch_info}<input type="hidden" name="items[][batch_id]" value="${batch_id}"></td>
            <td>${qty}<input type="hidden" name="items[][qty]" value="${qty}"></td>
            <td>${price}<input type="hidden" name="items[][unit_price]" value="${price}"></td>
            <td>${discount}<input type="hidden" name="items[][discount]" value="${discount}"></td>
            <td class="lineTotal">${total.toFixed(2)}</td>
            <td><button type="button" class="btn btn-sm btn-danger remove">X</button></td>
        </tr>`;

        $('#itemsTable tbody').append(row);
        calculateTotal();
    });

    // REMOVE ITEM
    $(document).on('click', '.remove', function(){
        $(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));
    }

   

});
</script>
<script>
$(document).ready(function() {

    // SAVE SALE
    $('#saleForm').submit(function(e){
        e.preventDefault();

        // DEBUG: check if event fires
        console.log("Form submitted");

        $.ajax({
            url: 'save_sale.php',
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(res) {
                console.log(res); // DEBUG: see returned JSON
                if(res.status === 'success') {
                    alert('Sale saved successfully!');
                    window.location.reload(); // ready for next sale
                } else {
                    alert(res.message);
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error:", status, error, xhr.responseText);
                alert("An error occurred while saving the sale.");
            }
        });
    });

});

</script>
