@extends('layouts.app')

@section('title')
    All Balloting Map Files
@stop

@section('breadcrumb')
    <ol class="breadcrumb pull-right">
        <li><a href="{{ route('home') }}"><i class="fa fa-dashboard"></i> Home</a></li>

        <li class="active">Pre-Condition Inventory List</li>
    </ol>
@stop
@section('css')
@livewireStyles
    <style type="text/css">
        .swal2-popup {
            font-size: 2.0rem !important;
        }

        .bg-color {
            background-color: #1c3752;
        }

        .anchor-link {
            display: none;
        }

        body {
            font-weight: bold;
        }

        #slider {
            height: 34px;
            -webkit-appearance: none;
            appearance: none;
            background-color: #ddd;
            outline: none;
            padding: 0;
            margin: 0;
            border-radius: 0px;
        }

        #slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #555;
            cursor: pointer;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
        }

        #slider::-moz-range-thumb {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #555;
            cursor: pointer;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
        }

        #switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        #switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        #slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            -webkit-transition: .4s;
            transition: .4s;
        }

        #slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
        }

        input:checked+#slider {
            background-color: #2196F3;
        }

        input:focus+#slider {
            box-shadow: 0 0 1px #2196F3;
        }

        input:checked+#slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        /* Rounded sliders */
        #slider.round {
            border-radius: 34px;
        }

        #slider.round:before {
            border-radius: 50%;
        }
    </style>
    <style type="text/css" media="print">
        @media print {
            .page-wrapper {
                font-size: 12px !important;
                font-family: "time-new-roman", Arial, sans-serif !important;
                color: black !important;
            }

            h3 {
                line-height: 1px;
            }

            h3 strong {
                text-transform: uppercase;
                color: black !important
            }

            h4 strong {
                text-transform: uppercase;
                color: black !important
            }

            body {
                font-weight: bold;
            }

            .printFH11 {
                font-size: 13px;
                font-weight: 800;
                background-color: #000000;
            }

            .white-box .box-title {
                margin: 0px 0px 4px 0px;
                font-weight: 700;
                font-size: 14px;
                color: #1c3752;
                background-color: #000000 !important;
            }

            .white-box {
                padding: 0px 0px 2px 0px;
                margin-bottom: 0px;
                margin-bottom: 0;
                border-radius: inherit;
            }

            .table {
                width: 100% !important;
                margin-bottom: 5px;
                margin-top: -2px;
            }

            .table>tbody>tr>td,
            .table>tbody>tr>th,
            .table>tfoot>tr>td,
            .table>tfoot>tr>th {
                vertical-align: top;
            }

            .page-wrapper {
                padding-top: 0px;
            }
        }

        .select2-container {
            width: 300px;
            /* set the width to 300 pixels */
        }
    </style>

@stop
@section('content')


    <div class="container-fluid">
        <!-- /row -->
        <div class="row">


            <div class="col-md-12">
                @if ($errors->any())
                    <div class="white-box">
                        <h2>Errors</h2>
                        <ul>
                            {!! implode('', $errors->all('<li><span class="help-block"><strong>:message</strong></span></li>')) !!}
                        </ul>
                    </div>
                @endif
                @php
                    $total_val = count($allStatements);
                @endphp
                <div class="white-box">
                    <h3 class="box-title m-b-0"><i class="icon-layers fa-fw"></i> Pre-Condtion Invnetory List</h3>

                    <p class="text-muted  font-13"> Total Inventories are : <span class="label label-success"
                            id='total'>{{ $total_val }}</span></p>

                    <hr>

                </div>
            </div>

        </div>
      
        @livewire('start-live-balloting',['multipro_id' => $multipro_id,
        'pre_cond'=>$pre_cond,
        'balloting_files'=>$balloting_files,
        'allStatements' =>$allStatements])

    </div>
    <!-- /.container-fluid -->

@stop

@section('js')
@livewireScripts
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
  
    <script>
 

    Livewire.on('reInitializeSelect2', function () {
        // Reinitialize Select2 after the button is clicked
        selectCall();
       
    });

    
    
          
//         function submitForm() {
//     var formData = new FormData(document.getElementById('myForm'));
//     console.log(formData);

//     Livewire.emit('submitForm', formData);
// }

        $(function() {
            $('#myTable').DataTable();

            var table = $('#example').DataTable({
                "columnDefs": [{
                    "visible": false,
                    "targets": 2
                }],
                "order": [
                    [2, 'asc']
                ],
                "displayLength": 25,
                "drawCallback": function(settings) {
                    var api = this.api();
                    var rows = api.rows({
                        page: 'current'
                    }).nodes();
                    var last = null;
                    api.column(2, {
                        page: 'current'
                    }).data().each(function(group, i) {
                        if (last !== group) {
                            $(rows).eq(i).before('<tr class="group"><td colspan="5">' + group +
                                '</td></tr>');
                            last = group;
                        }
                    });
                }
            });
            // Order by the grouping
            $('#example tbody').on('click', 'tr.group', function() {
                var currentOrder = table.order()[0];
                if (currentOrder[0] === 2 && currentOrder[1] === 'asc') {
                    table.order([2, 'desc']).draw();
                } else {
                    table.order([2, 'asc']).draw();
                }
            });
        });
        $('#example23').DataTable({
            dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ]
        });

        function removeParentDiv(self) {
            var id = $(self).closest('tr').data("id");

            // console.log(id);
            $('#account_tr_' + id).remove();
            count = $('#total').text();
            $('#total').text(parseInt(count) - 1);


        }

        var count = {{ $total_val }};

        function addNewRow() {

            count = parseInt(count) + 1;
            var account_row = `<tr height="2px" id="custom_account_tr_` + count + `"
                                            data-id="` + count + `" >
                                            <input type='hidden' wire:model.defer='dynamic_inventory_id.`+count+`' id='inventory_id` + count + `' >
                                            <td id='count` + count +
                `'>

                                              
                                                
                                            </td>
                                            <td  >
                                                <select class='js-example-basic-single' name="customer_property" id='customer_property` +
                count + `'
                                                class="form-control "
                                                 onchange='getInformation(this.value,{data_id:` + count + `})'>
                                                 <option value='' select=''> None</option>
                                                
                                                     
                                               
                                            </select> 
                                            </td>
                                            <td id='plot_size` + count + `'></td>
                                            <td id='customer_name` + count + `'></td>



                                               <td id='net_pay` + count + `'></td>


                                              




                               <td id='booking_data` + count + `'></td>
                               <td id='unit_category_id` + count + `'></td>
                                          

                                            <td class="pt-3-half name">

                                                <button type="button" class="btn btn-sm btn-danger btn-sm"
                                                    onclick="removeCustomParentDiv(this)"><i
                                                        class="fa fa-times"></i></button>
                                            </td>

                                        </tr>
                                             `;

            // var tr_id =count -1;
            var lastrow = $('#state_table').find('tr').last();
            $(lastrow).after(account_row);
            $('#count' + count).text(count);
            //    $('#custom_account_tr_'+0).after(account_row);

            selectCall();
        }
      

        function removeCustomParentDiv(self) {
            var id = $(self).closest('tr').data("id");


            $('#custom_account_tr_' + id).remove();
            count = $('#total').text();
            selectCall();
        }

        function getInformation(value, data) {
            //     console.log(value); // logs the selected value of the select element
            //   console.log(data.data_id);
            $.ajax({
                url: '{{ route('balloting.get.inventory-info') }}',
                data: {
                    id: value
                },
                dataType: 'json',
                success: function(response) {
                    // Get the input array using jQuery
                    var inputArray = $('input[name="inventory_id[]"]');
                    var match_count = 0;
                    // Loop through the array to compare each value with item.id
                    inputArray.each(function() {
                        var inputValue = $(this).val(); // Get the value of the current input
                        // The ID to match against

                        // Check if the input value matches the item ID
                        if (inputValue == response.id) {
                            // Trigger a SweetAlert alert
                            Swal.fire("Match found!", "This Unit number  all ready selected.", "error");
                            match_count = match_count + 1;
                        }

                    });

                    if (match_count > 0) {
                        $('#customer_property' + data.data_id).val(null).trigger('change');
                        return false;

                    }
                    // val_t= $('#total').text();
                    //    $('#total').text(parseInt(val_t) + 1);
                    $('#unit_category_id' + data.data_id).empty();
                    $('#inventory_id' + data.data_id).val(response.id);
                    $('#plot_size' + data.data_id).text(response.size + ' Marla');
                    $('#customer_name' + data.data_id).text(response.name);
                    $('#net_pay' + data.data_id).text(response.netpay);
                    $('#booking_data' + data.data_id).text(response.data);

                    var mySubtype = document.getElementById("unit_category_id" + data.data_id);


                    var select = $("<select>").attr("id", "subtypeunit_category_id_" + response.id).attr("name",
                        "unit_category_" + response.id + "[]").attr("multiple", "multiple");

                    // var selectList = document.createElement("select");
                    var id = "subtypeunit_category_id_" + response.id;
                    // selectList.name = "unit_category_"+response.id+"[]";
                    // selectList.multiple="";
                    // selectList.class="form-control chosen-select";
                    // mySubtype.appendChild(selectList);
                    // mySubtype.appendChild(select);
                    $('#unit_category_id' + data.data_id).append(select);


                    var unit_category = "<option value='' >None</option>";

                    for (var i = 0; i < response.category_id.length; i++) {
                        unit_category += "<option value='" + response.category_id[i] + "'>" + response
                            .category_name[
                                i] +
                            "</option>";

                    }
                    $("#" + id).html(unit_category);
                    $("#" + id).chosen({
                        width: "100%", // Set the width of the dropdown
                        // Set the maximum number of options that can be selected
                        placeholder_text_multiple: "Select..", // Set the placeholder text for the multi-select
                    });




                    //    set Perference data

                    // var chosenSelect1 = $(".chosen-select");
                    // selectList.chosen();
                    //                     $('#unit_category_id'+data.data_id).appened()

                },
                error: function() {
                    // Handle errors
                }
            });
        }

        function selectCall() {
            var multi_value= $('#multipro_id').val();
            $('.js-example-basic-single').select2({
                width: '250px',
                placeholder: 'Search Unit Number...',
                ajax: {
                    url: '{{ route('balloting.get.inventory-unit') }}',

                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            q: params.term, // search term
                            multipro_id: multi_value
                        };
                    },
                    processResults: function(data) {
                        return {
                            results: $.map(data, function(item) {

                                return {
                                    id: item.id,
                                    text: item.text
                                }
                            })
                        };
                    },
                    cache: true

                }
            });
        }

        function confirmSubmit() {
            Swal.fire({
                title: "Are you sure?",
                text: "Do you want to Lock these inventories for balloting?",
                icon: "warning",
                buttons: ["No", "Yes"]
            }).then((confirm) => {
                if (confirm) {
                    // User clicked "Yes", submit the form
                    document.getElementById("myForm").submit();
                } else {
                    // User clicked "No", do nothing

                }
            });
        }


        function getMapData(self) {

            
            val = $("#map_file").val();

            var pc_id = "{{ $pre_cond->id }}";

            // val = $(self).val();
            $('.preloader').fadeIn();
            $.ajax({
                url: `{{ route('balloting.get.map.data') }}`,

                type: 'GET',
                data: {
                    id: val,
                    pc_id: pc_id
                },
                dataType: 'json',
                success: function(response) {
                    $('.preloader').fadeOut();
                    var sector = "<option value='' >None</option>";

                    for (var i = 0; i < parseInt(response.sector.length); i++) {
                        sector += "<option value='" + response.sector[i].unit_block_id + "'>" + response.sector[
                                i].sector +
                            "</option>";

                    }
                    $("#sector_0").html(sector);
                    // Livewire.emit('updateSelectValue',  val);
                    return true;
                    //    set Perference data

                    // var chosenSelect1 = $(".chosen-select");
                    // chosenSelect1.chosen("destroy");
                    // $("#feature_0").empty();
                    // $("#sector_pre").empty();
                    // $("#road_category_0").empty();
                    // var road = "<option value='' >None</option>";
                    // var sector = "<option value='' >None</option>";
                    // var feature = "<option value='' >None</option>";
                    // for (var i = 0; i < parseInt(response.map.length); i++) {

                    //     road += "<option value='" + response.map[i].unit_floor_id + "'>" + response.map[i]
                    //         .street +
                    //         "</option>";
                    //     sector += "<option value='" + response.map[i].unit_block_id + "'>" + response.map[i]
                    //         .sector +
                    //         "</option>";
                    //     feature += "<option value='" + response.map[i].unit_category_ids + "'>" + response.map[
                    //             i]
                    //         .feature +
                    //         "</option>";
                    // }

                    // $("#feature_0").html(feature);
                    // $("#sector_pre").html(sector);
                    // $("#road_category_0").html(road);
                    // $(".chosen-select").chosen();
                    //  end set preference data



//                     Swal.fire({
//                         title: 'Inventory Differences',
//                         html: ` <strong>Between Map and Pre Condition Inventory List</strong><br> 

// `,
//                         icon: 'info',
                         
//                         showCloseButton: true,
//                         showCancelButton: true,
//                         focusConfirm: false,
//                         confirmButtonText: '<i class="fa fa-thumbs-up"></i> Ok Continue!',
//                         confirmButtonAriaLabel: 'Thumbs up, great!',
//                         cancelButtonText: '<i class="fa fa-thumbs-down"></i>',
//                         cancelButtonAriaLabel: 'Thumbs down'
//                     })
//                     console.log(response);
                },
                error: function(xhr, status, error) {
                    $('.preloader').fadeOut();
                    // $('.preloader').fadeOut();
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Unable to fetch Map data!',

                    })
                }

            });

        }
        



        // Get the checkbox element
        const checkbox = document.getElementById('specific_block');

        // Add an event listener to the checkbox
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                // Checkbox is checked

                $('#specficblock').show();


            } else {
                // Checkbox is not checked
                $('#specficblock').hide();


            }
        });

        $('#start_balloting_old').submit(function(e) {
            e.preventDefault();
           

            var form_data = $(this).serialize();
            var pre_condition = $('#pre-condition').val();
            var map_file = $('#map_file').val();


            if (map_file == "") {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Map File is required!',

                })
                return false;
            }

            function updateProgressBar() {

                $.ajax({
                    url: '{{ route('balloting.progress') }}',
                    success: function(data) {
                        // Update progress bar
                        $('.progress-bar').css('width', data.progress + '%').text(data.progress + '%');
                        $('#progress_val').empty();
                        $('#progress_val').text(data.progress);

                        // Check if process is complete
                        if (data.progress == 100) {

                            clearInterval(progressInterval);
                        }
                    }
                });
            }
            var progressInterval = setInterval(updateProgressBar, 2000); // Send a request every 5 seconds





            Swal.fire({
                title: 'Balloting Start',
                html: `  Importing...   <span id='progress_val'></span>%<div class="progress">
                             <div class="progress-bar" role="progressbar" style="width: {{ session('progress') }}%" aria-valuenow="{{ session('progress') }}" aria-valuemin="0" aria-valuemax="100">{{ session('progress') }}%</div>
                             </div>`,
                showConfirmButton: false,
                allowOutsideClick: false,
                allowEscapeKey: false,


            });
            //    return false;
            $('.preloader').fadeIn();







            $.ajax({
                url: "{{ route('balloting.start.store.data') }}",
                type: 'POST',
                data: form_data,
                success: function(response) {

                    $('.preloader').fadeOut();

                    if (response.success) {

                        Swal.fire({
                            icon: 'success',
                            title: 'Balloting Completed Successfully',

                            confirmButtonText: 'Ok',

                        }).then((result) => {
                            /* Read more about isConfirmed, isDenied below */
                            if (result.isConfirmed) {
                                {!! session()->forget('progress') !!}
                                window.location.href =
                                    `{{ route('balloting.map.inventory', ':id') }}`.replace(
                                        ':id', response.id);
                            }
                        })
                    }
                },
                error: function(xhr, status, error) {
                    $('.preloader').fadeOut();
                    clearInterval(progressInterval);
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Something went wrong!',

                    })
                }
            });

        });
        // Get the checkbox element
        const checkbox2 = document.getElementById('add_preference');

        // Add an event listener to the checkbox
        checkbox2.addEventListener('change', function() {
            if (this.checked) {
                // Checkbox is checked

                $('#preference').show();

            } else {
                // Checkbox is not checked
                $('#preference').hide();



            }
        });
        $('#select_property').select2({
            width: '300px',
            placeholder: 'Search Unit Number...',
            ajax: {
                url: '{{ route('balloting.get.inventory') }}',

                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        q: params.term, // search term

                    };
                },
                processResults: function(data) {
                    return {
                        results: $.map(data, function(item) {
                            return {
                                id: item.id,
                                text: item.text
                            }
                        })
                    };
                },
                cache: true

            }


        });
    </script>
@stop
