<?php
// delete (better to use POST, but keeping your GET style)
if (isset($_GET['delete-id'])) {
    header('Content-Type: application/json');
    $delId = (int)$_GET['delete-id'];
    $obj->raw_sql("DELETE FROM re_mikrotik_user WHERE id=" . $delId);
    echo '<script> window.location = "?page=reseller-mikrotik"; </script>';
    exit;
}


$resellers = $obj->raw_sql("SELECT  _reseller_createuser.*, _re_useraccess.`UserAccessId`, _re_useraccess.`UserId`, _re_useraccess.`UserType`, _re_useraccess.`MenuPermission`, _re_useraccess.`WorkPermission`  FROM `_reseller_createuser`left JOIN  _re_useraccess ON  _re_useraccess.`UserId` = _reseller_createuser.UserId WHERE _re_useraccess.`UserType`='RE'");


$mikrotik_users = $obj->rawSql("
    SELECT 
        mu.id,
        mu.user_id,
        mu.mik_username,
        mu.mik_password,
        mu.mik_ip,
        mu.mik_port,
        mu.status,
        cu.UserName
    FROM re_mikrotik_user mu
    LEFT JOIN _reseller_createuser cu ON cu.UserId = mu.user_id
    ORDER BY mu.id DESC
");





?>

<style>
    /* ===== Modern Card + Table ===== */
    .page-title {
        font-weight: 700;
        font-size: 22px;
        color: #111827;
        margin: 0;
    }

    .table-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 14px;
        overflow: hidden;
        box-shadow: 0 8px 24px rgba(17, 24, 39, .06);
    }

    .table-card-header {
        padding: 14px 16px;
        border-bottom: 1px solid #e5e7eb;
        background: linear-gradient(180deg, #fafafa, #fff);
    }

    .table-card-body {
        padding: 14px 16px;
    }

    .header-actions {
        display: flex;
        gap: 10px;
        align-items: center;
        justify-content: flex-end;
    }

    .searchbox {
        width: 260px;
        max-width: 100%;
    }

    .searchbox input {
        border-radius: 10px;
        border: 1px solid #e5e7eb;
        padding: 9px 12px;
        outline: none;
    }

    .searchbox input:focus {
        border-color: #93c5fd;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, .15);
    }

    /* table */
    .table-modern {
        border-collapse: separate !important;
        border-spacing: 0;
    }

    .table-modern thead th {
        background: #0f172a;
        color: #fff;
        font-weight: 600;
        font-size: 13px;
        border: none !important;
        padding: 12px 12px;
        white-space: nowrap;
    }

    .table-modern tbody td {
        padding: 12px 12px;
        vertical-align: middle;
        border-top: 1px solid #eef2f7 !important;
    }

    .table-modern tbody tr:hover {
        background: #f9fafb;
    }

    .badge-chip {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 6px 10px;
        border-radius: 999px;
        font-size: 12px;
        font-weight: 600;
        background: #f3f4f6;
        color: #111827;
        border: 1px solid #e5e7eb;
    }

    .mono {
        font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    }

    /* buttons */
    .btn-soft {
        border: none;
        border-radius: 10px;
        padding: 8px 10px;
        font-weight: 600;
    }

    .btn-soft-success {
        background: #ecfdf5;
        color: #047857;
    }

    .btn-soft-info {
        background: #eff6ff;
        color: #1d4ed8;
    }

    .btn-soft-primary {
        background: #eef2ff;
        color: #4338ca;
    }

    .btn-soft-danger {
        background: #fef2f2;
        color: #b91c1c;
    }

    .td-actions {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        justify-content: flex-end;
    }

    .pass-wrap {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .pass-wrap .pass {
        max-width: 180px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .icon-btn {
        border: 1px solid #e5e7eb;
        background: #fff;
        border-radius: 10px;
        padding: 6px 10px;
        cursor: pointer;
    }

    .icon-btn:hover {
        background: #f9fafb;
    }
</style>

<div class="container-fluid">

    <div class="table-card mb-3">
        <div class="table-card-header">
            <div class="row align-items-center">
                <div class="col-sm-6">
                    <h6 class="page-title ">Mikrotik User List</h6>
                    <small style="color:#6b7280;">Manage mikrotik credentials & secrets</small>
                </div>

                <div class="col-sm-6">
                    <div class="header-actions">
                        <div class="searchbox">
                            <input type="text" id="tableSearch" placeholder="Search username, IP, user..." />
                        </div>
                        <a href="javascript:void(0)" class="btn btn-success" id="btnAddMikrotik">
                            + Add New Mikrotik
                        </a>

                    </div>
                </div>

            </div>
        </div>

        <div class="table-card-body">
            <div class="table-responsive">
                <table id="mikrotikTable" class="table table-striped table-hover table-modern w-100">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Username</th>
                            <th>Password</th>
                            <th>Port</th>
                            <th>IP Address</th>
                            <th>Panel User</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php $sl = 0;
                        foreach ($mikrotik_users as $user): $sl++; ?>
                        
                            <tr>
                                <td class="mono"><?php echo $sl; ?></td>

                                <td>
                                    <span class="badge-chip mono"><?php echo htmlspecialchars($user['mik_username'] ?? ''); ?></span>
                                </td>

                                <td>
                                    <div class="pass-wrap">
                                        <span class="pass mono" data-pass="<?php echo htmlspecialchars($user['mik_password'] ?? ''); ?>">
                                            ••••••••
                                        </span>
                                        <button type="button" class="icon-btn btnTogglePass" title="Show/Hide">
                                            <i class="mdi mdi-eye-outline"></i>
                                        </button>
                                        <button type="button" class="icon-btn btnCopyPass" title="Copy">
                                            <i class="mdi mdi-clipboard-text-outline"></i>
                                        </button>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge-chip mono"><?php echo $user['mik_port'] ?? ''; ?></span>
                                </td>

                                <td>
                                    <span class="mono"><?php echo htmlspecialchars($user['mik_ip'] ?? ''); ?></span>
                                </td>

                                <td>
                                    <span class="badge-chip"><?php echo htmlspecialchars($user['UserName'] ?? 'N/A'); ?></span>
                                </td>
                                <td>
                                    <button class="btn-status btn" disabled data-id="<?= $user['id'] ?>" data-status="<?= $user['status'] ?>">Checking...</button>
                                    
                                </td>

                                <td class="text-end">
                                    <div class="td-actions">
                                        <a href="?page=admin-reseller-software-secretlist&id=<?php echo (int)$user['user_id']; ?>&mkid=<?php echo (int)$user['id']; ?>"
                                            class="btn-soft btn-soft-info">
                                            Secret List
                                        </a>
                                        <a href="?page=admin-reseller-software-unmatching&id=<?php echo (int)$user['user_id']; ?>&mkid=<?php echo (int)$user['id']; ?>"
                                            class="btn-soft btn-soft-info">
                                            Unmatching
                                        </a>

                                        <a href="javascript:void(0)"
                                            class="btn btn-primary btn-sm btn-edit-mikrotik"
                                            data-id="<?php echo (int)$user['id']; ?>"
                                            data-user_id="<?php echo (int)$user['user_id']; ?>"
                                            data-username="<?php echo htmlspecialchars($user['mik_username'] ?? '', ENT_QUOTES); ?>"
                                            data-password="<?php echo htmlspecialchars($user['mik_password'] ?? '', ENT_QUOTES); ?>"
                                            data-ip="<?php echo htmlspecialchars($user['mik_ip'] ?? '', ENT_QUOTES); ?>"
                                            data-port="<?php echo htmlspecialchars($user['mik_port'] ?? '', ENT_QUOTES); ?>"
                                            data-user_name="<?php echo htmlspecialchars($user['UserName'] ?? '', ENT_QUOTES); ?>"
                                            >
                                            
                                            Edit
                                        </a>


                                        <!-- Optional delete -->
                                        <a href="javascript:void(0);"
                                            class="btn-soft btn-soft-danger"
                                            onclick="deleteMikrotik('<?php echo (int)$user['id']; ?>')">
                                            🗑 Delete
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>

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

    <!-- Edit Mikrotik Modal -->
    <div class="modal fade" id="editMikrotikModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content" style="border-radius:14px; overflow:hidden;">
                <div class="modal-header" style="background:#0f172a; color:#fff;">
                    <h5 class="modal-title mb-0 text-white">Edit Mikrotik</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form id="editMikrotikForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_mikrotik">
                        <input type="hidden" name="id" id="mk_id">

                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" class="form-control" name="mik_username" id="mk_username" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Password</label>
                            <input type="text" class="form-control" name="mik_password" id="mk_password" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">IP Address</label>
                            <input type="text" class="form-control" name="mik_ip" id="mk_ip" required>
                        </div>
                        <div class="mb-1">
                            <label class="form-label">Port</label>
                            <input type="number" class="form-control" name="mk_port" id="mk_port" required>
                        </div>
                        
                        <input type="hidden" class="form-control" name="user_id" id="mk_user_id" required>
                        
                        <div class="mb-1">
                            <label class="form-label">Panel User</label>
                            <select class="form-control" name="user_id" id="user_id" required>
                                <option value="">Select Reseller</option>
                                <?php foreach($resellers as $reseller){ ?>
                                    <option value="<?php echo $reseller['UserId']; ?>">
                                        <?php echo $reseller['FullName']; ?>
                                    </option>
                                <?php } ?>
                            </select>
                        </div>


                        <div id="mk_msg" class="mt-3" style="display:none;"></div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-success" id="mk_save_btn">Update</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Mikrotik Modal -->
    <div class="modal fade" id="addMikrotikModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius:14px; overflow:hidden;">
        <div class="modal-header" style="background:#0f172a; color:#fff;">
            <h5 class="modal-title mb-0 text-white">Add New Mikrotik</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <form id="addMikrotikForm">
            <div class="modal-body">
            <input type="hidden" name="action" value="add_mikrotik">

            <div class="mb-3">
                <label class="form-label">Username</label>
                <input type="text" class="form-control" name="mik_username" id="add_mk_username" required>
            </div>

            <div class="mb-3">
                <label class="form-label">Password</label>
                <input type="text" class="form-control" name="mik_password" id="add_mk_password" required>
            </div>

            <div class="mb-3">
                <label class="form-label">IP Address</label>
                <input type="text" class="form-control" name="mik_ip" id="add_mk_ip" required>
            </div>
            <div class="mb-1">
                <label class="form-label">Port</label>
                <input type="number" class="form-control" name="mk_port" id="mk_port" required>
            </div>

            <div class="mb-1">
                <label class="form-label">Panel User</label>
               <select class="form-control" name="user_id">
                    <option value="">Select Reseller</option>
                    <?php foreach($resellers as $reseller){?>
                        <option value="<?php echo $reseller['UserId']?>"><?php echo $reseller['FullName']?></option>
                    <?php }?>
                </select>
            </div>

            <div id="add_mk_msg" class="mt-3" style="display:none;"></div>
            </div>

            <div class="modal-footer">
            <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-success" id="add_mk_save_btn">Save</button>
            </div>
        </form>
        </div>
    </div>
    </div>



</div>

<?php $obj->start_script(); ?>
<script>
    (function() {
        const table = $('#mikrotikTable').DataTable({
            pageLength: 10,
            lengthMenu: [
                [10, 20, 50, 100, 500],
                [10, 20, 50, 100, 500]
            ],
            order: [
                [0, 'asc']
            ],
            responsive: true,
            dom: `<"row mb-2"<"col-sm-6"l><"col-sm-6 text-end"f>>` +
                `<"row"<"col-sm-12"tr>>` +
                `<"row mt-2"<"col-sm-5"i><"col-sm-7 text-end"p>>`,
            language: {
                search: "Search:",
                lengthMenu: "Show _MENU_ rows",
                info: "Showing _START_ to _END_ of _TOTAL_",
                zeroRecords: "No mikrotik user found"
            }
        });

        $('#tableSearch').on('keyup', function() {
            table.search(this.value).draw();
        });
        $(document).on('click', '.btnTogglePass', function() {
            const $pass = $(this).closest('.pass-wrap').find('.pass');
            const real = $pass.attr('data-pass') || '';
            const isHidden = $pass.text().includes('•');
            $pass.text(isHidden ? real : '••••••••');
        });

        $(document).on('click', '.btnCopyPass', function() {
            const $pass = $(this).closest('.pass-wrap').find('.pass');
            const real = $pass.attr('data-pass') || '';
            if (!real) return;

            navigator.clipboard.writeText(real).then(() => {
                alert('Password copied!');
            }).catch(() => {
                alert('Copy failed!');
            });
        });

    })();
</script>

<script>



    $(document).on('click', '.btn-edit-mikrotik', function() {
        const id = $(this).data('id');
        let userId = $(this).data('user_id');
        $('#mk_id').val(id);
        $('#mk_user_id').val($(this).data('user_id'));
        $('#user_name').val($(this).data('user_name'));
        $('#mk_username').val($(this).data('username'));
        $('#mk_password').val($(this).data('password'));
        $('#mk_ip').val($(this).data('ip'));
        $('#mk_port').val($(this).data('port'));
        $('#user_id').val(userId).trigger('change');
        
        $('#mk_msg').hide().html('');
        $('#mk_save_btn').prop('disabled', false).text('Update');
        const modal = new bootstrap.Modal(document.getElementById('editMikrotikModal'));
        modal.show();

    });

    $('#editMikrotikForm').on('submit', function(e) {
        e.preventDefault();

        $('#mk_save_btn').prop('disabled', true).text('Updating...');

        $.ajax({
            url: "pages/admin_reseller/re_mikrotik_ajax.php",
            type: "POST",
            data: $(this).serialize(),
            dataType: "json",
            success: function(res) {
                if (res.success) {
                    $('#mk_msg').show().html('<div class="alert alert-success mb-0">' + res.message + '</div>');

                    setTimeout(function() {
                        location.reload();
                    }, 600);
                } else {
                    $('#mk_msg').show().html('<div class="alert alert-danger mb-0">' + (res.message || "Update failed") + '</div>');
                    $('#mk_save_btn').prop('disabled', false).text('Update');
                }
            },
            error: function(xhr) {
                $('#mk_msg').show().html('<div class="alert alert-danger mb-0">Server error. Try again.</div>');
                $('#mk_save_btn').prop('disabled', false).text('Update');
                console.log(xhr.responseText);
            }
        });
    });
</script>

<script>
(function(){

  // open add modal
  $('#btnAddMikrotik').on('click', function(){
    $('#addMikrotikForm')[0].reset();
    $('#add_mk_msg').hide().html('');
    $('#add_mk_save_btn').prop('disabled', false).text('Save');

    const modal = new bootstrap.Modal(document.getElementById('addMikrotikModal'));
    modal.show();
  });

  // submit add form
  $('#addMikrotikForm').on('submit', function(e){
    e.preventDefault();

    $('#add_mk_save_btn').prop('disabled', true).text('Saving...');

    $.ajax({
      url: "pages/admin_reseller/re_mikrotik_ajax.php",
      type: "POST",
      data: $(this).serialize(),
      dataType: "json",
      success: function(res){
        if(res.success){
          $('#add_mk_msg').show().html('<div class="alert alert-success mb-0">'+res.message+'</div>');

          setTimeout(function(){
            location.reload();
          }, 600);

        }else{
          $('#add_mk_msg').show().html('<div class="alert alert-danger mb-0">'+(res.message || "Insert failed")+'</div>');
          $('#add_mk_save_btn').prop('disabled', false).text('Save');
        }
      },
      error: function(xhr){
        $('#add_mk_msg').show().html('<div class="alert alert-danger mb-0">Server error. Try again.</div>');
        $('#add_mk_save_btn').prop('disabled', false).text('Save');
        console.log(xhr.responseText);
      }
    });
  });

})();

//Delete Mikrotik

function deleteMikrotik(id) {

    Swal.fire({
        title: 'Are you sure?',
        text: "This Mikrotik will be permanently deleted!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel'
    }).then((result) => {

        if (result.isConfirmed) {

            $.ajax({
                type: "POST",
                url: "../pages/admin_reseller/re_mikrotik_ajax.php",
                dataType: "json",
                data: {
                    action: "delete_mikrotik",
                    id: id
                },
                success: function (data) {

                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Deleted!',
                            text: data.message,
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Failed!',
                            text: data.message
                        });
                    }
                },
                error: function (xhr) {
                    console.log(xhr.responseText);
                    Swal.fire(
                        'Error!',
                        'Server error occurred.',
                        'error'
                    );
                }
            });

        }
    });
}

$('.btn-status').each(function(){
    let btn = $(this);
    let id = btn.data('id');

    $.ajax({
        url: '/pages/admin_reseller/mikrotik_status_checker.php',
        type: 'POST',
        data: {id: id},
        dataType: 'json',
        success: function(res){
            if(res.connected){
                btn.prop('disabled', false);
                btn.data('status', res.status); // save current status

                if(res.status == 1){
                    btn.prop('disabled', false).text('Enable')
                       .removeClass('btn-danger btn-secondary')
                       .addClass('btn-success');
                }else{
                    btn.prop('disabled', false).text('Disable')
                       .removeClass('btn-success btn-secondary')
                       .addClass('btn-danger');
                }
            }else{
                btn.prop('disabled', true)
                   .text('Disconnected')
                   .removeClass('btn-success btn-danger')
                   .addClass('btn-secondary');
            }
        }
    });
});


$(document).on('click', '.btn-status', function(){
    let btn = $(this);
    let id = btn.data('id');
    let status = btn.data('status') == 1 ? 'enable' : 'disable';

    $.ajax({
        url: '/pages/admin_reseller/mikrotik_status_changer.php',
        type: 'POST',
        data: {user_id: id, status: status},
        dataType: 'json',
        success: function(res){
            if(res.success){
                // Update button text & color instantly without reload
                if(status == 'enable'){
                    btn.text('Disable')
                       .removeClass('btn-success')
                       .addClass('btn-danger');
                    btn.data('status', 0); // now status = 0
                }else{
                    btn.text('Enable')
                       .removeClass('btn-danger')
                       .addClass('btn-success');
                    btn.data('status', 1); // now status = 1
                }
            }else{
                alert(res.message || 'Update failed');
            }
        },
        error: function(xhr){
            console.log(xhr.responseText);
            alert('Server error');
        }
    });
});


</script>



<?php $obj->end_script(); ?>