<?php
$user_id = $_GET['mkid'];
$allmikrotik = $obj->details_by_cond('re_mikrotik_user', "id=$user_id"); 


?>

<div class="col-xl-12">
    <div class="card h-100 p-0">
        <div class="card-header border-bottom bg-base py-16 px-24">
            <h6 class="text-lg fw-semibold mb-0">Mikrotik Connection</h6>
        </div>
        <div class="card-body p-24">
           <div class="row">
            <div class="col-md-10">
                 <div class="d-flex flex-wrap align-items-center gap-3">
                    <div class="col-md-2 mb-2"> <span id="m<?php echo $allmikrotik ['id']; ?>"><button class="btn btn-primary" type="button" disabled> <span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span> Loading...</button> </span></div>
               
            </div>
            </div>
            
            

                <div class="col-md-2 text-end">
                    <button class="btn btn-primary" type="button" id="add_all_customer">Import All Unmatching Data</button>
                </div>

            
           </div>
        </div>
    </div>
</div>


<div class="card basic-data-table">
    <div class="card-header d-flex flex-wrap align-items-center justify-content-between">
        <h5 class="card-title mb-0">Unmatching Secret List</h5>
    </div>
    <div class="card-body">
        <table
            class="table table-striped bordered-table mb-0"
            id="secrettable"
            data-page-length="10">
            <thead>
                <tr>
                    <th scope="col">SL.No</th>
                    <th scope="col">Name</th>
                    <th scope="col">Password</th>
                    <th scope="col">Profile</th>
                    <th scope="col">Service</th>
                    <th scope="col">Last Log out</th>
                    <th scope="col">Status</th>
                    <th scope="col">Action</th>
                </tr>
            </thead>
            <tbody id="secret_body">
            </tbody>
        </table>
    </div>
</div>
<div class="card basic-data-table">
    <div class="card-header d-flex flex-wrap align-items-center justify-content-between">
        <h5 class="card-title mb-0">Unmatching Customer List</h5>
    </div>
    <div class="card-body">
        <table
            class="table bordered-table mb-0"
            id="Customertable"
            data-page-length="10">
            <thead>
                <tr>
                    <th scope="col">SL.No</th>
                    <th scope="col">Name</th>
                    <th scope="col">IP</th>
                    <th scope="col">Password</th>
                    <th scope="col">Profile</th>
                    <th scope="col">Status</th>
                    <th scope="col">Action</th>
                </tr>
            </thead>
            <tbody id="customer_secret_body">
            </tbody>
        </table>
    </div>
</div>


<?php $obj->start_script(); ?>
<script src="assets/libs/jquery-tabledit/jquery.tabledit.min.js"></script>

<script>
    let sectetShow = true;

    function mkConnectCheck(id, mkip) {
        
        $.ajax({
            type: "GET",
            url: "./pages/admin_reseller/connect_ajax.php",
            data: {
                'mkid': id
            },
            dataType: "JSON",
            success: function(response) {
                
                console.log(response);
                if (response.connection) {
                    $('#m' + id).html(`<button class="btn btn-success" onclick="mkAllSecret(${id})"   type="button">${mkip} ${response.status}</button>`);
                    if (sectetShow) {
                        mkAllSecret(`${id}`);
                    }
                    sectetShow = false;
                } else {
                    $('#m' + id).html(`<button class="btn btn-danger" disabled type="button">${mkip} ${response.status}</button>`);
                }

            },
            error: function(response) {
                console.log(response);
                // $('#m' + id).html(`<button class="btn btn-danger" type="button"> ${mkip} ${response.status}</button>`);
            }
        });
    }

    function mkAllSecret(id) {
        $.ajax({
            type: "GET",
            url: "pages/admin_reseller/connect_ajax.php",
            data: {
                'mkidsecretunmatching': id
            },
            dataType: "JSON",
            success: function(response) {
                
                console.log(response);
                if (response.connection) {
                    if ($.fn.DataTable.isDataTable('#secrettable')) {
                        $('#secrettable').DataTable().destroy();
                    }
                    $('#secret_body').html('');
                    $('#secret_body').html(`${response.status}`);
                    $('#customer_secret_body').html('');
                    $('#customer_secret_body').html(`${response.unmatching}`);
                    $('#secrettable').DataTable({
                        pageLength: 100,
                        lengthMenu: [ [10, 25, 100, 500], [10, 25, 100, 500] ],
                        responsive: true
                    });
                } else {
                    $('#secret_body').html('');
                    $('#customer_secret_body').html('');
                }
            },
            error: function(e) {
                alert(e);
            }
        });
    }
</script>



    <script>
        mkConnectCheck(`<?php echo $allmikrotik['id']; ?>`, `<?php echo $allmikrotik['mik_ip']; ?>`);
    </script>

<script>
    $(document).ready(function() {
        // Attach a click event listener to buttons with the class `secretAddSoft`
        $('#secrettable').on('click', '.secretAddSoft', function() {
            // Extract data attributes from the clicked button
            const id = $(this).data('mkid'); // Secret ID
            const status = $(this).data('status');
            const profile = $(this).data('profile');
            const password = $(this).data('password');
            const name = $(this).data('name');

            // AJAX POST request
            $.ajax({
                url: './pages/admin_reseller/secretAddSoft.php', // Replace with your endpoint URL
                type: 'POST',
                data: {
                    mkid: id,
                    status: status,
                    profile: profile,
                    password: password,
                    name: name,
                    re_id : <?php echo $allmikrotik['user_id']; ?>
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: response.status,
                            showConfirmButton: false,
                            timer: 2000,
                            position: 'top-end'
                        }).then(() => {
                            // Reload the page after user closes the alert
                            location.reload();
                        });

                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.status,
                            showConfirmButton: false,
                            timer: 2000,
                            position: 'top-end',
                        }).then(() => {
                            // Reload the page after user closes the alert
                            location.reload();
                        });
                    }
                },
                error: function(xhr, status, error) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Request Failed',
                        text: 'An error occurred while processing your request.'
                    });
                }
            });
        });
        $("#Customertable").on('click', '.secretDelete', function() {
            var id = $(this).data('id');
            $.ajax({
                type: "GET",
                url: "./pages/admin_reseller/delete_unmatching_secret.php",
                data: {
                    'id': id
                },
                dataType: "JSON",
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: response.status,
                            showConfirmButton: false,
                            timer: 2000,
                            position: 'top-end'
                        }).then(() => {
                            // Reload the page after user closes the alert
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.status,
                            showConfirmButton: false,
                            timer: 2000,
                            position: 'top-end',
                        }).then(() => {
                            // Reload the page after user closes the alert
                            location.reload();
                        });
                    }
                },
                error: function(xhr, status, error) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Request Failed',
                        text: 'An error occurred while processing your request.'
                    });
                }
            });
        });
        
        
        // tariql insert all unmatiching data
        $("#add_all_customer").on('click',function(){
            // console.log("click")
            $("#add_all_customer").text('Processing...');
            let AllData = [];
            $('#secrettable .secretAddSoft').each(function(){
                AllData.push({
                    id : $(this).data('mkid'),
                    status : $(this).data('status'),
                    profile : $(this).data('profile'),
                    password : $(this).data('password'),
                    name : $(this).data('name'),
                });
            });
            
           AllData.forEach(function (item, index) {
                $.ajax({
                    url: './pages/admin_reseller/secretAddSoft.php',
                    type: 'POST',
                    data: {
                        mkid: item.id,
                        status: item.status,
                        profile: item.profile,
                        password: item.password,
                        name: item.name,
                        re_id : <?php echo $allmikrotik['user_id']; ?>
                    },
                    success: function (response) {

                
                Swal.fire({
                    icon: response.success ? 'success' : 'error',
                    title: response.success ? 'Success' : 'Failed',
                    text: response.status,   //  backend status message
                    position: 'top-end',
                    timer: 4000,
                    showConfirmButton: false
                });
                
                 $("#add_all_customer").text('Import All Unmatching Data');
                
               
                // last
                if (index === AllData.length - 1 && response.success) {
                    setTimeout(() => {
                        location.reload();
                    }, 2600);
                };
                
               
            },
            error: function () {
                Swal.fire({
                    icon: 'error',
                    title: 'Request Failed',
                    text: 'Server error occurred',
                    position: 'top-end',
                    timer: 2500,
                    showConfirmButton: false
                });
            }
                });
            });
            
        });
    });
</script>
<?php $obj->end_script(); ?>