@extends('layouts.app')

@section('title', isset($order) ? 'Edit Order' : 'Add Order')

@section('content')

{{-- =========================================================
PAGE HEADER
========================================================= --}}

<div class="row">
    <div class="col-sm-12">

        <div class="card card-transparent card-block card-stretch card-height border-none">

            <div class="card-body p-0 mt-lg-2 mt-0">

                <h3 class="mb-2">
                    {{ isset($order) ? 'Edit Order' : 'Create Order' }}
                </h3>

                <p class="mb-0">
                    {{ isset($order)
                        ? 'Update the customer order and invoice details.'
                        : 'Create a new stationery distribution order for a customer.'
                    }}
                </p>

            </div>

        </div>

    </div>
</div>


{{-- =========================================================
CUSTOMER + ORDER DETAILS
========================================================= --}}

<div class="row">

    {{-- CUSTOMER INFORMATION --}}
    <div class="col-lg-8">

        <div class="card card-block card-stretch card-height">

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

                <div class="header-title">

                    <h4 class="card-title">
                        Customer Information
                    </h4>

                </div>

            </div>

            <div class="card-body">

                <div class="row">

                    {{-- CUSTOMER --}}
                    <div class="col-md-6 form-group">

                        <label for="customerSelect">

                            Select Customer

                            <span class="text-danger">
                                *
                            </span>

                        </label>

                        <select
                            name="customer_id"
                            id="customerSelect"
                            class="form-control custom-select"
                            form="orderForm"
                            required
                        >

                            <option value="">
                                Select Customer
                            </option>

                            @foreach($customers as $customer)

                                <option
                                    value="{{ $customer->customer_id }}"
                                    data-phone="{{ $customer->customer_phonenum ?? '' }}"
                                    data-shop="{{ $customer->shop_name ?? '' }}"
                                    data-area="{{ $customer->area->area_name ?? '' }}"
                                    {{ old('customer_id', $order->customer_id ?? '') == $customer->customer_id ? 'selected' : '' }}
                                >

                                    {{ $customer->customer_name }}
                                    -
                                    {{ $customer->shop_name }}

                                </option>

                            @endforeach

                        </select>

                        @error('customer_id')

                            <small class="text-danger">
                                {{ $message }}
                            </small>

                        @enderror

                    </div>


                    {{-- PHONE --}}
                    <div class="col-md-4">

                        <div class="form-group">

                            <label>
                                Phone Number
                            </label>

                            <input
                                type="text"
                                id="customerPhone"
                                class="form-control"
                                readonly
                                placeholder="Customer phone"
                            >

                        </div>

                    </div>


                    {{-- SHOP --}}
                    <div class="col-md-4">

                        <div class="form-group">

                            <label>
                                Shop Name
                            </label>

                            <input
                                type="text"
                                id="customerShop"
                                class="form-control"
                                readonly
                                placeholder="Shop name"
                            >

                        </div>

                    </div>


                    {{-- AREA --}}
                    <div class="col-md-4">

                        <div class="form-group">

                            <label>
                                Area
                            </label>

                            <input
                                type="text"
                                id="customerArea"
                                class="form-control"
                                readonly
                                placeholder="Area"
                            >

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </div>


    {{-- ORDER DETAILS --}}
    <div class="col-lg-4">

        <div class="card card-block card-stretch card-height">

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

                <div class="header-title">

                    <h4 class="card-title">
                        Order Details
                    </h4>

                </div>

            </div>

            <div class="card-body">

                {{-- STATUS --}}
                <div class="form-group">

                    <label>

                        Order Status

                        <span class="text-danger">
                            *
                        </span>

                    </label>

                    <select
                        name="order_status"
                        class="form-control custom-select"
                        form="orderForm"
                        required
                    >

                        <option value="">
                            Select Status
                        </option>

                        @foreach($statuses as $status)

                            <option
                                value="{{ $status->status_id }}"
                                {{ old('order_status', $order->order_status ?? '') == $status->status_id ? 'selected' : '' }}
                            >

                                {{ $status->status_name }}

                            </option>

                        @endforeach

                    </select>

                    @error('order_status')

                        <small class="text-danger">
                            {{ $message }}
                        </small>

                    @enderror

                </div>


                {{-- TAKEN BY --}}
                <div class="form-group">

                    <label>
                        Taken By
                    </label>

                    <input
                        type="text"
                        class="form-control"
                        value="{{ $order->takenBy->user_name ?? auth()->user()->user_name ?? 'Current User' }}"
                        readonly
                    >

                </div>


                {{-- ORDER DATE --}}
                <div class="form-group mb-0">

                    <label>
                        Order Date
                    </label>

                    <input
                        type="date"
                        name="order_date"
                        class="form-control"
                        form="orderForm"
                        value="{{ old(
                            'order_date',
                            isset($order) && $order->taken_at
                                ? \Carbon\Carbon::parse($order->taken_at)->format('Y-m-d')
                                : date('Y-m-d')
                        ) }}"
                    >

                </div>

            </div>

        </div>

    </div>

</div>


{{-- =========================================================
ORDER FORM
========================================================= --}}

<form
    id="orderForm"
    action="{{ isset($order)
        ? route('orders.update', $order->order_id)
        : route('orders.store')
    }}"
    method="POST"
>

    @csrf

    @if(isset($order))

        @method('PUT')

    @endif


    {{-- =====================================================
    ORDER ITEMS
    ====================================================== --}}

    <div class="row">

        <div class="col-lg-12">

            <div class="card card-block card-stretch card-height">

                <div class="card-header d-flex justify-content-between align-items-center">

                    <div class="header-title">

                        <h4 class="card-title">
                            Order Items
                        </h4>

                    </div>

                    <div class="card-header-toolbar">

                        <button
                            type="button"
                            id="addItemBtn"
                            class="btn btn-primary btn-sm"
                        >

                            <i class="las la-plus mr-1"></i>

                            Add Item

                        </button>

                    </div>

                </div>


                <div class="card-body">

                    <div class="table-responsive">

                        <table
                            class="table table-striped table-bordered mb-0"
                            id="orderItemsTable"
                        >

                            <thead>

                                <tr>

                                    <th width="50">
                                        #
                                    </th>

                                    <th style="min-width:220px;">
                                        Item Name
                                    </th>

                                    <th style="min-width:140px;">
                                        Item Code
                                    </th>

                                    <th width="120">
                                        Stock
                                    </th>

                                    <th width="145">
                                        Purchase Price
                                    </th>

                                    <th width="150">
                                        Sale Price
                                    </th>

                                    <th width="120">
                                        Quantity
                                    </th>

                                    <th width="150">
                                        Total
                                    </th>

                                    <th width="80" class="text-center">
                                        Action
                                    </th>

                                </tr>

                            </thead>


                            <tbody id="orderItemsBody">

                                @php

                                    $existingDetails = isset($order)
                                        ? $order->details
                                        : collect();

                                @endphp


                                @if($existingDetails->count() > 0)

                                    @foreach($existingDetails as $index => $detail)

                                        @php

                                            $inventoryItem = $items->firstWhere(
                                                'item_id',
                                                $detail->item_id
                                            );

                                        @endphp

                                        <tr class="order-item-row">

                                            <td class="row-number">
                                                {{ $index + 1 }}
                                            </td>


                                            {{-- PRODUCT --}}
                                            <td>

                                                <select
                                                    name="items[{{ $index }}][item_id]"
                                                    class="form-control custom-select product-select"
                                                    required
                                                >

                                                    <option value="">
                                                        Select Product
                                                    </option>

                                                    @foreach($items as $item)

                                                        <option
                                                            value="{{ $item->item_id }}"
                                                            data-code="{{ $item->item_code ?? '' }}"
                                                            data-stock="{{ $item->item_quantity ?? 0 }}"
                                                            data-purchase-price="{{ $item->item_purchase_price ?? 0 }}"
                                                            data-max-sale-price="{{ $item->item_saleprice ?? 0 }}"
                                                            {{ $detail->item_id == $item->item_id ? 'selected' : '' }}
                                                        >

                                                            {{ $item->item_name }}

                                                        </option>

                                                    @endforeach

                                                </select>

                                            </td>


                                            {{-- ITEM CODE --}}
                                            <td>

                                                <input
                                                    type="text"
                                                    class="form-control item-code"
                                                    value="{{ $inventoryItem->item_code ?? '' }}"
                                                    readonly
                                                    placeholder="Item Code"
                                                >

                                            </td>


                                            {{-- STOCK --}}
                                            <td>

                                                <span class="badge badge-secondary stock-badge">

                                                    {{ $inventoryItem->item_quantity ?? 0 }}

                                                </span>

                                                <input
                                                    type="hidden"
                                                    class="stock-value"
                                                    value="{{ $inventoryItem->item_quantity ?? 0 }}"
                                                >

                                            </td>


                                            {{-- PURCHASE PRICE --}}
                                            <td>

                                                <input
                                                    type="text"
                                                    name="items[{{ $index }}][purchase_price]"
                                                    class="form-control purchase-price"
                                                    value="{{ number_format((float)($detail->purchase_price ?? $inventoryItem->item_purchase_price ?? 0), 2, '.', '') }}"
                                                    readonly
                                                    placeholder="Rs. 0.00"
                                                >

                                            </td>


                                            {{-- SALE PRICE --}}
                                            <td>

                                                <input
                                                    type="number"
                                                    name="items[{{ $index }}][sale_price]"
                                                    class="form-control sale-price"
                                                    value="{{ old(
                                                        'items.' . $index . '.sale_price',
                                                        $detail->sale_price ?? 0
                                                    ) }}"
                                                    min="0"
                                                    step="0.01"
                                                    required
                                                    placeholder="Rs. 0.00"
                                                >

                                                <small class="text-muted max-price-note">

                                                    Max/reference:
                                                    Rs.
                                                    {{ number_format((float)($inventoryItem->item_saleprice ?? 0), 2) }}

                                                </small>

                                            </td>


                                            {{-- QUANTITY --}}
                                            <td>

                                                <input
                                                    type="number"
                                                    name="items[{{ $index }}][quantity]"
                                                    class="form-control quantity"
                                                    value="{{ old(
                                                        'items.' . $index . '.quantity',
                                                        $detail->quantity
                                                    ) }}"
                                                    min="1"
                                                    required
                                                >

                                                <small class="text-danger stock-error d-none">
                                                    Quantity exceeds available stock.
                                                </small>

                                            </td>


                                            {{-- TOTAL --}}
                                            <td>

                                                <input
                                                    type="text"
                                                    name="items[{{ $index }}][subtotal]"
                                                    class="form-control subtotal"
                                                    value="Rs. {{ number_format((float)($detail->subtotal ?? 0), 2) }}"
                                                    readonly
                                                >

                                            </td>


                                            {{-- DELETE --}}
                                            <td class="text-center">

                                                <button
                                                    type="button"
                                                    class="btn btn-sm btn-danger remove-item"
                                                    title="Remove Item"
                                                >

                                                    <i class="las la-trash"></i>

                                                </button>

                                            </td>

                                        </tr>

                                    @endforeach

                                @else

                                    {{-- FIRST EMPTY ROW --}}

                                    <tr class="order-item-row">

                                        <td class="row-number">
                                            1
                                        </td>


                                        {{-- PRODUCT --}}
                                        <td>

                                            <select
                                                name="items[0][item_id]"
                                                class="form-control custom-select product-select"
                                                required
                                            >

                                                <option value="">
                                                    Select Product
                                                </option>

                                                @foreach($items as $item)

                                                    <option
                                                        value="{{ $item->item_id }}"
                                                        data-code="{{ $item->item_code ?? '' }}"
                                                        data-stock="{{ $item->item_quantity ?? 0 }}"
                                                        data-purchase-price="{{ $item->item_purchase_price ?? 0 }}"
                                                        data-max-sale-price="{{ $item->item_saleprice ?? 0 }}"
                                                    >

                                                        {{ $item->item_name }}

                                                    </option>

                                                @endforeach

                                            </select>

                                        </td>


                                        {{-- CODE --}}
                                        <td>

                                            <input
                                                type="text"
                                                class="form-control item-code"
                                                readonly
                                                placeholder="Item Code"
                                            >

                                        </td>


                                        {{-- STOCK --}}
                                        <td>

                                            <span class="badge badge-secondary stock-badge">
                                                -
                                            </span>

                                            <input
                                                type="hidden"
                                                class="stock-value"
                                                value="0"
                                            >

                                        </td>


                                        {{-- PURCHASE PRICE --}}
                                        <td>

                                            <input
                                                type="text"
                                                name="items[0][purchase_price]"
                                                class="form-control purchase-price"
                                                readonly
                                                placeholder="Rs. 0.00"
                                            >

                                        </td>


                                        {{-- SALE PRICE --}}
                                        <td>

                                            <input
                                                type="number"
                                                name="items[0][sale_price]"
                                                class="form-control sale-price"
                                                min="0"
                                                step="0.01"
                                                required
                                                placeholder="Rs. 0.00"
                                            >

                                            <small class="text-muted max-price-note">
                                                Max/reference: Rs. 0.00
                                            </small>

                                        </td>


                                        {{-- QUANTITY --}}
                                        <td>

                                            <input
                                                type="number"
                                                name="items[0][quantity]"
                                                class="form-control quantity"
                                                value="{{ old('items.0.quantity', 1) }}"
                                                min="1"
                                                required
                                            >

                                            <small class="text-danger stock-error d-none">
                                                Quantity exceeds available stock.
                                            </small>

                                        </td>


                                        {{-- SUBTOTAL --}}
                                        <td>

                                            <input
                                                type="text"
                                                name="items[0][subtotal]"
                                                class="form-control subtotal"
                                                readonly
                                                placeholder="Rs. 0.00"
                                            >

                                        </td>


                                        {{-- DELETE --}}
                                        <td class="text-center">

                                            <button
                                                type="button"
                                                class="btn btn-sm btn-danger remove-item"
                                                title="Remove Item"
                                                disabled
                                            >

                                                <i class="las la-trash"></i>

                                            </button>

                                        </td>

                                    </tr>

                                @endif

                            </tbody>

                        </table>

                    </div>

                </div>

            </div>

        </div>

    </div>


    {{-- =========================================================
    INSTRUCTIONS + SUMMARY
    ========================================================== --}}

    <div class="row">

        {{-- INSTRUCTIONS --}}
        <div class="col-lg-7">

            <div class="card card-block card-stretch card-height">

                <div class="card-header">

                    <div class="header-title">

                        <h4 class="card-title">
                            Instructions
                        </h4>

                    </div>

                </div>

                <div class="card-body">

                    <textarea
                        name="instructions"
                        class="form-control"
                        rows="7"
                        placeholder="e.g. Deliver before 5 PM, handle cartons with care, call before arrival..."
                    >{{ old('instructions', $order->instructions ?? '') }}</textarea>

                </div>

            </div>

        </div>


        {{-- SUMMARY --}}
        <div class="col-lg-5">

            <div class="card card-block card-stretch card-height">

                <div class="card-header">

                    <div class="header-title">

                        <h4 class="card-title">
                            Order Summary
                        </h4>

                    </div>

                </div>

                <div class="card-body">

                    <ul class="list-group list-group-flush">

                        <li class="list-group-item d-flex align-items-center justify-content-between px-0">

                            <span>
                                Total Items
                            </span>

                            <span id="totalItems">
                                0
                            </span>

                        </li>


                        <li class="list-group-item d-flex align-items-center justify-content-between px-0">

                            <span>
                                Total Quantity
                            </span>

                            <span id="totalQuantity">
                                0
                            </span>

                        </li>


                        <li class="list-group-item d-flex align-items-center justify-content-between px-0">

                            <span>
                                Subtotal
                            </span>

                            <span id="subtotalDisplay">
                                Rs. 0.00
                            </span>

                        </li>


                        <li class="list-group-item d-flex align-items-center justify-content-between px-0">

                            <span>
                                Discount
                            </span>

                            <div style="width:120px;">

                                <input
                                    type="number"
                                    name="discount"
                                    id="discount"
                                    class="form-control form-control-sm text-right"
                                    value="{{ old('discount', $order->discount ?? 0) }}"
                                    min="0"
                                    step="0.01"
                                >

                            </div>

                        </li>


                        <li class="list-group-item d-flex align-items-center justify-content-between px-0 border-top pt-3">

                            <span class="h5 mb-0">
                                Grand Total
                            </span>

                            <span
                                class="h5 mb-0 text-primary"
                                id="grandTotalDisplay"
                            >
                                Rs. 0.00
                            </span>

                        </li>

                    </ul>


                    <input
                        type="hidden"
                        name="total_amount"
                        id="totalAmount"
                        value="0"
                    >

                </div>

            </div>

        </div>

    </div>


    {{-- =========================================================
    ACTION BUTTONS
    ========================================================== --}}

    <div class="row">

        <div class="col-lg-12">

            <div class="card card-block card-stretch card-height border-none">

                <div class="card-body d-flex justify-content-end flex-wrap py-3">

                    <a
                        href="{{ route('orders.list') }}"
                        class="btn btn-secondary mr-2 mb-2 mb-md-0"
                    >
                        Cancel
                    </a>


                    <button
                        type="reset"
                        id="resetOrderBtn"
                        class="btn btn-outline-primary mr-2 mb-2 mb-md-0"
                    >

                        <i class="las la-redo mr-1"></i>

                        Reset

                    </button>


                    <button
                        type="submit"
                        id="saveOrderBtn"
                        class="btn btn-primary mb-2 mb-md-0"
                    >

                        <i class="las la-file-invoice mr-1"></i>

                        {{ isset($order) ? 'Update & Generate Invoice' : 'Save & Generate Invoice' }}

                    </button>

                </div>

            </div>

        </div>

    </div>

</form>


{{-- =========================================================
JAVASCRIPT
========================================================= --}}

<script>

document.addEventListener('DOMContentLoaded', function () {

    /* ========================================================
       CUSTOMER INFORMATION
    ======================================================== */

    const customerSelect = document.getElementById('customerSelect');
    const customerPhone = document.getElementById('customerPhone');
    const customerShop = document.getElementById('customerShop');
    const customerArea = document.getElementById('customerArea');

    function updateCustomerInformation() {

        const selectedOption =
            customerSelect.options[customerSelect.selectedIndex];

        if (!selectedOption || !selectedOption.value) {

            customerPhone.value = '';
            customerShop.value = '';
            customerArea.value = '';

            return;
        }

        customerPhone.value =
            selectedOption.getAttribute('data-phone') || '';

        customerShop.value =
            selectedOption.getAttribute('data-shop') || '';

        customerArea.value =
            selectedOption.getAttribute('data-area') || '';
    }

    customerSelect.addEventListener(
        'change',
        updateCustomerInformation
    );

    updateCustomerInformation();


    /* ========================================================
       ORDER ITEMS
    ======================================================== */

    const orderItemsBody =
        document.getElementById('orderItemsBody');

    const addItemBtn =
        document.getElementById('addItemBtn');

    const discountInput =
        document.getElementById('discount');

    const totalItems =
        document.getElementById('totalItems');

    const totalQuantity =
        document.getElementById('totalQuantity');

    const subtotalDisplay =
        document.getElementById('subtotalDisplay');

    const grandTotalDisplay =
        document.getElementById('grandTotalDisplay');

    const totalAmount =
        document.getElementById('totalAmount');


    let rowIndex =
        document.querySelectorAll('.order-item-row').length;


    /* ========================================================
       MONEY
    ======================================================== */

    function money(value) {

        return Number(value || 0).toFixed(2);

    }


    /* ========================================================
       UPDATE SINGLE ROW
    ======================================================== */

    function updateRow(row) {

        const productSelect =
            row.querySelector('.product-select');

        const selectedOption =
            productSelect.options[
                productSelect.selectedIndex
            ];

        const itemCode =
            row.querySelector('.item-code');

        const stockBadge =
            row.querySelector('.stock-badge');

        const stockValue =
            row.querySelector('.stock-value');

        const purchasePrice =
            row.querySelector('.purchase-price');

        const salePrice =
            row.querySelector('.sale-price');

        const quantity =
            row.querySelector('.quantity');

        const subtotal =
            row.querySelector('.subtotal');

        const stockError =
            row.querySelector('.stock-error');

        const maxPriceNote =
            row.querySelector('.max-price-note');


        if (!selectedOption || !selectedOption.value) {

            itemCode.value = '';

            stockBadge.textContent = '-';

            stockValue.value = 0;

            purchasePrice.value = '';

            salePrice.value = '';

            subtotal.value = '';

            maxPriceNote.textContent =
                'Max/reference: Rs. 0.00';

            stockError.classList.add('d-none');

            calculateSummary();

            return;
        }


        const code =
            selectedOption.getAttribute('data-code') || '';

        const stock =
            Number(
                selectedOption.getAttribute('data-stock') || 0
            );

        const inventoryPurchasePrice =
            Number(
                selectedOption.getAttribute(
                    'data-purchase-price'
                ) || 0
            );

        const maxSalePrice =
            Number(
                selectedOption.getAttribute(
                    'data-max-sale-price'
                ) || 0
            );


        itemCode.value =
            code;

        stockBadge.textContent =
            stock;

        stockValue.value =
            stock;

        purchasePrice.value =
            'Rs. ' + money(inventoryPurchasePrice);


        /*
         * IMPORTANT:
         * Inventory sale price is only a reference/max price.
         * It is NOT used to force the order sale price.
         */

        maxPriceNote.textContent =
            'Max/reference: Rs. ' +
            money(maxSalePrice);


        /*
         * Only fill sale price automatically when
         * the field is empty.
         */

        if (
            salePrice.value === '' ||
            Number(salePrice.value) === 0
        ) {

            salePrice.value =
                money(maxSalePrice);

        }


        calculateRowSubtotal(row);

    }


    /* ========================================================
       CALCULATE ROW SUBTOTAL
    ======================================================== */

    function calculateRowSubtotal(row) {

        const salePrice =
            row.querySelector('.sale-price');

        const quantity =
            row.querySelector('.quantity');

        const subtotal =
            row.querySelector('.subtotal');

        const stockValue =
            row.querySelector('.stock-value');

        const stockError =
            row.querySelector('.stock-error');


        const price =
            Number(salePrice.value || 0);

        let qty =
            Number(quantity.value || 0);

        const stock =
            Number(stockValue.value || 0);


        if (qty < 1) {

            qty = 1;

            quantity.value = 1;

        }


        /*
         * Stock validation only.
         *
         * There is intentionally NO validation
         * against inventory maximum sale price.
         */

        if (qty > stock) {

            stockError.classList.remove('d-none');

            subtotal.value =
                'Rs. 0.00';

        } else {

            stockError.classList.add('d-none');

            subtotal.value =
                'Rs. ' +
                money(price * qty);

        }


        calculateSummary();

    }


    /* ========================================================
       SUMMARY
    ======================================================== */

    function calculateSummary() {

        const rows =
            document.querySelectorAll(
                '.order-item-row'
            );

        let itemCount = 0;
        let quantityTotal = 0;
        let subtotalTotal = 0;


        rows.forEach(function (row) {

            const productSelect =
                row.querySelector('.product-select');

            const salePrice =
                row.querySelector('.sale-price');

            const quantity =
                row.querySelector('.quantity');

            const stockValue =
                row.querySelector('.stock-value');


            if (
                productSelect &&
                productSelect.value
            ) {

                itemCount++;


                const price =
                    Number(
                        salePrice.value || 0
                    );


                const qty =
                    Number(
                        quantity.value || 0
                    );


                const stock =
                    Number(
                        stockValue.value || 0
                    );


                if (qty <= stock) {

                    quantityTotal += qty;

                    subtotalTotal +=
                        price * qty;

                }

            }

        });


        const discount =
            Number(
                discountInput.value || 0
            );


        const grandTotal =
            Math.max(
                0,
                subtotalTotal - discount
            );


        totalItems.textContent =
            itemCount;

        totalQuantity.textContent =
            quantityTotal;

        subtotalDisplay.textContent =
            'Rs. ' +
            money(subtotalTotal);

        grandTotalDisplay.textContent =
            'Rs. ' +
            money(grandTotal);

        totalAmount.value =
            grandTotal.toFixed(2);

    }


    /* ========================================================
       PRODUCT CHANGE
    ======================================================== */

    orderItemsBody.addEventListener(
        'change',
        function (event) {

            if (
                event.target.classList.contains(
                    'product-select'
                )
            ) {

                const row =
                    event.target.closest(
                        '.order-item-row'
                    );

                updateRow(row);

            }

        }
    );


    /* ========================================================
       SALE PRICE / QUANTITY CHANGE
    ======================================================== */

    orderItemsBody.addEventListener(
        'input',
        function (event) {

            if (
                event.target.classList.contains(
                    'quantity'
                ) ||
                event.target.classList.contains(
                    'sale-price'
                )
            ) {

                const row =
                    event.target.closest(
                        '.order-item-row'
                    );

                calculateRowSubtotal(row);

            }

        }
    );


    /* ========================================================
       DISCOUNT
    ======================================================== */

    discountInput.addEventListener(
        'input',
        calculateSummary
    );


    /* ========================================================
       ADD ITEM
    ======================================================== */

    addItemBtn.addEventListener(
        'click',
        function () {

            const newRow =
                document.createElement('tr');

            newRow.className =
                'order-item-row';


            newRow.innerHTML = `

                <td class="row-number">
                    1
                </td>

                <td>

                    <select
                        name="items[${rowIndex}][item_id]"
                        class="form-control custom-select product-select"
                        required
                    >

                        <option value="">
                            Select Product
                        </option>

                        @foreach($items as $item)

                            <option
                                value="{{ $item->item_id }}"
                                data-code="{{ $item->item_code ?? '' }}"
                                data-stock="{{ $item->item_quantity ?? 0 }}"
                                data-purchase-price="{{ $item->item_purchase_price ?? 0 }}"
                                data-max-sale-price="{{ $item->item_saleprice ?? 0 }}"
                            >

                                {{ $item->item_name }}

                            </option>

                        @endforeach

                    </select>

                </td>


                <td>

                    <input
                        type="text"
                        class="form-control item-code"
                        readonly
                        placeholder="Item Code"
                    >

                </td>


                <td>

                    <span class="badge badge-secondary stock-badge">
                        -
                    </span>

                    <input
                        type="hidden"
                        class="stock-value"
                        value="0"
                    >

                </td>


                <td>

                    <input
                        type="text"
                        name="items[${rowIndex}][purchase_price]"
                        class="form-control purchase-price"
                        readonly
                        placeholder="Rs. 0.00"
                    >

                </td>


                <td>

                    <input
                        type="number"
                        name="items[${rowIndex}][sale_price]"
                        class="form-control sale-price"
                        min="0"
                        step="0.01"
                        required
                        placeholder="Rs. 0.00"
                    >

                    <small class="text-muted max-price-note">
                        Max/reference: Rs. 0.00
                    </small>

                </td>


                <td>

                    <input
                        type="number"
                        name="items[${rowIndex}][quantity]"
                        class="form-control quantity"
                        value="1"
                        min="1"
                        required
                    >

                    <small class="text-danger stock-error d-none">
                        Quantity exceeds available stock.
                    </small>

                </td>


                <td>

                    <input
                        type="text"
                        name="items[${rowIndex}][subtotal]"
                        class="form-control subtotal"
                        readonly
                        placeholder="Rs. 0.00"
                    >

                </td>


                <td class="text-center">

                    <button
                        type="button"
                        class="btn btn-sm btn-danger remove-item"
                        title="Remove Item"
                    >

                        <i class="las la-trash"></i>

                    </button>

                </td>

            `;


            orderItemsBody.appendChild(newRow);

            rowIndex++;

            updateRowNumbers();

            updateRemoveButtons();

            calculateSummary();

        }
    );


    /* ========================================================
       REMOVE ITEM
    ======================================================== */

    orderItemsBody.addEventListener(
        'click',
        function (event) {

            const removeButton =
                event.target.closest(
                    '.remove-item'
                );


            if (!removeButton) {

                return;

            }


            const row =
                removeButton.closest(
                    '.order-item-row'
                );


            row.remove();

            updateRowNumbers();

            updateRemoveButtons();

            calculateSummary();

        }
    );


    /* ========================================================
       ROW NUMBERS
    ======================================================== */

    function updateRowNumbers() {

        const rows =
            document.querySelectorAll(
                '.order-item-row'
            );


        rows.forEach(function (row, index) {

            const numberCell =
                row.querySelector('.row-number');

            numberCell.textContent =
                index + 1;

        });

    }


    /* ========================================================
       REMOVE BUTTON STATE
    ======================================================== */

    function updateRemoveButtons() {

        const rows =
            document.querySelectorAll(
                '.order-item-row'
            );


        rows.forEach(function (row) {

            const button =
                row.querySelector(
                    '.remove-item'
                );

            button.disabled =
                rows.length === 1;

        });

    }


    /* ========================================================
       RESET
    ======================================================== */

    document
        .getElementById('resetOrderBtn')
        .addEventListener(
            'click',
            function () {

                setTimeout(
                    function () {

                        document
                            .querySelectorAll(
                                '.order-item-row'
                            )
                            .forEach(function (row) {

                                updateRow(row);

                            });

                        updateCustomerInformation();

                        updateRemoveButtons();

                        calculateSummary();

                    },
                    50
                );

            }
        );


    /* ========================================================
       INITIAL SETUP
    ======================================================== */

    document
        .querySelectorAll(
            '.order-item-row'
        )
        .forEach(function (row) {

            const productSelect =
                row.querySelector(
                    '.product-select'
                );

            if (
                productSelect &&
                productSelect.value
            ) {

                updateRow(row);

            }

        });


    updateRemoveButtons();

    calculateSummary();

});

</script>

@endsection