
<?php $__env->startSection('content'); ?>
<style>
    .invoice-table {
        width: 100%;
        border-collapse: collapse;
    }
    .invoice-table th, .invoice-table td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    .invoice-table th {
        background-color: #f2f2f2;
    }
    .form-control {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }
    .checkbox-label {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
    }
    .summary-box {
        border: 1px solid #ddd;
        padding: 15px;
        margin-top: 20px;
        background-color: #f9f9f9;
    }
    .char-count {
        font-size: 12px;
        color: #6c757d;
    }
    .btn {
        padding: 8px 16px;
        margin-right: 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    .btn-primary {
        background-color: #007bff;
        color: white;
    }
    .btn-secondary {
        background-color: #6c757d;
        color: white;
    }
    .btn-danger {
        background-color: #dc3545;
        color: white;
    }
    .btn-success {
        background-color: #28a745;
        color: white;
    }
    .action-buttons {
        margin-bottom: 15px;
    }
</style>
<main class="main-content">
    <div class="container px-2">
        <h2>Add New Tax Invoice</h2>
        <div class="page-header">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb ">
                    <li class="breadcrumb-item"><a href="<?php echo e(asset('dashboard')); ?>"><?php echo e(__('message.dashboard')); ?></a></li>
                    <li class="breadcrumb-item"><a href="<?php echo e(asset('account/invoice')); ?>">Invoice</a></li>
                    <li class="breadcrumb-item active" aria-current="page"><?php echo e(__('message.add')); ?></li>
                </ol>
            </nav>
        </div>

        <div class="card">
        <?php if (isset($component)) { $__componentOriginal8a5ba9c90b64d384232e9948b1023e746ba08e74 = $component; } ?>
<?php $component = $__env->getContainer()->make(App\View\Components\FlashMessage::class, []); ?>
<?php $component->withName('flashMessage'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php $component->withAttributes([]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal8a5ba9c90b64d384232e9948b1023e746ba08e74)): ?>
<?php $component = $__componentOriginal8a5ba9c90b64d384232e9948b1023e746ba08e74; ?>
<?php unset($__componentOriginal8a5ba9c90b64d384232e9948b1023e746ba08e74); ?>
<?php endif; ?>
            <form action="<?php echo e(asset('account/add-invoice')); ?>" method="post">
                <?php echo csrf_field(); ?>
                <div class="card-header py-4">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-5">Client Name</label>
                                <select class="col-7 form-control py-2 border" name="customer_id">
                                    <option selected disabled>Select</option>
                                    <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cus): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($cus->id); ?>"><?php echo e($cus->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Invoice No.</label>
                                <input type="text" class="form-control py-2 col-7 border" name="invoice_number" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Invoice Date</label>
                                <input type="date" class="form-control py-2 col-7 border" name="invoice_date" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Due Date</label>
                                <input type="date" class="form-control py-2 col-7 border" name="due_date" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">PO No.</label>
                                <input type="text" class="form-control py-2 col-7 border" name="po_number" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">PO Date</label>
                                <input type="date" class="form-control py-2 col-7 border" name="po_date" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Payment Terms</label>
                                <select name="payment_terms" class="form-control py-2 col-7 border" name="payment_terms">
                                    <option disabled selected>Select</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="action-buttons">
                        <button type="button" id="addItemBtn" class="btn btn-success">
                            <i class="fa fa-plus"></i> Add Item
                        </button>
                    </div>
                    
                    <table class="invoice-table" id="invoiceItems">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Item Name</th>
                                <th>QTY</th>
                                <th>Price</th>
                                <th>Discount (%)</th>
                                <th>CGST</th>
                                <th>SGST</th>
                                <th>IGST</th>
                                <th>Total</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="item-row">
                                <td>1</td>
                                <td>
                                    <select class="form-control item-name select-item-change" name="item_id[]">
                                        <option disabled selected>Select</option>
                                        <?php $__currentLoopData = $items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($item->id); ?>"><?php echo e($item->name); ?></option>
                                            
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </td>
                                
                                <td><input type="number" class="form-control item-qty" min="1" name="item_quantity[]" required></td>
                                <td><input type="number" class="form-control item-price" min="0" step="0.01" name="item_price[]"></td>
                                <td><input type="number" class="form-control item-discount" min="0" max="100" name="item_discount[]"></td>
                                <td><input type="number" class="form-control item-cgst" readonly name="item_cgst[]"></td>
                                <td><input type="number" class="form-control item-sgst" readonly name="item_sgst[]"></td>
                                <td><input type="number" class="form-control item-igst" readonly name="item_igst[]"></td>
                                <td><input type="number" class="form-control item-total" readonly name="item_total[]"></td>
                                <td></td>
                            </tr>
                        </tbody>
                    </table>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            
                            
                            <div class="form-group">
                                <label>Description</label>
                                <textarea class="form-control" id="description" rows="3" name="description"></textarea>
                                <div class="char-count"><span id="charCount">1000</span> characters left</div>
                            </div>
                            
                            <div class="form-group">
                                <!-- <div class="checkbox-label">
                                    <input type="checkbox" id="totalQuantity"> <label for="totalQuantity" class="pt-2">&nbsp; Total quantity</label>
                                </div>
                                -->
                                <div class="row">
                                    <div class="checkbox-label col-md-5"  >
                                        <input type="checkbox" id="shippingCharges"> <label for="shippingCharges" class="pt-2" style="cursor:pointer;">&nbsp;Add shipping charges</label>
                                    </div>
                                    <div class="col-md-7 px-3 shipping_box d-none">
                                        <div class="form-group">
                                            <input type="number" class="form-control shipping_charge" name="shipping_charge">
                                        </div>
                                        
                                    </div>
                                </div>
                            
                                
                                <div class="checkbox-label">
                                    <input type="checkbox" id="showCess" name="cess"> <label for="showCess" class="pt-2">&nbsp; Show CESS</label>
                                </div>
                                <!--                             
                                <button class="btn btn-secondary mt-2" class="pt-2">&nbsp;+ Add TDS/TCS</button>
                                <div class="checkbox-label mt-2">
                                    <input type="checkbox" id="transportLabels"> <label for="transportLabels" class="pt-2">&nbsp;Transport Labels and E-Way data</label>
                                </div> -->
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="summary-box">
                                <h4>Summary</h4>
                                <div class="d-flex justify-content-between">
                                    <span>Subtotal: </span>
                                    <span>₹ &nbsp;<input id="subtotal" type="text" name="subtotal" class="p-1 border-0" placeholder="0.00"></span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span>CGST:</span>
                                    
                                    <span>₹ &nbsp;<input id="cgstTotal" type="text" name="cgst_total" class="p-1 border-0" placeholder="0.00"></span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span>SGST:</span>
                                    
                                    <span>₹ &nbsp;<input id="sgstTotal" type="text" name="sgst_total" class="p-1 border-0" placeholder="0.00"></span>
                                    
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span>IGST:</span>                                
                                    <span>₹ &nbsp;<input id="igstTotal" type="text" name="igst_total" class="p-1 border-0" placeholder="0.00"></span>
                                </div>
                                <div class="d-flex justify-content-between" id="cessContainer" style="display:none;">
                                    <span>CESS:</span>
                                    
                                    <span>₹ &nbsp;<input id="cessTotal" type="text" name="cess_total" class="p-1 border-0" placeholder="0.00"></span>
                                </div>
                                <div class="add_extra_total">
                                    
                                </div>
                                <hr>
                                <div class="d-flex justify-content-between font-weight-bold">
                                    <span>Total:</span>
                                    
                                    <span>₹ &nbsp;<input id="grandTotal" type="text" name="grand_total" class="p-1 border-0" placeholder="0.00"></span>
                                </div>
                                
                            </div>
                            
                            <div class="form-group mt-3">
                                <label>Terms & Conditions</label>
                                <textarea class="form-control" rows="3" name="terms_and_conditions"></textarea>
                            </div>
                            
                            <div class="form-group">
                                <label>Private notes (not shown to client)</label>
                                <textarea class="form-control" rows="3" name="private_note"></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="text-right mt-4">
                        <button type="submit" class="btn btn-primary">Preview & save</button>
                        
                    </div>
                </div>
            </form>
        </div>
    </div>
</main>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('footer-script'); ?>
<script>
    $(document).ready(function() {
        // Initialize item counter
        let itemCounter = 1;
        
        // Character count for description
        $('#description').on('input', function() {
            const maxLength = 1000;
            const currentLength = $(this).val().length;
            $('#charCount').text(maxLength - currentLength);
        });

        // Add new item row
        $('#addItemBtn').click(function() {
            itemCounter++;
            const newRow = `
                <tr class="item-row">
                    <td>${itemCounter}</td>
                    <td>
                        <select class="form-control item-name select-item-change" name="item_id[]">
                            <option disabled selected>Select</option>
                            <?php $__currentLoopData = $items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($item->id); ?>"><?php echo e($item->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </td>
                    
                    <td><input type="number" class="form-control item-qty" min="1" name="item_quantity[]" required></td>
                    <td><input type="number" class="form-control item-price" min="0" step="0.01" name="item_price[]"></td>
                    <td><input type="number" class="form-control item-discount" min="0" max="100" name="item_discount[]"></td>
                    <td><input type="number" class="form-control item-cgst" readonly name="item_cgst[]"></td>
                    <td><input type="number" class="form-control item-sgst" readonly name="item_sgst[]"></td>
                    <td><input type="number" class="form-control item-igst" readonly name="item_igst[]"></td>
                    <td><input type="number" class="form-control item-total" readonly name="item_total[]"></td>
                            
                    
                    <td><button type="button" class="remove-item-btn btn btn-sm btn-danger"><i class="fa fa-trash"></i></button></td>
                </tr>
            `;
            $('#invoiceItems tbody').append(newRow);
            $('#removeItemBtn').prop('disabled', false);
            
            // Set tax rates based on current selection
            
            
            // Add event listeners to new row
            addRowEventListeners($('#invoiceItems tbody tr:last'));
            // Remove last item row
            $('.remove-item-btn').click(function() {
                
                    $(this).parent().parent().remove();
                    calculateInvoice();
                
            });

            //select item change
            $(".select-item-change").on("change",function(){
                var item_id = $(this).val();
                var row = $(this).closest('tr');
                $.ajax({
                        url: "<?php echo e(asset('account/fetch-item')); ?>",
                        type: 'post',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        data: {
                            "item_id":item_id
                        },
                        success: function(result) {
                            const item = (result.data);
                            row.find('.item-price').val(item.sales_unit_price);
                            row.find('.item-igst').val(Number(item.tax));

                            updateTaxRates(Number(item.tax));
                        },
                        error: function(xhr) {
                            console.log("error");
                        }
                    });
            });
        });

        

        // Tax type selection
        // $('#taxType').change(function() {
        //     updateTaxRates();
        //     calculateInvoice();
        // });

        // Show/hide CESS
        $('#showCess').change(function() {
            if($(this).is(':checked')) {
                $('#cessContainer').show();
            } else {
                $('#cessContainer').hide();
            }
            calculateInvoice();
        });

        // Update tax rates for all rows
        function updateTaxRates(tax) {
            const taxType = $('#taxType').val();
            $('.item-row').each(function() {
                if(taxType === 'cgst_sgst') {
                    $(this).find('.item-igst').val(0);
                    $(this).find('.item-cgst').val(0);
                    $(this).find('.item-sgst').val(0);
                } else {
                    $(this).find('.item-igst').val(tax);
                    $(this).find('.item-cgst').val(0);
                    $(this).find('.item-sgst').val(0);
                }
            });
        }

        // Add event listeners to a row
        function addRowEventListeners(row) {
            row.find('.item-qty, .item-price, .item-discount').on('input', calculateInvoice);
        }

        // Auto calculation for invoice items
        function calculateInvoice() {
            let subtotal = 0;
            let totalCgst = 0;
            let totalSgst = 0;
            let totalIgst = 0;
            let grandTotal = 0;

            $('.item-row').each(function() {
                const qty = parseFloat($(this).find('.item-qty').val()) || 0;
                const price = parseFloat($(this).find('.item-price').val()) || 0;
                const discount = parseFloat($(this).find('.item-discount').val()) || 0;
                const cgstRate = parseFloat($(this).find('.item-cgst').val()) || 0;
                const sgstRate = parseFloat($(this).find('.item-sgst').val()) || 0;
                const igstRate = parseFloat($(this).find('.item-igst').val()) || 0;
                
                // Calculate item subtotal after discount
                const itemSubtotal = qty * price;
                const discountAmount = itemSubtotal * (discount / 100);
                const itemSubtotalAfterDiscount = itemSubtotal - discountAmount;
                
                // Calculate taxes
                const cgstAmount = itemSubtotalAfterDiscount * (cgstRate / 100);
                const sgstAmount = itemSubtotalAfterDiscount * (sgstRate / 100);
                const igstAmount = itemSubtotalAfterDiscount * (igstRate / 100);
                const itemTotal = itemSubtotalAfterDiscount + cgstAmount + sgstAmount + igstAmount;
                
                // Update item row
                $(this).find('.item-total').val(itemTotal.toFixed(2));
                
                // Add to totals
                subtotal += itemSubtotalAfterDiscount;
                totalCgst += cgstAmount;
                totalSgst += sgstAmount;
                totalIgst += igstAmount;
                grandTotal += itemTotal;
            });

            // Update summary
            $('#subtotal').val(subtotal.toFixed(2));
            $('#cgstTotal').val(totalCgst.toFixed(2));
            $('#sgstTotal').val(totalSgst.toFixed(2));
            $('#igstTotal').val(totalIgst.toFixed(2));
            
            
            if($("#shippingCharges").is(':checked')) {
                var shippingCharge = $("#shippingInput").val();
                grandTotal = Number(grandTotal) + Number(shippingCharge);
            };
            // Calculate CESS if enabled
            if($('#showCess').is(':checked')) {
                const cessPercent = 2; // Example CESS percentage
                const cessAmount = (subtotal * cessPercent) / 100;
                $('#cessTotal').val(cessAmount.toFixed(2));
                grandTotal = parseFloat(grandTotal + cessAmount).toFixed(2);
            }
            
            $('#grandTotal').val(grandTotal);
        }

        // Add event listeners to initial row
        addRowEventListeners($('.item-row'));
        
        // Initial calculation
        calculateInvoice();

        $("#shippingCharges").change(function() {
            if ($(this).is(':checked')) {
                $(".shipping_box").removeClass("d-none");
                
                // Only add shipping input if it doesn't already exist
                if ($(".shipping_input_box").length === 0) {
                    var shipping = `<div class="d-flex justify-content-between shipping_input_box">
                                    <span>Shipping Charge:</span>                                
                                    <span>₹ &nbsp;<input id="shippingInput" type="number" name="shipping_total" class="p-1 border-0" placeholder="0.00" min="0" step="0.01"></span>
                                    </div>`;
                    $(".add_extra_total").append(shipping);
                }
                
                // Handle shipping charge changes
                $(".shipping_charge").on("input", function() {
                    var charge = parseFloat($(this).val()) || 0;
                    $('#shippingInput').val(charge.toFixed(2));
                    calculateInvoice(); // Recalculate the entire invoice
                });
            } else {
                // Remove shipping charge from calculation
                $('.shipping_input_box').remove();
                $(".shipping_box").addClass("d-none");
                $(".shipping_charge").val('');
                calculateInvoice(); // Recalculate the entire invoice
            }
        });

        //select item change
        $(".select-item-change").on("change",function(){
            var item_id = $(this).val();
            var row = $(this).closest('tr');
            $.ajax({
                    url: "<?php echo e(asset('account/fetch-item')); ?>",
                    type: 'post',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {
                        "item_id":item_id
                    },
                    success: function(result) {
                        const item = (result.data);
                        row.find('.item-price').val(item.sales_unit_price);
                        row.find('.item-igst').val(Number(item.tax));
                    },
                    error: function(xhr) {
                        console.log("error");
                    }
                });
        });

        
        
    });
</script>
<?php $__env->stopPush(); ?>
<?php echo $__env->make('layout', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\account_admin\resources\views/accounting/invoice/add.blade.php ENDPATH**/ ?>