

<?php $__env->startSection('title','Update Order'); ?>
<?php $__env->startSection('page-title','Update Order'); ?>

<?php $__env->startSection('content'); ?>

<div class="container-fluid">

<form action="<?php echo e(route('admin.orders.update',$order->id)); ?>" method="POST">

    <?php echo csrf_field(); ?>
    

    <input type="hidden"
           name="customer_id"
           id="customer_id"
           value="<?php echo e($order->customer_id); ?>">

    <!-- ==========================================
        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 -->

                <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"
                        autocomplete="off"
                        placeholder="Search customer..."
                        value="<?php echo e(old('customer_name',$order->customer->name ?? '')); ?>">

                    <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>
                    <input
                        type="text"
                        name="customer_name_urdu"
                        id="customer_name_urdu"
                        class="form-control"
                        autocomplete="off"
                        placeholder="Search customer..."
                        value="<?php echo e(old('customer_name',$order->customer->urdu_name ?? '')); ?>">

                </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"
                        value="<?php echo e(old('phone',$order->customer->phone ?? '')); ?>">

                </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"
                        readonly
                        value="Rs. <?php echo e(number_format($order->customer->opening_balance ?? 0,2)); ?>">

                </div>

                <!-- New 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"
                        value="<?php echo e(old('phone2',$order->customer->phone2 ?? '')); ?>">

                </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="<?php echo e(old('order_date', optional($order->order_date)->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"
                            <?php echo e(old('customer_type',$order->customer_type)=='regular' ? 'selected' : ''); ?>>
                            Regular
                        </option>

                        <option value="walkin"
                            <?php echo e(old('customer_type',$order->customer_type)=='walkin' ? 'selected' : ''); ?>>
                            Walk-in
                        </option>

                        <option value="wholesale"
                            <?php echo e(old('customer_type',$order->customer_type)=='wholesale' ? 'selected' : ''); ?>>
                            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"><?php echo e(old('address',$order->customer->address ?? '')); ?></textarea>

                    <textarea
                        name="address_urdu"
                        class="form-control"
                        rows="2"
                        placeholder="Customer Address"><?php echo e(old('address',$order->customer->urdu_address ?? '')); ?></textarea>

                </div>

            </div>

        </div>

    </div>


  
   

        <!-- ==========================================
        PRODUCTS
    =========================================== -->

    <div class="card">

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

            <h5 class="mb-0">

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

                Order Items

            </h5>

        </div>

        <div class="card-body">

            <div class="row mb-3">

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

                    <input
                        type="text"
                        class="form-control"
                        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
                        id="product_desc"
                        class="form-control"
                        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="12%">Price</th>

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

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

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

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

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

                    </tr>

                    </thead>

                    <tbody id="productTableBody">

                    <?php $__empty_1 = true; $__currentLoopData = $order->details; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $detail): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>

                        <tr data-id="<?php echo e($detail->product_id); ?>"
                        data-category="<?php echo e($detail->product->category); ?>">

                            <td>

                                <strong>

                                    <?php echo e($detail->product->name); ?>


                                </strong>

                               <div class="mt-2">

                                    <textarea
                                        name="description[]"
                                        class="form-control form-control-sm"
                                        rows="2"
                                        placeholder="Product Description"><?php echo e(old('description.' . $loop->index, $detail->description)); ?></textarea>
                                
                                </div>

                                <input
                                    type="hidden"
                                    name="product_id[]"
                                    value="<?php echo e($detail->product_id); ?>">

                               

                            </td>

                            <td>

                                <input
                                    type="number"
                                    step="0.01"
                                    class="form-control price"
                                    name="price[]"
                                    value="<?php echo e($detail->price); ?>">

                            </td>

                            <td>

                                <input
                                    type="number"
                                    class="form-control qty"
                                    name="qty[]"
                                    value="<?php echo e($detail->qty); ?>">

                            </td>

                            <td>

                                <input
                                    type="number"
                                    step="0.01"
                                    class="form-control discount"
                                    name="discount[]"
                                    value="<?php echo e($detail->discount); ?>">

                            </td>
                            
                             <td >
                             <?php if( $detail->product->category ==2  ): ?>
                                <input
                                    type="number"
                                    class="form-control days"
                                    name="days[]"
                                    value="<?php echo e($detail->days); ?>">
                             <?php else: ?>
                             <input
                                    type="number"
                                    class="form-control days"
                                    name="days[]"
                                    value="-"
                                    readonly>
                             <?php endif; ?>
                            </td>
                            


                            <?php if( $detail->product->category ==2  ): ?>
                              <?php
                              $pri=$detail->price * $detail->qty
                              ?>
                             <td class="row-total">
                                <?php echo e(number_format(($pri * $detail->days) - $detail->discount,2)); ?>

                            </td>

                            <?php else: ?>
                            <td class="row-total">
                                <?php echo e(number_format(($detail->price * $detail->qty) - $detail->discount,2)); ?>

                            </td>

                            <?php endif; ?>

                            <td class="text-center">

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

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

                                </button>

                            </td>

                        </tr>

                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>

                        <tr>

                            <td colspan="6" class="text-center text-muted">

                                No products found.

                            </td>

                        </tr>

                    <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>
    
        <!-- ==========================================
        ORDER SUMMARY
    =========================================== -->

    <div class="row mt-4">

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

            <div class="card">

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

                    <h5 class="mb-0">

                        <i class="fas fa-file-invoice-dollar me-2"></i>

                        Order Summary

                    </h5>

                </div>

                <div class="card-body">

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

                        <span>Subtotals</span>

                        <strong>
                            Rs.
                            <span id="subtotal" name="subtotal">
                                <?php echo e($order->subtotal); ?>

                            </span>
                        </strong>

                        <input
                            type="hidden"
                            name="subtotal_amount"
                            id="subtotal_amount"
                            class="form-control"
                            value="<?php echo e(($order->subtotal)); ?>">

                        <input
                            type="hidden"
                            name="gtotal_amount_pre"
                            id="gtotal_amount_pre"
                            class="form-control"
                            value="<?php echo e(($order->grand_total)); ?>">

                    </div>

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

                        <span>Discount</span>

                        <strong>

                            Rs.
                            <span id="totalDiscount">

                                <?php echo e($order->discount ?? 0); ?>


                            </span>

                        </strong>

                    </div>

                    <hr>
                     
                    <label>Cariage </label>

                    <input
                      name="cariage"
                      id="cariage"
                      type="number"
                      class="form-control mb-3 cariage"
                      value="<?php echo e(($order->carriage)); ?>">

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

                        <h5>Grand Total</h5>
                         <h5 class="text-success">
                           Rs. <span id="grandTotal" name="grandTotal"><?php echo e($order->grand_total); ?></span>
                         </h5>


                    </div>

                    

                    <!-- Paid Amount -->

                    <div class="mb-3">

                        <label class="form-label">

                            Paid Amount

                        </label>


                        <input
                            type="number"
                            step="0.01"
                            name="paid_amount"
                            id="paid_amount"
                            class="form-control"
                            value="<?php echo e(old('paid_amount',$order->paid_amount)); ?>">

                    </div>

                    <!-- Remaining -->

                    <div class="mb-3">

                        <label class="form-label">

                            Remaining Amount

                        </label>

                        <input
                            type="text"
                            id="remaining_amount"
                            name="remaining_amount"
                            class="form-control bg-light"
                            readonly
                            value="<?php echo e($order->grand_total-$order->paid_amount); ?>">

                    </div>

                    <!-- Payment Method -->

                    <div class="mb-3">

                        <label class="form-label">

                            Payment Method

                        </label>

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

                            <option value="Cash"
                                <?php echo e($order->payment_method=='Cash'?'selected':''); ?>>
                                Cash
                            </option>

                            <option value="Bank"
                                <?php echo e($order->payment_method=='Bank'?'selected':''); ?>>
                                Bank
                            </option>

                            <option value="JazzCash"
                                <?php echo e($order->payment_method=='JazzCash'?'selected':''); ?>>
                                JazzCash
                            </option>

                            <option value="EasyPaisa"
                                <?php echo e($order->payment_method=='EasyPaisa'?'selected':''); ?>>
                                EasyPaisa
                            </option>

                            <option value="Cheque"
                                <?php echo e($order->payment_method=='Cheque'?'selected':''); ?>>
                                Cheque
                            </option>

                        </select>

                    </div>

                    <!-- Payment Status -->

                    <div class="mb-3">

                        <label class="form-label">

                            Payment Status

                        </label>

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

                            <option value="Pending"
                                <?php echo e($order->payment_status=='Pending'?'selected':''); ?>>
                                Pending
                            </option>

                            <option value="Partially-Paid"
                                <?php echo e($order->payment_status=='Partially-Paid'?'selected':''); ?>>
                                Partially Paid
                            </option>

                            <option value="Paid"
                                <?php echo e($order->payment_status=='Paid'?'selected':''); ?>>
                                Paid
                            </option>

                        </select>

                    </div>

                    <!-- Order Status -->

                    <div class="mb-3">

                        <label class="form-label">

                            Order Status

                        </label>

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

                            <option value="Pending"
                                <?php echo e($order->delivery_status=='Pending'?'selected':''); ?>>
                                Pending
                            </option>

                            <option value="Confirmed"
                                <?php echo e($order->delivery_status=='Confirmed'?'selected':''); ?>>
                                Confirmed
                            </option>

                            <option value="Delivered"
                                <?php echo e($order->delivery_status=='Delivered'?'selected':''); ?>>
                                Delivered
                            </option>

                            <option value="Completed"
                                <?php echo e($order->delivery_status=='Completed'?'selected':''); ?>>
                                Completed
                            </option>

                            <option value="Cancelled"
                                <?php echo e($order->delivery_status=='Cancelled'?'selected':''); ?>>
                                Cancelled
                            </option>

                        </select>

                    </div>

                    <!-- Equipment -->

                    <div class="form-check mb-3">

                        <input
                            class="form-check-input"
                            type="checkbox"
                            name="equipment_returned"
                            value="1"
                            <?php echo e($order->equipment_returned ? 'checked' : '1'); ?>>

                        <label class="form-check-label">

                            All equipment returned

                        </label>

                    </div>

                    <!-- Notes -->

                    <div class="mb-3">

                        <label class="form-label">

                            Notes

                        </label>

                        <textarea
                            name="notes"
                            rows="4"
                            class="form-control"><?php echo e(old('notes',$order->notes)); ?></textarea>

                    </div>

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

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

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

                            Update Order

                        </button>

                        <button
                            type="submit"
                            name="print"
                            value="1"
                            class="btn btn-dark">

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

                            Update & Print

                        </button>

                        <a href=""
                           class="btn btn-secondary">

                            Cancel

                        </a>

                    </div>

                </div>

            </div>

        </div>

    </div>

</form>

</div>

<?php $__env->stopSection(); ?>

<?php $__env->startPush('js'); ?>
<script>

$(function () {

    let customerXHR;
    let productXHR;
    let selectedProduct = null;

    //=====================================================
    // CUSTOMER SEARCH
    //=====================================================

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

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

        if (search.length < 2) {

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

            return;

        }

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

        customerXHR = $.ajax({

            url: "<?php echo e(route('admin.customers.search')); ?>",

            type: "GET",

            data:{
                search:search
            },

            success:function(customers){

                let html='';

                if(customers.length){

                    $.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 ?? ''}">

                            <strong>${customer.name}</strong>

                            <br>

                            <small>${customer.phone}</small>

                        </a>

                        `;

                    });

                }else{

                    html='<div class="list-group-item text-danger">No Customer Found</div>';

                }

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

            }

        });

    });


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

        $('#customer_id').val($(this).data('id'));

        $('#customer_name').val($(this).data('name'));

        $('#customer_phone').val($(this).data('phone'));

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

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

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

    });

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


    //=====================================================
    // PRODUCT SEARCH
    //=====================================================

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

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

        if(keyword.length<2){

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

            return;

        }

        if(productXHR){

            productXHR.abort();

        }

        productXHR=$.ajax({

            url:"<?php echo e(route('admin.products.search')); ?>",

            type:"GET",

            data:{
                keyword:keyword
            },

            success:function(products){

                let html='';

                if(products.length){

                    $.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}">

                            <strong>${product.name}</strong>

                            <br>

                            <small>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;

        }

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

        if(existing.length){

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

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

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

            selectedProduct=null;

            return;

        }

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

        let row=`

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

            <td>

                <strong>${selectedProduct.name}</strong>

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

                <textarea
                    class="form-control form-control-sm mt-2"
                    name="description[]"
                    rows="2">${desc}</textarea>

            </td>

            <td>

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

            </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.00">

            </td>

             <td>

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

    </td>

            <td class="row-total">

                ${selectedProduct.price.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);

        calculateTotals();

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

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

        selectedProduct=null;

    });



    //=====================================================
    // REMOVE PRODUCT
    //=====================================================

    $(document).on('click','.removeRow',function(){

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

        calculateTotals();

    });



    //=====================================================
    // PRICE QTY DISCOUNT
    //=====================================================

   $(document).on('keyup change','.price,.qty,.days,.discount',function(){

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

    let category = Number(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;
    }

    if (total < 0) {
        total = 0;
    }

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

    calculateTotals();

});




    //=====================================================
    // PAID AMOUNT
    //=====================================================

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

        calculateTotals();

    });



    //=====================================================
    // CALCULATE TOTALS
    //=====================================================

    function calculateTotals(){

        let subtotal=0;

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

           let value = $(this).find('.row-total').text().replace(/,/g, '');

          subtotal += parseFloat(value) || 0;

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

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

        let grandtota=subtotal+carriage;

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

        let paid=parseFloat($('#paid_amount').val())||0;

        let remaining=grandtota-paid;

        if(remaining<0){

            remaining=0;

        }

        $('#remaining_amount').val(remaining.toFixed(2));
        $('#subtotal_amount').val(subtotal.toFixed(2));

    }

    calculateTotals();



    //=====================================================
    // HIDE SEARCH BOXES
    //=====================================================

    $(document).click(function(e){

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

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

        }

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

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

        }

    });

});
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('Admin.layout.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\wamp64\www\alifoods\resources\views/Admin/partials/update_order.blade.php ENDPATH**/ ?>