@extends('layout.app')

@section('content')
    <div class="card">
        <div class="card-header">
            <h3 class="card-title" style="color:#115548;">Create Invoice</h3>
            <div class="card-tools">
                <a href="{{ route('bw-sale.index') }}"><button class="btn btn-sm btn-primary"><i
                            class="fa fa-arrow-circle-left" aria-hidden="true"></i> &nbsp; Back</button></a>
            </div>
        </div>

        <div class="card-body">
            <form action="{{ route('bw-sale.store') }}" method="POST" class="" id="purchaseForm"
                enctype="multipart/form-data">
                @csrf

                <div class="row">
                    <div class="col-xl-4 col-md-4 col-12 mb-1">
                        <div class="form-group">
                            <label>Customer</label>
                            <select class="form-control select2" name="customer_id" id="customer_id" required>
                                <option value="">Select One</option>
                                @foreach ($customer as $item)
                                    <option value="{{ $item->id }}">{{ $item->customer_name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-xl-4 col-md-4 col-12 mb-1" style="display: none">
                        <div class="form-group">
                            <label>Invoice No</label>
                            <input type="text" class="form-control" id="invoice_no" name="invoice_no" readonly>
                        </div>
                    </div>

                    <div class="col-xl-4 col-md-4 col-12 mb-1">
                        <div class="form-group">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="billing_date" required>
                                Billing Date
                            </label>
                            <div class="input-group date" id="searchTo" data-target-input="nearest">
                                <input type="text" id="billingDate" name="billing_date" value=""
                                    class="form-control datetimepicker-input input-group-append"
                                    data-toggle="datetimepicker" data-target="#searchTo" autocomplete="off">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-5">
                        <label>Select Service</label>
                        <select class="form-control " id="serviceId">
                            <option value="">Select One</option>
                            @foreach ($service as $item)
                                <option value="{{ $item->id }}">{{ $item->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <p class="text-danger h3">Note: By changing Billing Date all data will be reset</p>
                <div class="row">
                    <div class="table-responsive">
                        <table id="result" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th style="padding-left: 2px;padding-right: 2px">Service </th>
                                    <th style="padding-left: 2px;padding-right: 2px">From Date</th>
                                    <th style="padding-left: 2px;padding-right: 2px">To Date</th>
                                    <th style="padding-left: 2px;padding-right: 2px">Quantity(MB)</th>
                                    <th style="padding-left: 2px;padding-right: 2px">Rate(TK)</th>
                                    <th style="padding-left: 2px;padding-right: 2px">Vat(%)</th>
                                    <th style="padding-left: 2px;padding-right: 2px">Value(Line Total)</th>
                                    <th style="padding-left: 2px;padding-right: 2px">Action</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="col-md-3 float-right">
                            <input type="number" class="form-control" id="totalPrice" name="totalPrice" autocomplete="off"
                                step=".01" min="0" readonly>
                        </div>
                        <div class="col-md-3 float-right">
                            Sub Total
                        </div>

                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-12">
                        <div class="col-md-3 float-right">
                            <input type="number" class="form-control" id="discount" name="discount" autocomplete="off"
                                value="0" step=".01" min="0">
                        </div>
                        <div class="col-md-3 float-right">
                           Discount
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="col-md-3 float-right">
                            <input type="number" class="form-control" id="grandtotal" name="grandtotal" autocomplete="off"
                                step=".01" min="0" readonly>
                        </div>
                        <div class="col-md-3 float-right">
                            Total
                        </div>

                    </div>
                </div>

                <div class="row mt-2">
                    <div class="col-md-12">
                        <div class="col-md-3 float-right">
                            <input type="number" class="form-control" id="paidAmount" name="paidAmount" autocomplete="off"
                                value="0" step=".01" min="0">
                        </div>
                        <div class="col-md-3 float-right">
                            Paid <span style="color: green">(The paid amount will not be getter than the total
                                amount.)</span>
                        </div>
                    </div>
                </div>

                <div class="row mt-2">
                    <div class="col-md-12">
                        <div class="col-md-3 float-right">
                            <input type="number" class="form-control" id="DueAmount" name="DueAmount" autocomplete="off"
                                step=".01" min="0" readonly>
                        </div>
                        <div class="col-md-3 float-right">
                            Due
                        </div>
                    </div>
                </div>


                <button class="btn btn-primary waves-effect waves-float waves-light float-right mt-2" type="submit"
                    id="submitButton">Submit
                </button>
            </form>
        </div>
    </div>

    <style>
        li.selected {
            background: #17A2B8 !important;
        }
    </style>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
@endsection

@section('ajax')
    <script src="{{ asset('adminlte/js/jquery.validate.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>

    <script>
        let billinngMonth = null;
        let firstDay = null;
        let lastDay = null;
        $(document).ready(function() {
            $('#billingDate').on('blur change', function() {
                billinngMonth = $(this).val();
                dateStr = billinngMonth;
                var dateParts = dateStr.split('/');
                var month = parseInt(dateParts[0], 10) - 1; // Months are 0-based in JavaScript Date
                var day = parseInt(dateParts[1], 10);
                var year = parseInt(dateParts[2], 10);

                var date = new Date(year, month, day);


                firstDay = new Date(date.getFullYear(), date.getMonth(), 1);


                lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

                $('#result tbody').empty();
                setToalAndSubTrackPaidAmount();

            });
        });

        function formatDateString(date) {
            let day = date.getDate();
            let month = date.getMonth() + 1; // Months are 0-based in JavaScript Date
            let year = date.getFullYear();
            return `${day}-${month}-${year}`;
        }

        function myFunction() {}

        // Function to get the first day of the current month
        function getFirstDayOfMonth() {

            if (billinngMonth) {
                return formatDateString(firstDay);
            } else {

                var today = new Date();
                var firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
                return firstDayOfMonth;
            }
        }

        // Function to get the last day of the current month
        function getLastDayOfMonth() {

            if (billinngMonth) {
                return formatDateString(lastDay);
            } else {

                var today = new Date();
                var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                return lastDayOfMonth;
            }
        }

        function getDaysInCurrentMonth() {
            if (billinngMonth) {
                return lastDay.getDate();
            } else {

                var now = new Date();
                var year = now.getFullYear();
                var month = now.getMonth();

                // Create a date object for the first day of the next month
                var nextMonth = new Date(year, month + 1, 1);

                // Subtract one day to get the last day of the current month
                var lastDayOfCurrentMonth = new Date(nextMonth - 1);

                return lastDayOfCurrentMonth.getDate();
            }
        }

        const fetchData = (productId) => {

            searchResult(productId);
        }

        $('#serviceId').change(() => {

            var serviceSelect = $('#serviceId').val();

            if (serviceSelect) {

                fetchData(serviceSelect);
            }

        });

        function searchResult(productId) {
            $.ajax({
                type: 'get',
                url: '{{ route('productinfo') }}',
                data: {
                    data: productId
                },
                success: function(res) {

                    r = res;
                    var check = 0;

                    var id = $('#serviceId').val();

                    if (check == 0) {
                        $('#result tbody').append('<tr>' +
                            '<td style="padding-left: 2px; align: center; display:none"><input style="width: 90px" class="product_id" value="' +
                            r.id + '" type="number" name="service_id[]" required></td>' +
                            '<td style="padding-left: 2px"><lable style="width: 50px" class="product_name"> ' +
                            r.name + '</td>' +

                            '<td style="padding-left: 2px"><input style="width: 150px" class="formDate" id="from" type="text" required name="from_date[]"></td>' +
                            '<td style="padding-left: 2px"><input style="width: 150px" class="toDate" id="to" type="text" required name="to_date[]"></td>' +

                            '<td style="padding-left: 2px"><input style="width: 150px" class="quantity" min="0" value="0" type="number" step="0.001" required name="quantity[]" ></td>' +
                            '<td style="padding-left: 2px"><input style="width: 150px" class="rate" min="0" value="0" type="number" step="0.01" required name="rate[]"></td>' +
                            '<td style="padding-left: 2px"><input style="width: 150px" class="vat" min="0" value="0" type="number" step="0.01" required name="vat[]" ></td>' +
                            '<td style="padding-left: 2px"><input style="width: 150px" class="lineTotal" min="0" value="0" type="number" step="0.01" readonly required name="lineTotal[]"></td>' +
                            '<td style="padding-left: 2px"><button type="button" name="remove" class="btn btn-danger btn-sm remove"><i class="fa fa-minus-circle"></i></button></td>' +
                            '</tr>');

                        // getValue();

                        $(function() {
                            $(".formDate").flatpickr({
                                dateFormat: "d-m-Y",
                                minDate: getFirstDayOfMonth(),
                                maxDate: getLastDayOfMonth()
                            });
                        });

                        $(function() {
                            $(".toDate").flatpickr({
                                dateFormat: "d-m-Y",
                                minDate: getFirstDayOfMonth(),
                                maxDate: getLastDayOfMonth()
                            });
                        });
                    } else {
                        alert('Product already added.');
                    }
                }
            });
        }






        function getValue(thisObj) {

            var totalSum = 0;
            var subTotal = 0;

            $("tr").each(function() {
                var qty = parseFloat(thisObj.parents("tr").find("input.quantity").val()) || 0;
                var rate = parseFloat(thisObj.parents("tr").find(".rate").val()) || 0;
                var vat = parseFloat(thisObj.parents("tr").find(".vat").val()) || 0;
                let form_date = thisObj.parents("tr").find(".formDate").val();
                let to_date = thisObj.parents("tr").find(".toDate").val();


                let days = calculateDateDifference(form_date, to_date);
                let totalDaysInThisMonth = getDaysInCurrentMonth();


                let lineTotal = 0;
                if (totalDaysInThisMonth === days) {
                    lineTotal = qty * rate;
                } else {
                    lineTotal = ((qty * rate) / totalDaysInThisMonth) * days;
                }



                let totalVat = 0;
                if (vat > 0) {
                    totalVat = (lineTotal * vat) / 100;
                }

                let lineTotalWithVat = lineTotal + totalVat;


                thisObj.parents("tr").find(".lineTotal").val(lineTotalWithVat.toFixed(2));
            });

            setToalAndSubTrackPaidAmount();


        };

        function setToalAndSubTrackPaidAmount() {
            let sumOfLineTotal = 0;
            $("tr .lineTotal").each(function(index, value) {

                thisLineTotal = parseFloat($(this).val());
                sumOfLineTotal = sumOfLineTotal + thisLineTotal;

            });

            $('#totalPrice').val(sumOfLineTotal.toFixed(2));

            let paidAmount = $('#paidAmount').val();
            let discount = $('#discount').val();

            let grandTotal = 0;
            grandTotal = sumOfLineTotal - discount;

            let due = 0;
            due = sumOfLineTotal - paidAmount - discount;

            $('#DueAmount').val(due.toFixed(2));
            $('#grandtotal').val(grandTotal.toFixed(2));

        };





        function calculateDateDifference(startDate, endDate) {
            var start = moment(startDate, "DD-MM-YYYY");
            var end = moment(endDate, "DD-MM-YYYY");
            var difference = end.diff(start, 'days') + 1;
            return Math.abs(difference);
        }

        $(document).on("keyup", ".vat", function(event) {
            getValue($(this));
        });

        $(document).on("keyup", ".rate", function(event) {
            getValue($(this));
        });

        $(document).on("keyup", ".quantity", function(event) {
            getValue($(this));
        });
        $(document).on("change", ".formDate", function(event) {
            getValue($(this));
        });
        $(document).on("change", ".toDate", function(event) {
            getValue($(this));
        });
        $(document).on("keyup", "#paidAmount", function(event) {
            setToalAndSubTrackPaidAmount();
        });
        $(document).on("keyup", "#discount", function(event) {
            setToalAndSubTrackPaidAmount();
        });
        $(document).on("click", ".remove", function(event) {
            $(this).closest("tr").remove();
            setToalAndSubTrackPaidAmount();
        });
    </script>
@endsection
