@extends('layout.app')

@section('content')
    <div class="card">
        <div class="card-header">
            <h3 class="card-title" style="color:#115548;">Purchase Add</h3>
            <div class="card-tools">
                <a href="{{ route('band-purchase.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('band-purchase.update', $purchase->id) }}" method="POST" class="" id="purchaseForm"
            enctype="multipart/form-data">
            @csrf
            @method('put')

                <div class="row">
                    <div class="col-xl-3 col-md-3 col-12 mb-1">
                        <div class="form-group">
                            <label>Provider <span style="color: red">(require)</span></label>
                            <select class="form-control select2" name="provider_id" id="provider_id" required>
                                <option value="">Select One</option>
                                @foreach ($provider as $item)
                                    <option value="{{ $item->id }}" @if ($item->id == $purchase->provider_id) selected @endif>{{ $item->company_name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="col-xl-3 col-md-3 col-12 mb-1">
                        <div class="form-group">
                            <label>Invoice No <span style="color: red">(require)</span></label>
                            <input type="text" class="form-control" value="{{$purchase->invoice_no}}" id="invoice_no" name="invoice_no">
                            <div id="invoiceWarning"></div>
                            @error('invoice_no')
                                <div class="text-danger mt-2 text-sm ">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                    </div>


                    <div class="col-xl-3 col-md-3 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 <span style="color: red">(require)</span>
                            </label>
                            <div class="input-group date" id="searchTo" data-target-input="nearest">
                                <input type="text" id="billingDate" name="billing_date"  value="{{$purchase->billing_date}}"
                                    class="form-control datetimepicker-input input-group-append"
                                    data-toggle="datetimepicker" data-target="#searchTo" autocomplete="off">
                            </div>
                        </div>
                    </div>
                    <div class="form-group col-md-3">
                        <label for="document" class="block text-sm font-medium text-gray-700">
                            Document <span style="color: green">(optional)</span>
                        </label>
                        <input type="file" name="document" id="document" class="form-control" value="">
                         @php
                            $isS3 = checkSettings('store_image_to_s3') === 'enable';
                            $imgUrl = $isS3
                                ? $purchase->document // assume full URL from S3
                                : (!empty($purchase->document) ? asset('storage/bandPurchase/' . $purchase->document) : null);
                        @endphp
                        @if ($imgUrl)
                            <img src="{{ $imgUrl }}" alt="No Image" class="img-fluid"
                                style="max-width: 100%; height: 100px;" />
                        @else
                            <h6 class="lead">Image Not Provided</h6>
                        @endif
                       
                    </div>
                    @php
                        $service = App\Models\BandService::all();
                    @endphp
                    <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>
                                @foreach ($purchase->purchaseItem as $item)
                                    <tr>
                                        <td style="padding-left: 2px; align: center; display:none">
                                            <input style="width: 90px" class="product_id" value="{{ $item->service_id }}"
                                                type="number" name="service_id[]" required>
                                        </td>
                                        <td style="padding-left: 2px; align: center; display:none">
                                            <input style="width: 90px" class="purchase_item_id" value="{{ $item->id }}"
                                                type="number" name="purchase_item_id[]" required>
                                        </td>
                                        <td style="padding-left: 2px">
                                            <lable style="width: 50px" class="product_name">
                                                {{ $item->service->name ?? '' }}</lable>
                                        </td>


                                        <td style="padding-left: 2px"><input style="width: 150px" class="formDate" id="from"  value="{{ \Carbon\Carbon::parse($item->from_date)->format('d-m-Y') }}" type="text" required name="from_date[]"></td>
                                        <td style="padding-left: 2px"><input style="width: 150px" class="toDate" id="to" value="{{ \Carbon\Carbon::parse($item->to_date)->format('d-m-Y') }}"  type="text" required name="to_date[]"></td>
                                        <td style="padding-left: 2px; align: center">
                                            <input style="width: 90px" class="quantity border-0"
                                                value="{{ $item->quantity ?? '' }}" type="number" name="quantity[]"
                                                min=0 required>
                                        </td>
                                        <td style="padding-left: 2px; align: center">
                                            <input style="width: 90px" class="rate border-0"
                                                value="{{ $item->rate ?? '' }}" type="number" step=".01"
                                                name="rate[]" min=0 required>
                                        </td>
                                        <td style="padding-left: 2px">
                                            <input style="width: 90px" class="vat border-0" type="number"
                                                value="{{ $item->vat ?? '' }}" name="vat[]" min=0>
                                        </td>



                                        <td style="padding-left: 2px"><input style="width: 150px" class="lineTotal" min="0" value="{{$item->line_total}}" 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>
                                @endforeach
                            </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" value="{{$purchase->total_price}}" 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="paidAmount" name="paidAmount" value="{{$purchase->paid}}"
                                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 better 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" value="{{$purchase->total_price - $purchase->paid}}"
                                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 type="text/javascript">
        $(function() {
            $('#invoice_no').on('change', function() {
                $.ajax({
                    type: 'get',
                    url: '{{ route('checkInvoiceNo') }}',
                    data: {
                        inv: $(this).val()
                    },
                    success: function(data) {
                        if (data != true) {
                            $('#invoice_no').css('border', '1px solid red');
                            $('#invoiceWarning').html(
                                '<span style="color:red">Already Exist</span>');
                        } else {
                            $('#invoice_no').css('border', '1px solid #ddd');
                            $('#invoiceWarning').html(
                                '<span style="color:green">You can use</span>');
                        }
                    }
                });
            });
        });
    </script>

    <script>
        let billinngMonth = null;
        let firstDay = null;
        let lastDay = null;
        $(document).ready(function() {
            let billingDate = "{{$purchase->billing_date}}"; // Laravel value
            let formattedDate = moment(billingDate).format('MM/DD/YYYY');

            // Manually set the input value and trigger change
            $('#billingDate').val(formattedDate);

            setCurrentBillingDate();
            getValue();

            $('#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 setCurrentBillingDate() {
                billinngMonth = $("#billingDate").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);
            }
        });

        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() {
            $(".formDate").flatpickr({
                dateFormat: "d-m-Y",
                minDate: getFirstDayOfMonth(),
                maxDate: getLastDayOfMonth()
            });
        });

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

        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() {

            var totalSum = 0;
            var subTotal = 0;

            $("tr").each(function() {
                var thisObj = $(this); // Get the current row element
                var qty = parseFloat(thisObj.find("input.quantity").val()) || 0;
                var rate = parseFloat(thisObj.find(".rate").val()) || 0;
                var vat = parseFloat(thisObj.find(".vat").val()) || 0;
                let form_date = thisObj.find(".formDate").val();
                let to_date = thisObj.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;

                // Set the calculated value in the table cell
                thisObj.find(".lineTotal").val(lineTotalWithVat.toFixed(2));  // Formats to two decimal places
            });


            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 due = 0 ;
            due = sumOfLineTotal - paidAmount;

            $('#DueAmount').val(due.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();
        });

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

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