@extends('Admin.layout.app')

@section('title','New Sale')
@section('page-title','New Sale')

@section('content')

<div class="container-fluid">

<form action="{{ route('admin.sales.store') }}" method="POST">

    @csrf

    <!-- Customer Card -->
    <!-- Customer Information -->
<div class="card mb-4">

    <div class="card-header bg-primary text-white">
        <h5 class="mb-0">
            <i class="fas fa-user me-2"></i>
            Customer Information
        </h5>
    </div>

    <div class="card-body">

        <!-- Row 1 -->
        <div class="row g-3">

            <!-- Customer Name -->
            <div class="col-lg-5 position-relative">
                <label class="form-label fw-semibold">
                    Customer Name
                </label>

                <input
                    type="text"
                    name="customer_name"
                    id="customer_name"
                    class="form-control"
                    placeholder="Search or enter customer name..."
                    autocomplete="off">

                <!-- AJAX Suggestions -->
                <div id="customer-list"
                    class="list-group position-absolute w-100 shadow"
                    style="display:none; max-height:250px; overflow-y:auto; z-index:1050;">
                </div>
            </div>

            <!-- Mobile -->
            <div class="col-lg-3">
                <label class="form-label fw-semibold">
                    Mobile No.
                </label>

                <input
                    type="text"
                    name="phone"
                    id="customer_phone"
                    class="form-control"
                    placeholder="03XXXXXXXXX">
            </div>

            <!-- Previous Balance -->
            <div class="col-lg-2">
                <label class="form-label fw-semibold">
                    Previous Balance
                </label>

                <input
                    type="text"
                    class="form-control bg-light"
                    id="previous_balance"
                    value="0.00"
                    readonly>
            </div>

            <!-- Add Customer 
            <div class="col-lg-2 d-grid align-items-end">
                <label class="form-label invisible">Button</label>

                <button
                    type="button"
                    class="btn btn-success">

                    <i class="fas fa-user-plus me-1"></i>

                    New Customer

                </button>
            </div>-->

        </div>

        <!-- Row 2 -->
        <div class="row g-3 mt-1">

            <!-- Alternate Phone -->
            <div class="col-lg-4">
                <label class="form-label fw-semibold">
                    Alternate Phone
                </label>

                <input
                    type="text"
                    name="phone2"
                    class="form-control"
                    placeholder="Optional">
            </div>

            <!-- Order Date -->
            <div class="col-lg-4">
                <label class="form-label fw-semibold">
                    Order Date & Time
                </label>

                <input
                    type="datetime-local"
                    name="order_date"
                    class="form-control"
                    value="{{ now()->format('Y-m-d\TH:i') }}">
            </div>

            <!-- Customer Type -->
            <div class="col-lg-4">
                <label class="form-label fw-semibold">
                    Customer Type
                </label>

                <select
                    name="customer_type"
                    class="form-select">

                    <option value="regular">Regular</option>
                    <option value="walkin">Walk-in</option>
                    <option value="wholesale">Wholesale</option>

                </select>
            </div>

        </div>

        <!-- Row 3 -->
        <div class="row mt-3">

            <div class="col-12">

                <label class="form-label fw-semibold">
                    Address
                </label>

                <textarea
                    name="address"
                    class="form-control"
                    rows="2"
                    placeholder="Customer Address (Optional)"></textarea>

            </div>

        </div>

    </div>

</div>

    <!-- Product Card -->

    <div class="card">

        <div class="card-header bg-dark text-white">

            <h5 class="mb-0">

                <i class="fas fa-cart-shopping me-2"></i>

                Products

            </h5>

        </div>

        <div class="card-body">

            <div class="row mb-3">

                <div class="col-md-5">

                    <input
                        type="text"
                        class="form-control"
                        name="product_name"
                        id="product_name"
                        placeholder="Search Product ">

                    <div id="product-list"
                      class="list-group position-absolute w-100 shadow"
                      style="display:none; max-height:250px; overflow-y:auto; z-index:1050;">
                    </div>

                </div>
                <div class="col-md-5">

                    <textarea
                        type="text"
                        class="form-control"
                        name="product_desc"
                        id="product_desc"
                        placeholder="description"></textarea>

                </div>

                <div class="col-md-2">

                    <button type="button" id="addProduct" class="btn btn-primary w-100">
                     <i class="fas fa-plus"></i> Add
                    </button>

                </div>

            </div>

            <div class="table-responsive">

                <table class="table table-bordered align-middle">

                    <thead class="table-light">

                    <tr>

                        <th width="30%">Product</th>

                        <th width="10%">Price</th>

                        <th width="10%">Qty</th>

                        <th width="10%">Discount</th>

                        <th width="10%">Days</th>

                        <th width="15%">Total</th>

                        <th width="8%">Action</th>

                    </tr>

                    </thead>

                    <tbody id="productTableBody">
                   </tbody>

                </table>

            </div>

        </div>

    </div>

    <!-- Totals -->

    <div class="row mt-4">

        <div class="col-lg-4 ms-auto">

            <div class="card">

                <div class="card-header">

                    Invoice Summary

                </div>

                <div class="card-body">

                    <div class="d-flex justify-content-between mb-2">

                        <span>Subtotal</span>

                        <strong id="subtotal">0.00</strong>

                    </div>

                    <div class="d-flex justify-content-between mb-2">

                        <span>Discount</span>

                        <strong>0</strong>

                    </div>

                    
                     <hr>
                    <label>Cariage </label>

                    <input
                      name="cariage"
                      id="cariage"
                      type="number"
                      class="form-control mb-3 cariage">


                    <div class="d-flex justify-content-between">

                        <h5>Total</h5>

                         <h5 class="text-success">
                           Rs. <span id="grandTotal">0.00</span>
                         </h5>

                    </div>


                    <hr>

                    <label>Paid Amount</label>

                    <input
                        name="paid_amount"
                        id="paid_amount"
                        type="number"
                        class="form-control mb-3">

                    <label>Payment Method</label>

                    <select name="payment_method" id="payment_method" class="form-select mb-3">

                        <option value="Cash">Cash</option>

                        <option value="Bank">Bank</option>

                        <option value="JazzCash">JazzCash</option>

                        <option value="EasyPaisa">EasyPaisa</option>

                    </select>

                    <label>Notes</label>

                    <textarea
                        name="notes"
                        id="notes"
                        class="form-control"
                        rows="3"></textarea>

                    <div class="d-grid gap-2 mt-4">

                        <button class="btn btn-success btn-lg">

                            <i class="fas fa-floppy-disk me-2"></i>

                            Save Sale

                        </button>

                        <button class="btn btn-dark">

                            <i class="fas fa-print me-2"></i>

                            Save & Print

                        </button>

                    </div>

                </div>

            </div>

        </div>

    </div>

</form>

</div>

@endsection


@push('js')
<script>

$(function () {

    // Search by name or phone
    $(document).on('keyup', '#customer_name, #customer_phone', function () {

        let search = $(this).val();

        $('#customer_id').val('');

        if (search.length < 2) {
            $('#customer-list').hide().html('');
            return;
        }

        $.ajax({

            url: "{{ route('admin.customers.search') }}",

            type: "GET",

            data: {
                search: search
            },

            success: function (customers) {

                let html = '';

                if (customers.length > 0) {

                    $.each(customers, function (index, customer) {

                        html += `
                            <a href="javascript:void(0)"
                               class="list-group-item list-group-item-action customer-item"
                               data-id="${customer.id}"
                               data-name="${customer.name}"
                               data-phone="${customer.phone}"
                               data-phone2="${customer.phone2 ?? ''}"
                               data-address="${customer.address ?? ''}"
                               data-opening_balance="${customer.opening_balance ?? '0'}">

                                <div class="fw-bold">
                                    <i class="fas fa-user text-primary me-2"></i>
                                    ${customer.name}
                                </div>

                                <small class="text-muted">
                                    <i class="fas fa-phone me-1"></i>
                                    ${customer.phone}
                                </small>

                            </a>`;
                    });

                } else {

                    html = `
                        <div class="list-group-item text-center text-danger">
                            No customer found
                        </div>`;
                }

                $('#customer-list').html(html).show();

            },

            error: function (xhr) {
                console.log(xhr.responseText);
            }

        });

    });

    // Select customer
    $(document).on('click', '.customer-item', function () {

        $('#customer_id').val($(this).data('id'));
        $('#customer_name').val($(this).data('name'));
        $('#customer_phone').val($(this).data('phone'));
        $('#previous_balance').val($(this).data('opening_balance'));

        $('input[name="phone2"]').val($(this).data('phone2'));
        $('textarea[name="address"]').val($(this).data('address'));

        $('#customer-list').hide();

    });

    // Hide suggestion list
    $(document).on('click', function (e) {

        if (!$(e.target).closest('#customer_name,#customer_phone,#customer-list').length) {

            $('#customer-list').hide();

        }

    });

});

/*
$(function () {

    let xhr;

    $(document).on('keyup', '#product_name', function () {

        let keyword = $(this).val().trim();

        if (keyword.length < 2) {
            $('#product-list').hide().html('');
            return;
        }

        // Abort previous request
        if (xhr) {
            xhr.abort();
        }

        xhr = $.ajax({
            url: '/admin/products/search', // Change to your route
            type: 'GET',
            data: {
                keyword: keyword
            },
            success: function (response) {

                let html = '';

                if (response.length > 0) {

                    $.each(response, function (index, product) {

                        html += `
                            <a href="javascript:void(0)"
                               class="list-group-item list-group-item-action product-item"
                               data-id="${product.id}"
                               data-name="${product.name}">
                                ${product.name}
                            </a>
                        `;
                    });

                } else {

                    html = `
                        <div class="list-group-item text-muted">
                            No Product Found
                        </div>
                    `;
                }

                $('#product-list').html(html).show();
            }
        });

    });

    // Select product
    $(document).on('click', '.product-item', function () {

        $('#product_name').val($(this).data('name'));
        $('#product-list').hide();

        // If you have a hidden input
        // $('#product_id').val($(this).data('id'));

    });

    // Hide dropdown when clicking outside
    $(document).click(function (e) {

        if (!$(e.target).closest('#product_name, #product-list').length) {
            $('#product-list').hide();
        }

    });

});

*/

$(function () {

    let xhr;
    let selectedProduct = null;

    // ==========================
    // Product Search
    // ==========================
    $(document).on('keyup', '#product_name', function () {

        let keyword = $(this).val().trim();

        if (keyword.length < 2) {
            $('#product-list').hide().html('');
            return;
        }

        if (xhr) {
            xhr.abort();
        }

        xhr = $.ajax({

            url: "{{ route('admin.products.search') }}",

            type: "GET",

            data: {
                keyword: keyword
            },

            success: function (products) {

                let html = '';

                if (products.length > 0) {

                    $.each(products, function (index, product) {

                        html += `
                            <a href="javascript:void(0)"
                               class="list-group-item list-group-item-action product-item"
                               data-id="${product.id}"
                               data-name="${product.name}"
                               data-price="${product.price}"
                               data-category="${product.category}">

                                <div class="fw-bold">
                                    ${product.name}
                                </div>

                                <small>
                                    Price : Rs. ${product.price}
                                </small>

                            </a>
                        `;

                    });

                } else {

                    html = `
                        <div class="list-group-item text-danger">
                            No Product Found
                        </div>
                    `;
                }

                $('#product-list').html(html).show();

            }

        });

    });


    // ==========================
    // Select Product
    // ==========================
    $(document).on('click', '.product-item', function () {

        selectedProduct = {

            id: $(this).data('id'),
            name: $(this).data('name'),
            price: parseFloat($(this).data('price')),
             category: $(this).data('category')

        };

        $('#product_name').val(selectedProduct.name);

        $('#product-list').hide();

    });


    // ==========================
    // Add Product
    // ==========================
    $('#addProduct').click(function () {

        if (selectedProduct == null) {

            alert('Please select a product.');

            return;

        }

        // Prevent duplicate product
        let existing = $('#productTableBody tr[data-id="' + selectedProduct.id + '"]');

        if (existing.length) {

            let qty = existing.find('.qty');

            qty.val(parseInt(qty.val()) + 1).trigger('change');

            $('#product_name').val('');
            $('#product_desc').val('');

            selectedProduct = null;

            return;

        }

        let desc = $('#product_desc').val();

        let days = parseInt($('#rental_days').val()) || 1;

     // Initial total
       let rowTotal = selectedProduct.category == 2
        ? (selectedProduct.price * days)
        : selectedProduct.price;


        let row = `

        <tr data-id="${selectedProduct.id}"
        data-category="${selectedProduct.category}">

            <td>

                ${selectedProduct.name}

                <br>

                <small class="text-muted">${desc}</small>
                <input
                 type="hidden"
                 name="description[]"
                 value="${desc}">

                <input type="hidden"
                       name="product_id[]"
                       value="${selectedProduct.id}">

            </td>

            <td>

                <input type="number"
                       class="form-control price"
                       name="price[]"
                       value="${selectedProduct.price}">

            </td>

            <td>

                <input type="number"
                       class="form-control qty"
                       name="qty[]"
                       value="1">

            </td>

            <td>

                <input type="number"
                       class="form-control discount"
                       name="discount[]"
                       value="0">

            </td>
           <td>
              ${
                  selectedProduct.category == 2
                  ? `<input type="number"
                            class="form-control days"
                            name="days[]"
                            value="${days}"
                             min="1">`
                  : `<span class="text-center d-block">-</span>
                     <input type="hidden"
                            class="days"
                            name="days[]"
                            value="1">`
              }
           </td>

            <td class="row-total">
                 ${rowTotal.toFixed(2)}
           </td>

            <td class="text-center">

                <button
                    type="button"
                    class="btn btn-danger btn-sm removeRow">

                    <i class="fas fa-trash"></i>

                </button>

            </td>

        </tr>

        `;

        $('#productTableBody').append(row);

        calculateGrandTotal();

        $('#product_name').val('');
        $('#product_desc').val('');

        selectedProduct = null;

    });


    // ==========================
    // Calculate Row Total
    // ==========================
   $(document).on('keyup change', '.price,.qty,.days,.discount', function () {

    let row = $(this).closest('tr');

    let category = row.data('category');

    let price = parseFloat(row.find('.price').val()) || 0;
    let qty = parseFloat(row.find('.qty').val()) || 0;
    let days = parseFloat(row.find('.days').val()) || 1;
    let discount = parseFloat(row.find('.discount').val()) || 0;

    let total;

    if (category == 2) {
        total = (price * qty * days) - discount;
    } else {
        total = (price * qty) - discount;
    }

    row.find('.row-total').text(total.toFixed(2));

    calculateGrandTotal();
});


    // ==========================
    // Remove Product
    // ==========================
    $(document).on('click', '.removeRow', function () {

        $(this).closest('tr').remove();

        calculateGrandTotal();

    });

   $(document).on('keyup change', '#cariage', function () {
    calculateGrandTotal();
});



    // ==========================
    // Grand Total
    // ==========================
    function calculateGrandTotal() {

        let subtotal = 0;

        $('#productTableBody tr').each(function () {

            subtotal += parseFloat($(this).find('.row-total').text()) || 0;

        });

        let carriage = parseFloat($('#cariage').val()) || 0;

            let grandTotal = subtotal + carriage;


        $('#subtotal').text(subtotal.toFixed(2));

        $('#grandTotal').text(grandTotal.toFixed(2));

    }

   


    // ==========================
    // Hide Search
    // ==========================
    $(document).click(function (e) {

        if (!$(e.target).closest('#product_name,#product-list').length) {

            $('#product-list').hide();

        }

    });

});

</script>
@endpush
