@extends('layouts.master')
@section('content')
    <style></style>
    {{-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css"> --}}
    <div class="az-content-breadcrumb">
        <span>Purchase Order</span>
        <span>Purchase Order </span>
        {{-- <span>Forms</span> --}}
        {{-- <span>Form Layouts</span> --}}
    </div>
    <h2 class="az-content-title" style="display: inline">Create PO <span>
            {{-- <a href="{{ route('po.list') }}"
                class="btn btn-az-primary" style="float: right">Purchase Order List</a> --}}
            <a href="{{ route('po.list') }}" class="btn border" style="float: right"><i class="fa-solid fa-bars-staggered"></i>
                Back to Purchase Order
            </a>
        </span></h2>
    {{-- <h2 style="float: right" class="az-content-title"></h2> --}}


    {{-- <div class="az-content-body pd-lg-l-40 d-flex flex-column"> --}}
    <div class="row">
        <div class="col-12">
            <div class="card card-body shadow-sm">
                <h5 class="card-title mb-4">Add Purchase Order</h5>
                <form method="post" action="{{ route('po.store') }}" id="purchase_order_form">
                    @csrf
                    @if (count($errors) > 0)
                        <div class="alert alert-danger">
                            @foreach ($errors->all() as $error)
                                <div>{{ $error }}</div>
                            @endforeach
                        </div>
                    @endif
                    <input type="hidden" name="purchase_order" id="products_data">
                    <div class="row mb-4">
                        <div class="col-12 col-md-4">
                            <label for="supplier_select" class="form-label">Search Supplier</label>
                            <select class="form-control select2" name="supplier_name" 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 class="col-12 col-md-4">
                            <label for="date" class="form-label">Date</label>
                            <input type="text" id="date-disabled" name="date-disabled" class="form-control" disabled />
                            <input type="hidden" id="date" name="date" class="form-control" required />
                        </div>

                        <div class="col-12 col-md-4 mt-4 mt-md-0">
                            <div class="card border-0 p-3 text-white" style="background-color: #00beda;">
                                <b>SUPPLIER INFO</b>
                            </div>
                            <div class="row p-2" id="supplier_details">
                                <div class="col-md-12">
                                    <p>Supplier Name: <span id="supplier_name">-</span></p>
                                </div>
                                <div class="col-md-12">
                                    <p>Supplier Address: <span id="supplier_address">-</span></p>
                                </div>
                                <div class="col-md-12">
                                    <p>Supplier Phone: <span id="supplier_phone">-</span></p>
                                </div>
                                <div class="col-md-12">
                                    <p>Supplier Email: <span id="supplier_email">-</span></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <hr>
                    <div class="cadrd card-body mb-4">
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <label for="supplier_brands" class="form-label">Brands</label>
                                <select class="form-control select2" id="supplier_brands" name="supplier_brands[]" required>
                                    <!-- Dynamically populated brands -->
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="supplier_brands_products" class="form-label">Products</label>
                                <select class="form-control select2" id="supplier_brands_products"
                                    name="supplier_brands_products[]" required>
                                    <!-- Dynamically populated products -->
                                </select>
                            </div>
                            <div class="col-md-2 mb-3">
                                <label for="currency" class="form-label">Currency</label>
                                <select class="form-control select2" id="currency" name="currency" required>
                                    <option value="PKR">PKR</option>
                                    <option value="USD">USD</option>
                                    <option value="EUR">EUR</option>
                                </select>
                            </div>
                            <div class="col-md-2 mb-3">
                                <label for="currency_rate" class="form-label">Currency Rate <span style="font-size: 10px" class="text-info">(Defalt Value Is 1)</span></label>
                                <input type="text" class="form-control" id="currency_rate" name="currency_rate" value="1" required>
                            </div>
                            <div class="col-md-1 d-flex align-items-end mb-3">
                                <button type="button" id="add_product" class="btn btn-az-primary btn-block">
                                    Add <i class="fas fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="card card-body mb-4">
                        <div class="table-responsive">
                            <table id="products_table" class="table table-hover">
                                <thead class="thead-light">
                                    <tr>
                                        <th>Product ID</th>
                                        <th>Brand</th>
                                        <th>Product</th>
                                        <th>Currency</th>
                                        <th>Unit Price</th>
                                        <th>Qty</th>
                                        <th>Total Price</th>
                                        <th>Remove</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Dynamically added products will appear here -->
                                </tbody>
                            </table>
                        </div>
                        <div class="d-flex justify-content-end mt-3">
                            <h5>Total: <span id="overall_total">0.00</span></h5>
                        </div>
                    </div>

                    <div class="d-flex justify-content-between">
                        <a href="{{ route('po.list') }}" class="btn btn-danger">Cancel</a>
                        <button type="submit" class="btn btn-az-primary">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="duplicateProductModal" tabindex="-1" role="dialog"
        aria-labelledby="duplicateProductModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content border border-danger rounded-3" style="width: 500px; padding: 20px;">
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                    aria-label="Close"></button>
                <div class="modal-body text-center">
                    <center>

                        <div
                            style="font-size: 60px; color: #17a2b8; margin-bottom: 20px; border: 3px solid #17a2b8; border-radius: 50%; padding: 10px; width: 80px; height: 80px; display: flex; align-items: center; justify-content: center;">
                            !
                        </div>
                    </center>
                    <h2 class="modal-title" style="font-weight: bold; margin-bottom: 10px;">Product Already Added!</h2>
                    <p style="margin-bottom: 20px;">If you want to change this product, please remove and add it again.</p>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">
                        <i class="fas fa-check" style="margin-right: 5px;"></i> OK
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Error Modal HTML -->
    <div class="modal fade" id="missingFieldsModal" tabindex="-1" role="dialog"
        aria-labelledby="missingFieldsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content border border-danger rounded-3" style="width: 500px; padding: 20px;">
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                    aria-label="Close"></button>
                <div class="modal-body text-center">
                    <center>

                        <div
                            style="font-size: 60px; color: #dc3545; margin-bottom: 20px; border: 3px solid #dc3545; border-radius: 100%; width: 80px; height: 80px;">
                            !
                        </div>
                    </center>
                    <h2 class="modal-title" style="font-weight: bold; margin-bottom: 10px;">Missing Information</h2>
                    <span style="display: block; margin-bottom: 20px;">Supplier/Brand/Product & Date should not be
                        empty!</span>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">
                        <i class="fas fa-check" style="margin-right: 5px;"></i> OK
                    </button>
                </div>
            </div>
        </div>
    </div>



@endsection

@push('scripts')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        $('#purchase_order_form').on('submit', function(event) {
             let products = gatherProductData();

             $('#products_data').val(JSON.stringify(products));
        });

        function gatherProductData() {
             let products = [];

             $('#products_table tbody tr').each(function() {
                 let productId = $(this).find('.product-id').text();
                let brand = $(this).find('.brand').text();
                let product = $(this).find('.product').text();
                let currency = $(this).find('.currency').text();
                let unitPrice = $(this).find('.unit-price').text();
                let qty = $(this).find('.qty').val();
                let totalPrice = $(this).find('.total-price').text();

                 let productData = {
                    productId: productId,
                    brand: brand,
                    product: product,
                    currency: currency,
                    unitPrice: unitPrice,
                    qty: qty,
                    totalPrice: totalPrice
                };

                 products.push(productData);
            });

            return products;
        }

         $('#add_product').click(function() {
            let products = gatherProductData();
            console.log(products);
         });

        $(document).ready(function() {
             var today = new Date().toISOString().split('T')[0];

             $('#date').val(today);
            $('#date-disabled').val(today);
        });

        $(document).ready(function() {
            $('.select2').select2();

            $('#add_product').on('click', function(e) {
                e.preventDefault();

                var supplier = $('#supplier_select').val();
                var brand = $('#supplier_brands').val();
                var product = $('#supplier_brands_products').val();
                var date = $('#date').val();

                if (!supplier || !brand || !product || !date) {
                    $('#missingFieldsModal').modal('show');
                } else {
                    var productId = $('#supplier_brands_products').val();
                    var productText = $('#supplier_brands_products option:selected').text();
                    var brandText = $('#supplier_brands option:selected').text();
                    var currency = $('#currency').val();
                    var currencyRate = parseFloat($('#currency_rate')
                        .val());
                    var unitPrice = parseFloat(productText.split('|')[1].trim());

                    if (!isNaN(currencyRate) && !isNaN(unitPrice) && productId) {
                        var convertedUnitPrice = (unitPrice * currencyRate).toFixed(2);

                        var qty = 1;
                        var totalPrice = (convertedUnitPrice * qty).toFixed(2);

                        var productExists = false;
                        $('#products_table tbody tr').each(function() {
                            var rowProductId = $(this).find('.product-id').text();
                            if (rowProductId === productId) {
                                productExists = true;
                                return false;
                            }
                        });

                        if (productExists) {
                            $('#duplicateProductModal').modal('show');
                        } else {
                            $('#products_table tbody').append(`
                            <tr>
                                <td class="product-id">${productId}</td>
                                <td class="brand">${brandText}</td>
                                <td class="product">${productText.split('|')[0].trim()}</td>
                                <td class="currency">${currency}</td>
                                <td class="unit-price">${convertedUnitPrice}</td>
                                <td><input type="number" name="qty" class="form-control qty" value="${qty}" min="1" style="width: 60px;"></td>
                                <td class="total-price">${totalPrice}</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>
                        `);

                            recalculateTotalPrice();
                        }
                    } else {
                        console.error('Invalid input values for product or currency rate.');
                    }
                }
            });

            function recalculateTotalPrice() {
                var overallTotal = 0;
                $('#products_table tbody tr').each(function() {
                    var totalPrice = parseFloat($(this).find('.total-price').text());
                    overallTotal += totalPrice;
                });
                $('#overall_total').text(overallTotal.toFixed(2));
                $('#total_price').val(overallTotal.toFixed(2));
            }

            $('#products_table').on('click', '.remove-product', function() {
                $(this).closest('tr').remove();
                recalculateTotalPrice();
            });

            $('#products_table').on('change', '.qty', function() {
                var row = $(this).closest('tr');
                var unitPrice = parseFloat(row.find('.unit-price').text());
                var qty = parseInt($(this).val());

                if (qty < 1) {
                    qty = 1;
                    $(this).val(qty);
                }

                var totalPrice = (unitPrice * qty).toFixed(2);
                row.find('.total-price').text(totalPrice);

                recalculateTotalPrice();
            });
        });

        $(document).ready(function() {
            $('.select2').select2();

            $('#supplier_select').on('change', function() {
                var id = $(this).val();
                if (id) {
                    $.ajax({
                        url: '{{ url('po/get_supplier_details') }}',
                        type: 'GET',
                        data: {
                            id: id
                        },
                        success: function(response) {
                            $('#supplier_details').html(response.html);

                            $.ajax({
                                url: '{{ url('po/get_supplier_brands') }}',
                                type: 'GET',
                                data: {
                                    id: id
                                },
                                success: function(brandsResponse) {
                                    $('#supplier_brands').html(brandsResponse.html);
                                    $('#supplier_brands')
                                        .select2();

                                    $('#supplier_brands_products').empty();
                                },
                                error: function(xhr, status, error) {
                                    console.log('Error fetching brands:', xhr
                                        .responseText);
                                }
                            });
                        },
                        error: function(xhr, status, error) {
                            console.log('Error fetching supplier details:', xhr.responseText);
                        }
                    });
                } else {
                    $('#supplier_details').html(`
                        <div class="row">
                            <div class="col-md-12">
                                <p>Supplier Name: <span></span></p>
                            </div>
                            <div class="col-md-12">
                                <p>Supplier Address: <span></span></p>
                            </div>
                            <div class="col-md-12">
                                <p>Supplier Phone: <span></span></p>
                            </div>
                            <div class="col-md-12">
                                <p>Supplier Email#: <span></span></p>
                            </div>
                        </div>
                    `);
                    $('#supplier_brands').empty();
                    $('#supplier_brands_products').empty();
                    $('.select2').select2();
                }
            });

            $('#supplier_brands').on('change', function() {
                var brandId = $(this).val();
                var supplierId = $('#supplier_select').val();
                if (brandId && supplierId) {
                    $.ajax({
                        url: '{{ url('po/get_supplier_brands_products') }}',
                        type: 'GET',
                        data: {
                            brand_id: brandId,
                            supplier_id: supplierId
                        },
                        success: function(productsResponse) {
                            $('#supplier_brands_products').html(productsResponse.html);
                            $('#supplier_brands_products').select2(); // Reinitialize Select2
                        },
                        error: function(xhr, status, error) {
                            console.log('Error fetching products:', xhr.responseText);
                        }
                    });
                } else {
                    $('#supplier_brands_products').empty();
                }
            });
        });
    </script>
    <script>
        $(document).ready(function() {
            $('#supplier_select').select2({
                theme: 'default'
            });
        });
    </script>
@endpush
