

<?php $__env->startSection('content'); ?>
    <style>
        .form-control {
            padding-left: 10px !important;
        }
    </style>

    <div class="row">
        <div class="col-12">
            <form class="form-submit" enctype="multipart/form-data">
                <?php echo csrf_field(); ?>
                <div class="card me-2">
                    <div class="card-header pb-0 d-flex justify-content-between align-items-center flex-wrap gap-2">
                        <h5 class="mb-0">Purchase Product's</h5>
                        <a href="javascript:void(0)" class="btn btn-primary btn-sm addProduct"><i
                                class="fa-solid fa-plus"></i> Add Product</a>
                    </div>

                    <div class="card-body">
                        <div class="row">
                            <!-- Supplier + Payment Date -->
                            <div class="col-md-4 mb-3">
                                <label for="supplier_id">Supplier:</label>
                                <select name="supplier_id" id="supplier_id"
                                    class="form-select supplier_id select2 <?php $__errorArgs = ['supplier_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                    required>
                                    <option value="" selected disabled>Select Supplier</option>
                                    <?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $supplier): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($supplier->id); ?>"><?php echo e($supplier->supplier_name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <small class="text-danger" id="error-supplier_id"></small>
                            </div>

                            <div class="col-md-4 mb-3">
                                <label>Purchase Date:</label>
                                <input type="date" name="purchase_date" id="purchase_date"
                                    class="form-control <?php $__errorArgs = ['purchase_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                    value="<?php echo e(date('Y-m-d')); ?>">
                                <small class="text-danger" id="error-purchase_date"></small>
                            </div>
                        </div>

                        <!-- Product Table -->
                        <div class="table-responsive product-table mt-3">
                            <table class="table table-bordered table-striped text-sm align-middle">
                                <thead>
                                    <tr>
                                        <th style="width: 35%">Product</th>
                                        <th style="width: 15%">Qty</th>
                                        <th style="width: 20%">Buying Price</th>
                                        <th style="width: 20%">Selling Price</th>
                                        <th style="width: 10%" class="text-center">Action</th>
                                    </tr>
                                </thead>
                                <tbody class="product-body">
                                    <tr>
                                        <td colspan="5" class="text-center text-muted">
                                            Click "Add Row" to start adding products.
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <div class="text-end mt-1 me-2">
                                <button type="button" class="btn btn-primary btn-sm add-product-row">+ Add Row</button>
                            </div>
                        </div>

                        <!-- Payment Summary Section -->
                        <div class="row mt-2 justify-content-end">
                            <div class="col-md-4">
                                <label class="form-label mb-0 fw-bold">Total Purchase Amount</label>
                                <input type="number" name="grand_total" class="form-control grand_total" readonly
                                    placeholder="Total Amount">
                            </div>

                            <div class="col-md-4">
                                <label class="form-label mb-0 fw-bold">Payment Type</label>
                                <select name="payment_type" class="form-select payment_type" required>
                                    <option value="">Select Payment Type</option>
                                    <?php $__currentLoopData = $payment_type; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($item->name); ?>"><?php echo e($item->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>

                            <div class="col-md-4">
                                <label class="form-label mb-0 fw-bold">Paid Amount</label>
                                <input type="number" name="paid_amount" class="form-control paid_amount"
                                    placeholder="Paid Amount">
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="d-flex justify-content-end mt-3">
                            <button type="button" class="btn btn-primary btn-sm saveProduct">Save Product's</button>
                            <a href="<?php echo e(route('product-index')); ?>" class="btn btn-secondary btn-sm ms-2">Cancel</a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <?php echo $__env->make('products.product_modal', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
    <script>
        const products = <?php echo json_encode($product, 15, 512) ?>;
        let rowIndex = 0;

        $(document).ready(function () {

            refreshProductDropdowns();
            $('.select2').select2({ width: '100%' });

            // Add new product row
            $(document).on('click', '.add-product-row', function () {
                addProductRow();
            });

            // Remove product row
            $(document).on('click', '.remove-product-row', function () {
                $(this).closest('tr').remove();
                updateGrandTotal();
                if ($('.product-body tr').length === 0) {
                    $('.product-body').html(`<tr><td colspan="5" class="text-center text-muted">Click "Add Row" to start adding products.</td></tr>`);
                }
            });

            // Update total on qty or price change
            $(document).on('input', '.qty, .margin_price', function () {
                updateGrandTotal();
            });

            $(document).on('click', '.saveProduct', function (e) {
                e.preventDefault();

                clearValidationErrors();

                const form = $('.form-submit')[0];
                const formData = new FormData(form);

                let hasError = false;

                if (!$('.supplier_id').val()) {
                    $('#error-supplier_id').text('Please select a supplier.');
                    $('.supplier_id').addClass('is-invalid');
                    hasError = true;
                }

                if ($('.product-body tr').length === 0 || $('.product-body td[colspan="5"]').length) {
                    Swal.fire('Error!', 'Please add at least one product before saving.', 'error');
                    hasError = true;
                } else {
                    $('.product-body tr').each(function () {
                        const product = $(this).find('.product_id').val();
                        const qty = $(this).find('.qty').val();
                        const price = $(this).find('.margin_price').val();
                        const unit = $(this).find('.unit_price').val();

                        if (!product) {
                            $(this).find('.product_id').addClass('is-invalid');
                            $(this).find('.product_id').after('<div class="text-danger small">Please select a product.</div>');
                            hasError = true;
                        }
                        if (!qty || qty <= 0) {
                            $(this).find('.qty').addClass('is-invalid');
                            $(this).find('.qty').after('<div class="text-danger small">Quantity must be greater than 0.</div>');
                            hasError = true;
                        }
                        if (!price || price < 0) {
                            $(this).find('.margin_price').addClass('is-invalid');
                            $(this).find('.margin_price').after('<div class="text-danger small">Buying price must be 0 or more.</div>');
                            hasError = true;
                        }
                        if (!unit || unit < 0) {
                            $(this).find('.unit_price').addClass('is-invalid');
                            $(this).find('.unit_price').after('<div class="text-danger small">Selling price must be 0 or more.</div>');
                            hasError = true;
                        }
                    });
                }

                if (hasError) return;

                saveProduct(formData);
            });

        });

        function addProductRow() {
            if ($('.product-body tr').length === 1 && $('.product-body td[colspan="5"]').length) {
                $('.product-body').empty();
            }

            const newRow = `
                <tr data-index="${rowIndex}">
                    <td>
                        <select name="products[${rowIndex}][product_id]" class="form-select form-select-sm select2 product_id" required>
                            <option value="">Select Product</option>
                            ${window.products.map(p => {
                const displayName = p.native_name ? p.native_name : p.name;
                return `<option value="${p.id}">${displayName} - ${p.code}</option>`;
            }).join('')}
                            </select>
                        </td>

                        <td><input type="number" name="products[${rowIndex}][qty]" class="form-control form-control-sm qty" min="1" value="1" required></td>
                        <td><input type="number" name="products[${rowIndex}][margin_price]" class="form-control form-control-sm margin_price" min="0" step="0.01" required></td>
                        <td><input type="number" name="products[${rowIndex}][unit_price]" class="form-control form-control-sm unit_price" min="0" step="0.01" required></td>
                        <td class="text-center">
                            <a href="javascript:void(0);" class="text-danger remove-product-row">
                                <i class="fas fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                `;
            $('.product-body').append(newRow);
            rowIndex++;
            $('.select2').select2({ width: '100%' });
            updateGrandTotal();
        }

        function updateGrandTotal() {
            let total = 0;
            $('.product-body tr').each(function () {
                const qty = parseFloat($(this).find('.qty').val()) || 0;
                const price = parseFloat($(this).find('.margin_price').val()) || 0;
                total += qty * price;
            });
            $('.grand_total').val(total.toFixed(2));
        }

        function handleValidationErrors(errors) {
            clearValidationErrors();

            if (!errors) return; // <-- safeguard

            // Form-level errors
            if (errors.form) {
                Object.entries(errors.form).forEach(([field, message]) => {
                    const $field = $(`[name="${field}"]`);
                    $field.addClass('is-invalid');
                    $(`#error-${field}`).text(message);
                });
            }

            // Row-level errors
            if (errors.rows) {
                Object.entries(errors.rows).forEach(([rowIndex, fields]) => {
                    const $row = $(`.product-body tr[data-index="${rowIndex}"]`);
                    $row.addClass('border border-danger');

                    Object.entries(fields).forEach(([field, message]) => {
                        let $cell = $row.find(`[name="products[${rowIndex}][${field}]"]`).closest('td');
                        $cell.append(`<div class="text-danger small">${message}</div>`);
                    });
                });

                $('html, body').animate({
                    scrollTop: $('.border-danger').first().offset().top - 100
                }, 500);
            }
        }


        function clearValidationErrors() {
            $('.is-invalid').removeClass('is-invalid');
            $('.text-danger').text('');
            $('.product-body tr').removeClass('border border-danger');
            $('.product-body td div.text-danger').remove();
        }

        function saveProduct(formData) {

            $.ajax({
                url: "<?php echo e(route('product-stock-save')); ?>",
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    if (response.status === 'success') {
                        Swal.fire({
                            title: 'Success!',
                            text: response.message,
                            icon: 'success',
                            confirmButtonText: 'OK'
                        }).then(() => {
                            $('.form-submit')[0].reset();
                            $('.product-body').html(`
                                                                                    <tr>
                                                                                        <td colspan="5" class="text-center text-muted">
                                                                                            Click "Add Row" to start adding products.
                                                                                        </td>
                                                                                    </tr>
                                                                                `);
                            $('.grand_total').val('');
                            $('.select2').val('').trigger('change');
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function (xhr) {
                    if (xhr.status === 422) {
                        if (xhr.responseJSON.errors) {
                            handleValidationErrors(xhr.responseJSON.errors);
                        }
                        else if (xhr.responseJSON.message) {
                            Swal.fire('Error!', xhr.responseJSON.message, 'error');
                        }
                    } else {
                        Swal.fire(
                            'Error!',
                            xhr.responseJSON?.message || 'An error occurred while saving the purchase.',
                            'error'
                        );
                    }
                }

            });
        }
        function refreshProductDropdowns() {
            $.ajax({
                url: "<?php echo e(route('products-list')); ?>",
                type: "GET",
                success: function (res) {
                    if (res.status === 'success' && Array.isArray(res.products)) {
                        window.products = res.products;

                        const options = ['<option value="">Select Product</option>'];
                        window.products.forEach(p => {
                            const displayName = p.native_name ? p.native_name : p.name;
                            options.push(`<option value="${p.id}">${displayName} - ${p.code}</option>`);
                        });

                        $('.product_id').each(function () {
                            const selectedVal = $(this).val();
                            $(this)
                                .empty()
                                .append(options.join(''))
                                .val(selectedVal)
                                .trigger('change.select2');
                        });
                    }
                },
                error: function () {
                    console.error('Failed to refresh product dropdown.');
                }
            });
        }



    </script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('layouts.layoutapp', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /opt/lampp/htdocs/lara_commonbilling_new/resources/views/products/purchase.blade.php ENDPATH**/ ?>