@extends('layout')
@section('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 Debit Note</h2>
        <div class="page-header">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb ">
                    <li class="breadcrumb-item"><a href="{{ asset('dashboard') }}">{{ __('message.dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ asset('account/debit-note') }}">Debit Note</a></li>
                    <li class="breadcrumb-item active" aria-current="page">{{ __('message.add') }}</li>
                </ol>
            </nav>
        </div>

        <div class="card">
            <x-flashMessage />
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <form action="{{asset('account/add-debit-note')}}" method="post">
                @csrf
                <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" required>
                                    <option selected disabled>Select</option>
                                    @foreach($customers as $cus)
                                        <option value="{{$cus->id}}">{{$cus->name}}</option>
                                    @endforeach
                                </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">Debit Note No.</label>
                                <input type="number" class="form-control py-2 col-7 border" name="debit_note_number" value="{{$dr_no}}" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group d-flex row">
                                <label class="font-weight-bold col-5 pt-2">Date</label>
                                <input type="date" class="form-control py-2 col-7 border" name="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">Bill Date</label>
                                <input type="date" class="form-control py-2 col-7 border bill_date" name="bill_date" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-2">
                            <label class="font-weight-bold pt-2">Bill No</label>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group d-flex">
                                
                                <select class="form-control py-2 border select2 change_bill_number" name="bill_id" required>
                                    <option selected disabled>Select</option>
                                    @foreach($bills as $bill)
                                    <option value="{{$bill->id}}">{{$bill->bill_number}}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-7">
                            <div class="form-group row">
                                <label class="col-2">Reason</label>
                                <input type="text" name="reason" class="form-control col-10">
                            </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>
                                        @foreach($items as $item)
                                            <option value="{{$item->id}}">{{$item->name}}</option>
                                            
                                        @endforeach
                                    </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" > <label for="showCess" class="pt-2">&nbsp; Show CESS</label>
                                </div>

                                <div class="checkbox-label mt-2">
                                    <input type="checkbox" id="addOtherCharges"> <label for="addOtherCharges" class="pt-2">&nbsp; Add Other Charges</label>
                                </div>
                                
                                <div id="otherChargesContainer" class="mt-2" style="display:none;">
                                    <div class="additional-charge-row">
                                        <div class="row">
                                            <div class="col-md-5">
                                                <input type="text" class="form-control" placeholder="Charge Name" id="otherChargeName">
                                            </div>
                                            <div class="col-md-5">
                                                <input type="number" class="form-control" placeholder="Amount" id="otherChargeAmount" min="0" step="0.01">
                                            </div>
                                            <div class="col-md-2">
                                                <button type="button" class="btn btn-sm btn-success" id="addOtherChargeBtn">Add</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="checkbox-label mt-2">
                                    <input type="checkbox" id="applyDiscount"> <label for="applyDiscount" class="pt-2">&nbsp; Apply All Discount</label>
                                </div>
                                
                                <div id="discountContainer" class="mt-2" style="display:none;">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <input type="number" class="form-control" placeholder="Discount Percentage" id="discountPercentage" min="0" max="100">
                                        </div>
                                        <div class="col-md-4">
                                            <button type="button" class="btn btn-sm btn-primary" id="applyDiscountBtn">Apply</button>
                                        </div>
                                    </div>
                                </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="d-flex justify-content-between" id="cessContainer" style="display:none;">
                                    <span>Other Charge:</span>
                                    <input type="hidden" min="0" max="100" name="others_charge_name" id="others_charge_name">
                                    <span>₹ &nbsp;<input id="others_charge_amount" type="text" name="others_charge_amount" class="p-1 border-0" placeholder="0.00"></span>
                                </div>
                                <div class="d-flex justify-content-between" id="cessContainer" style="display:none;">
                                    <span>All Discount:</span>
                                    <input type="hidden" min="0" max="100" name="all_discount_percentage" id="all_discount_percentage">
                                    <span>₹ &nbsp;<input id="all_discount_amount" type="text" name="all_discount_amount" 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>
@endsection

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

         // Show/hide other charges input
        $('#addOtherCharges').change(function() {
            $('#otherChargesContainer').toggle(this.checked);
        });

        // Show/hide discount input
        $('#applyDiscount').change(function() {
            $('#discountContainer').toggle(this.checked);
            if (!this.checked) {
                discountPercentage = 0;
                $('#discountSummary').hide();
                calculateInvoice();
            }
        });
            // Add other charge
        $('#addOtherChargeBtn').click(function() {
            const chargeName = $('#otherChargeName').val();
            const chargeAmount = parseFloat($('#otherChargeAmount').val()) || 0;
            
            if (chargeName && chargeAmount > 0) {
                otherCharges = chargeAmount;
                // Add to summary
                $('#otherChargesSummary').append(`
                    <div class="d-flex justify-content-between" data-charge="${chargeName}">
                        <span>${chargeName}:</span>
                        <span>₹ &nbsp;<input type="text" value="${chargeAmount.toFixed(2)}" class="p-1 border-0" readonly></span>
                    </div>
                `);
                
                // show other charge
                $('#others_charge_name').val(chargeName);
                $('#others_charge_amount').val(chargeAmount);
                
                calculateInvoice();
            }
        });

        // Apply discount
        $('#applyDiscountBtn').click(function() {
            discountPercentage = parseFloat($('#discountPercentage').val()) || 0;
            if (discountPercentage > 0) {
                $('#discountSummary').show();
                calculateInvoice();
            }
        });


        // 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>
                            @foreach($items as $item)
                                <option value="{{$item->id}}">{{$item->name}}</option>
                            @endforeach
                        </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: "{{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);
            }
            // Add other charges
                let otherChargesTotal = 0;
                
                otherChargesTotal += otherCharges;
                
                grandTotal += otherChargesTotal;
                
                // Apply discount if enabled
                let allDdiscountAmount = 0;
                if (discountPercentage > 0) {
                    allDdiscountAmount = (grandTotal * discountPercentage) / 100;
                    $('#discountAmount').val(allDdiscountAmount.toFixed(2));
                    $("#all_discount_percentage").val(discountPercentage);
                    $("#all_discount_amount").val(allDdiscountAmount.toFixed(2));

                    grandTotal -= allDdiscountAmount.toFixed(2);
                }
            
            $('#grandTotal').val(grandTotal.toFixed(2));
        }

        // 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: "{{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");
                    }
                });
        });

        //change invoice number
        $(".change_bill_number").on("change",function(){
            var invoice_id = $(this).val();
            $.ajax({
                    url: "{{asset('account/fetch-bill-details')}}",
                    type: 'post',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {
                        "invoice_id":invoice_id
                    },
                    success: function(result) {
                        var invoiceData = result.data;
                        //console.log(invoiceData);
                        $(".bill_date").val(invoiceData.bill_date);
                    },
                    error: function(xhr) {
                        console.log("error");
                    }
                });
        });

        
        
    });
</script>
@endpush