@extends('layouts.master')

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Purchase Orders</span>
        <span>Create PO</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Create Purchase Order
        <span>
            <a href="{{ route('sales.list') }}" class="btn border" style="float: right">
                <i class="fa-solid fa-bars-staggered"></i> Back to List
            </a>
        </span>
    </h2>

    <div class="row">
        <div class="col-md-12 col-lg-12 col-xl-12">
            <div class="card card-body pd-40">
                <h5 class="card-title mg-b-20">Create Purchase Order</h5>
                <form action="{{ route('po.store') }}" method="POST">
                    @csrf

                    <!-- Error Display -->
                    @if (count($errors) > 0)
                        <div class="p-1">
                            @foreach ($errors->all() as $error)
                                <div class="alert alert-warning alert-danger fade show" role="alert">
                                    {{ $error }}
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                            @endforeach
                        </div>
                    @endif

                    <div class="row row-sm mg-b-20">
                        <!-- Date Field -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label" for="po_date">Date / تاریخ</label>
                                <input type="text" class="form-control" name="po_date" id="po_date" required>
                            </div>
                        </div>

                        <!-- PO Number -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label" for="po_no">PONo / پی او نمبر</label>
                                <input type="text" class="form-control" name="po_no" id="po_no" required>
                            </div>
                        </div>

                        <!-- Supplier Select -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label" for="supplier_select">Supplier / سپلائر</label>
                                <select class="form-control" name="supplier_id" id="supplier_select" required>
                                    <option value="">- Select -</option>
                                    @foreach ($supplier as $sup)
                                        <option value="{{ $sup->id_supplier }}">{{ $sup->supplier_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <!-- Status Field -->
                        <div class="col-md-4 mt-3">
                            <label class="az-content-label" for="po_status">Status / حیثیت</label>
                            <select id="po_status" name="po_status" class="form-control">
                                <option value="1" selected>Active</option>
                                <option value="0" {{ old('po_status') == '0' ? 'selected' : '' }}>In-Active</option>
                            </select>
                            @error('po_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                        <!-- Details Field -->
                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label" for="details">Details / تفصیلات</label>
                                <textarea class="form-control" name="details" id="details" cols="5" rows="5"></textarea>
                            </div>
                        </div>

                        <!-- Item Details Section -->
                        <div class="col-md-12 mt-5">
                            <h4>Item Details / آئٹم کی تفصیلات</h4>
                            <div class="shadow p-3 bg-light rounded">
                                <table class="table table-bordered" id="item-table">
                                    <thead>
                                        <tr>
                                            <th>Item / آئٹم</th>
                                            <th>Marka / مارکہ</th>
                                            <th>Bori / بوری</th>
                                            <th>Weight / وزن</th>
                                            <th>Rate / شرح</th>
                                            <th>Amount / رقم</th>
                                            <th>Action / عمل</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr class="delete_row">
                                            <td><input type="text" class="form-control" name="items_name[]"
                                                    id=""></td>
                                            <td><input type="text" class="form-control" name="marka[]" id="">
                                            </td>
                                            <td><input type="number" class="form-control" name="bori[]" required></td>
                                            <td><input type="number" class="form-control" name="weight[]" required></td>
                                            <td><input type="number" class="form-control" name="rate[]" required></td>
                                            <td><input type="number" class="form-control" name="amount[]"></td>
                                            <td>
                                                <button type="button" class="btn rounded shadow-base"
                                                    onclick="removeRow(this)">
                                                    <i class="text-danger fa-solid fa-trash-can"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                                <button type="button" class="btn btn-az-primary btn-block mt-2" onclick="addRow()">
                                    <span class="mdi mdi-arrow-expand-up"></span> Add More / مزید شامل کریں
                                </button>
                            </div>
                        </div>

                        <!-- Totals Section -->
                        <div class="col-md-12 mt-4">
                            <h4>Totals / کل</h4>
                            <div class="form-group row">
                                <label for="total_bori" class="col-sm-2 col-form-label">Total Bori / کل بوری:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="total_bori" name="total_bori"
                                        readonly>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="bori_weight" class="col-sm-2 col-form-label">Bori Weight / بوری وزن:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="bori_weight" name="bori_weight"
                                        readonly>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="rent_recieve" class="col-sm-2 col-form-label">Rent Receive / کرایہ وصول
                                    کریں:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="rent_recieve" name="rent_recieve">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="labour" class="col-sm-2 col-form-label">Labour / مزدوری:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="labour" name="labour">
                                </div>
                            </div>
                        </div>
                    </div>

                    <hr>

                    <!-- Form Action Buttons -->
                    <a href="{{ route('sales.list') }}" class="btn btn-danger pd-x-20">Cancel / منسوخ کریں</a>
                    <button type="submit" class="btn btn-az-primary pd-x-20">Submit / جمع کرائیں</button>
                </form>

            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script type="text/javascript">
        $(document).ready(function() {
            $('#supplier_select').select2({
                theme: 'default'
            });
        });
        $(document).ready(function() {
            var today = new Date().toISOString().split('T')[0];
            $('#po_date').val(today);

            $("#po_date").datepicker({
                dateFormat: "yy-mm-dd"
            });
        });

        // function addRow() {
        //     var row = `<tr>
    //         <td>
    //             <select class="form-control item-select" name="items_name[]" required>
    //                 <option value="">- Select -</option>
    //             </select>
    //         </td>
    //         <td>
    //             <select class="form-control marka-select" name="marka[]" required>
    //                 <option value="">- Select -</option>
    //             </select>
    //         </td>
    //         <td><input type="number" class="form-control" name="bori[]" required></td>
    //         <td><input type="number" class="form-control" name="weight[]" required></td>
    //         <td><input type="number" class="form-control" name="rate[]" required></td>
    //         <td><input type="number" class="form-control" name="amount[]"></td>
    //         <td>
    //             <button type="button" class="btn rounded shadow-base" onclick="removeRow(this)">
    //                 <i class="text-danger fa-solid fa-trash-can"></i>
    //             </button>
    //         </td>
    //     </tr>`;
        //     $('#item-table tbody').append(row);

        //     // Populate marka and item selects in the new row
        //     populateMarkaAndItems($('#item-table tbody tr:last'));
        // }
        function addRow() {
            var row = `<tr class="delete_row">
                <td>
                   <input type="text"class="form-control" name="items_name[]" id="">
                </td>
                <td>
                   <input type="text"class="form-control" name="marka[]" id="">
                </td>
                <td><input type="number" class="form-control" name="bori[]" required></td>
                <td><input type="number" class="form-control" name="weight[]" required></td>
                <td><input type="number" class="form-control" name="rate[]" required></td>
                <td><input type="number" class="form-control" name="amount[]"></td>
                <td>
                    <button type="button" class="btn rounded shadow-base" onclick="removeRow(this)">
                        <i class="text-danger fa-solid fa-trash-can"></i>
                    </button>
                </td>
            </tr>`;
            $('#item-table tbody').append(row);

            // Populate marka and item selects in the new row
            populateMarkaAndItems($('#item-table tbody tr:last'));
        }
        document.addEventListener('keydown', function(event) {
            const activeElement = document.activeElement;

            // Check for Tab key press
            if (event.key === "Tab") {
                const allRemarksInputs = document.querySelectorAll('input[name="amount[]"]');
                const lastRemarksInput = allRemarksInputs[allRemarksInputs.length - 1];

                // If activeElement is the last remarks input, add a new row
                if (activeElement === lastRemarksInput) {
                    event.preventDefault(); // Prevent default tab behavior

                    // Trigger the click event of the 'Add More' button
                    addRow();

                    // Focus on the newly added row's first input field (e.g., items select)
                    setTimeout(function() {
                        const newItemsInput = document.querySelectorAll('select[name="items_name[]"]');
                        newItemsInput[newItemsInput.length - 1].focus(); // Focus on the last added input
                    }, 0);
                }
            }

            // Detect Alt + D to delete the selected row
            if (event.altKey && event.key === 'd') {
                event.preventDefault();

                const focusedElement = document.activeElement;
                const focusedRow = focusedElement.closest('.delete_row'); // Find the closest row (div.row)

                // If a row is focused, remove it
                if (focusedRow) {
                    focusedRow.remove(); // Remove the focused row
                    updateTotals();

                    // You can add additional functionality like recalculating totals here
                    // Example: updateTotals();
                } else {
                    showErrorNotification(
                        'Please select the row you want to delete.\nبراہ کرم اس صف کو منتخب کریں جسے آپ حذف کرنا چاہتے ہیں۔'
                    );
                }
            }
        });

        function removeRow(button) {
            $(button).closest('tr').remove();
            updateTotals();
        }

        function addBoriRow() {
            var row = `
            <tr>
                <td><input type="text" class="form-control" name="bori_number[]" required></td>
                <td><input type="number" class="form-control" name="per_bori_weight[]" required></td>
                <td>
                    <button type="button" class="btn rounded shadow-base" onclick="removeBoriRow(this)">
                        <i class="text-danger fa-solid fa-trash-can"></i>
                    </button>
                </td>
            </tr>`;
            $('#bori-table tbody').append(row);
        }

        function removeBoriRow(button) {
            $(button).closest('tr').remove();
        }

        function populateMarkaAndItems(newRow) {
            var truckId = $('#truck').val();
            if (truckId) {
                $.ajax({
                    url: '{{ route('get.truck.items', '__TRUCK_ID__') }}'.replace('__TRUCK_ID__', truckId),
                    type: 'GET',
                    success: function(data) {
                        // Populate marka select in the new row
                        newRow.find('.marka-select').empty().append('<option value="">- Select -</option>');
                        $.each(data.markas, function(_, marka) {
                            newRow.find('.marka-select').append(
                                `<option value="${marka}">${marka}</option>`);
                        });

                        // Populate item select in the new row
                        newRow.find('.item-select').empty().append('<option value="">- Select -</option>');
                    }
                });
            }
        }

        // Fetch items and markas when the truck is selected
        $('#truck').on('change', function() {
            var truckId = $(this).val();
            if (truckId) {
                $('#item-table tbody tr').each(function() {
                    populateMarkaAndItems($(this));
                });
            }
        });

        // Fetch items based on selected marka
        $('#item-table').on('change', 'select[name="marka[]"]', function() {
            var marka = $(this).val();
            var truckId = $('#truck').val();
            if (marka && truckId) {
                $.ajax({
                    url: '{{ route('get.items.by.marka', ['truckId' => '__TRUCK_ID__', 'marka' => '__MARKA__']) }}'
                        .replace('__TRUCK_ID__', truckId).replace('__MARKA__', marka),
                    type: 'GET',
                    success: function(data) {
                        var itemSelect = $(this).closest('tr').find('.item-select');
                        itemSelect.empty().append('<option value="">- Select -</option>');
                        $.each(data, function(id, name) {
                            itemSelect.append(`<option value="${name}">${name}</option>`);
                        });
                    }.bind(this)
                });
            }
        });

        function updateTotals() {
            let totalBori = 0;
            let totalAmount = 0;
            let boriweight = 0;

            // Loop through each row to calculate totals
            $('#item-table tbody tr').each(function() {
                let bori = parseFloat($(this).find('input[name="bori[]"]').val()) || 0;
                let amount = parseFloat($(this).find('input[name="amount[]"]').val()) || 0;
                let weight = parseFloat($(this).find('input[name="weight[]"]').val()) || 0;

                totalBori += bori;
                totalAmount += amount;
                boriweight += weight;
            });

            // Update Total Bori and Total Amount fields
            $('#total_bori').val(totalBori);
            $('#total_amount').val(totalAmount);
            $('#bori_weight').val(boriweight);

            // Update Remaining Amount based on Cash Received
            let cashReceived = parseFloat($('#cash_received').val()) || 0;
            $('#remaining_amount').val(totalAmount - cashReceived);
        }

        function handleInputChange() {
            // Recalculate totals when any input changes
            $('#item-table').on('input', 'input[name="bori[]"], input[name="amount[]"]', updateTotals);

            // Update remaining amount when cash received changes
            $('#cash_received').on('input', function() {
                let cashReceived = parseFloat($(this).val()) || 0;
                let totalAmount = parseFloat($('#total_amount').val()) || 0;
                $('#remaining_amount').val(totalAmount - cashReceived);
            });
        }

        // Initialize the input change handler
        $(document).ready(function() {
            handleInputChange();
            // Update totals when rows are added or removed
            $('#item-table').on('DOMSubtreeModified', updateTotals);
        });
    </script>
@endpush
