@extends('layouts.admin')
@section('css')
    <style>
        a {
            color: #000000;
        }
    </style>
@endsection
@section('content')
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>VPS Server</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="#">Home</a></li>
                            <li class="breadcrumb-item active">VPS Server</li>
                        </ol>
                    </div>
                </div>
            </div><!-- /.container-fluid -->
        </section>

        <!-- Main content -->
        <section class="content">
            <!-- Default box -->
            <div class="card">
                <div class="card-body">
                    <div class="d-grid gap-2 d-md-flex mb-3">
                        <a class="btn btn-success btn-sm" href="javascript:void(0)" id="createNewData"> <i
                                class="fa fa-plus"></i> Create</a>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-sm table-hover text-nowrap data-table w-100">
                            <thead>
                                <tr>
                                    <th>No</th>
                                    <th>Country</th>
                                    <th>Name</th>
                                    <th>Description</th>
                                    <th width="100px">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
                <!-- /.card-body -->
            </div>
            <!-- /.card -->

        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <div class="modal fade" id="ajaxModal" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="modelHeading"></h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="dataForm" name="dataForm" class="form-horizontal">
                        <input type="hidden" name="id" id="id">
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-danger print-error-msg" style="display:none">
                                    <ul></ul>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-group">
                                    <label for="name" class="col-sm-12 control-label">Name</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control" id="name" name="name"
                                            placeholder="Enter Name">
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-group">
                                    <label for="vps_country_id" class="col-sm-12 control-label">Country</label>
                                    <div class="col-sm-12">
                                        <select class="form-control select2" id="vps_country_id" name="vps_country_id"
                                            placeholder="Select Country"></select>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-group">
                                    <label for="speed" class="col-sm-12 control-label">Speed</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control" id="speed" name="speed"
                                            placeholder="Enter speed" value="1 Gbps">
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-group">
                                    <label for="description" class="col-sm-12 control-label">Description</label>
                                    <div class="col-sm-12">
                                        <textarea type="text" class="form-control" id="description" name="description" placeholder="Enter Description"
                                            rows="3"></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12 col-sm-4">
                                <div class="form-group">
                                    <label for="protocol" class="col-sm-12 control-label">Protocol</label>
                                    <div class="col-sm-12">
                                        <select class="form-control" name="protocol" id="protocol">
                                            <option value="https">https</option>
                                            <option value="http">http</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12 col-sm-8">
                                <div class="form-group">
                                    <label for="hostname" class="col-sm-12 control-label">Hostname</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control" id="hostname" name="hostname"
                                            placeholder="Enter Hostname">
                                    </div>
                                </div>
                            </div>
                            <div class="col-12 col-sm-8">
                                <div class="form-group">
                                    <label for="ipaddress" class="col-sm-12 control-label">IP Address</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control" id="ipaddress" name="ipaddress"
                                            placeholder="Enter IP Address">
                                    </div>
                                </div>
                            </div>
                            <div class="col-12 col-sm-6">
                                <div class="form-group">
                                    <label for="username" class="col-sm-12 control-label">Username</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control" id="username" name="username"
                                            placeholder="Enter Username">
                                    </div>
                                </div>
                            </div>
                            <div class="col-12 col-sm-6">
                                <div class="form-group">
                                    <label for="password" class="col-sm-12 control-label">Password</label>
                                    <div class="col-sm-12">
                                        <input type="password" class="form-control" id="password" name="password"
                                            placeholder="Enter Password">
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-group">
                                    <label for="token_type" class="col-sm-12 control-label">Token Type</label>
                                    <div class="col-sm-12">
                                        <input type="text" class="form-control" id="token_type" name="token_type"
                                            placeholder="Enter Token Type" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="form-group">
                                    <label for="access_token" class="col-sm-12 control-label">Access Token</label>
                                    <div class="col-sm-12">
                                        <textarea type="text" class="form-control" id="access_token" name="access_token" placeholder="Enter Description"
                                            rows="3" readonly></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-success mt-2" id="saveBtn">Submit</button>
                                    <button type="button" class="btn btn-info mt-2" id="getTokenBtn"><i
                                            class="fa fa-sync"></i>
                                        Test Connection
                                    </button>
                                    <button type="button" class="btn btn-danger mt-2" id="cancelBtn"
                                        data-dismiss="modal"><i class="fa fa-cancel"></i>
                                        Cancel
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="modalShow" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="modalShowHeading"></h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="d-grid gap-2 d-md-flex mb-3">
                        <a class="btn btn-default btn-sm" href="javascript:void(0)" id="refreshUserBtn"> <i
                                class="fa fa-sync"></i> Sync Data VPS</a>
                    </div>
                    <ul class="nav nav-tabs" id="custom-content-below-tab" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="custom-content-below-user-tab" data-toggle="pill"
                                href="#custom-content-below-user" role="tab"
                                aria-controls="custom-content-below-user" aria-selected="true">Users</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="custom-content-below-system-tab" data-toggle="pill"
                                href="#custom-content-below-system" role="tab"
                                aria-controls="custom-content-below-system" aria-selected="false">System</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="custom-content-below-core-tab" data-toggle="pill"
                                href="#custom-content-below-core" role="tab"
                                aria-controls="custom-content-below-core" aria-selected="false">Core</a>
                        </li>
                    </ul>
                    <div class="tab-content my-3" id="custom-content-below-tabContent">
                        <div class="tab-pane fade show active" id="custom-content-below-user" role="tabpanel"
                            aria-labelledby="custom-content-below-user-tab">
                            <div class="d-grid gap-2 d-md-flex mb-3">
                                <a class="btn btn-success btn-sm" href="javascript:void(0)" id="createNewUser"> <i
                                        class="fa fa-plus"></i> Create</a>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-sm table-hover text-nowrap data-table-user w-100">
                                    <thead>
                                        <tr>
                                            <th>No</th>
                                            <th>Username</th>
                                            <th>Status</th>
                                            <th>Expired</th>
                                            <th width="100px">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="tab-pane fade" id="custom-content-below-system" role="tabpanel"
                            aria-labelledby="custom-content-below-system-tab">
                            <table class="table table-sm system-group">
                                <thead>
                                    <tr>
                                        <th>Category</th>
                                        <th>Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                        <div class="tab-pane fade" id="custom-content-below-core" role="tabpanel"
                            aria-labelledby="custom-content-below-core-tab">
                            <button type="button" class="btn btn-info btn-sm" id="restartCoreBtn"> <i
                                    class="fa fa-sync"></i> Restart Core</button>
                            <button type="button" class="btn btn-danger btn-sm" id="restartServerBtn"> <i
                                    class="fa fa-sync"></i> Restart Server</button>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="ajaxModal2" aria-hidden="true">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="modelHeading2"></h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="dataForm2" name="dataForm2" class="form-horizontal">
                        @csrf
                        <input type="hidden" name="id">
                        <input type="hidden" name="passwordvmess">
                        <input type="hidden" name="passwordvless">
                        <input type="hidden" name="passwordtrojan">
                        <input type="hidden" name="passwordshadowsocks">
                        <div class="alert alert-danger print-error-msg" style="display:none">
                            <ul></ul>
                        </div>

                        <div class="form-group">
                            <label for="account_proxies" class="col-sm-12 control-label">Account Proxies</label>
                            <div class="col-sm-12">
                                <select class="form-control" name="account_proxies">
                                    <option value="vmess">vmess</option>
                                    <option value="vless">vless</option>
                                    <option value="trojan">trojan</option>
                                    <option value="shadowsocks">shadowsocks</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="username" class="col-sm-12 control-label">Username</label>
                            <div class="col-sm-12">
                                <input type="text" class="form-control" name="username" placeholder="Enter Username">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="password" class="col-sm-12 control-label">UUID / Password</label>
                            <div class="col-sm-12">
                                <input type="text" class="form-control" name="password"
                                    placeholder="Enter UUID / Password">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="expire" class="col-sm-12 control-label">Expire</label>
                            <div class="col-sm-12">
                                <input type="number" class="form-control" name="expire" placeholder="Enter Expire Day"
                                    value="0">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="data_limit" class="col-sm-12 control-label">Data Limit (GB)</label>
                            <div class="col-sm-12">
                                <input type="number" class="form-control" name="data_limit"
                                    placeholder="Enter Data Limit (GB)" value="0">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="data_limit_reset_strategy" class="col-sm-12 control-label">Data Limit Reset
                                Strategy</label>
                            <div class="col-sm-12">
                                <select class="form-control" name="data_limit_reset_strategy">
                                    <option value="no_reset">no_reset</option>
                                    <option value="day">day</option>
                                    <option value="week">week</option>
                                    <option value="month">month</option>
                                    <option value="year">year</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="note" class="col-sm-12 control-label">Email User</label>
                            <div class="col-sm-12">
                                <input type="email" class="form-control" name="note"
                                    placeholder="Enter Email User">
                            </div>
                        </div>

                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-success mt-2" id="saveBtn2">Submit</button>
                            <button type="button" class="btn btn-danger mt-2" id="cancelBtn2" data-dismiss="modal"><i
                                    class="fa fa-cancel"></i>
                                Cancel
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection
@section('js')
    <script>
        $(function() {
            $('#vps_country_id').select2({
                placeholder: 'Select Country',
                ajax: {
                    url: "{{ route('admin.vps-country-select') }}",
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            q: params.term,
                            page: params.page || 1
                        };
                    },
                    processResults: function(data, params) {
                        params.page = params.page || 1;
                        return {
                            results: data.data,
                            pagination: {
                                more: data.next_page_url !== null
                            }
                        };
                    },
                    cache: true
                },
                minimumInputLength: 0,
            });

            var table = $('.data-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: "{{ route('admin.vps-server.index') }}",
                columns: [{
                        data: 'DT_RowIndex',
                        name: 'DT_RowIndex',
                        orderable: false,
                        searchable: false
                    },
                    {
                        data: 'vps_country_name',
                        name: 'vps_countries.name'
                    },
                    {
                        data: 'name',
                        name: 'name'
                    },
                    {
                        data: 'description',
                        name: 'description'
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        searchable: false
                    },
                ],
                ordering: true,
                order: [
                    [2, 'asc']
                ],
            });

            $('#createNewData').click(function() {
                $('#id').val('');
                $('#dataForm').trigger("reset");
                $('#modelHeading').html("<i class='fa fa-plus'></i> New Vps");
                $('#ajaxModal').modal('show');
                $("#vps_country_id").val(null).change();
            });

            $('#createNewUser').click(function() {
                var id = $(this).data('id');
                $('#dataForm2 input[name="username"]').removeAttr('readonly');
                $('#modelHeading2').html(
                    `<i class='fa fa-user'></i> New User`);
                $('#ajaxModal2').modal('show');
            });

            $('#getTokenBtn').click(function() {
                var formData = new FormData();
                formData.append('protocol', $('#protocol').val());
                formData.append('hostname', $('#hostname').val());
                formData.append('username', $('#username').val());
                formData.append('password', $('#password').val());
                $('#getTokenBtn').attr('disabled', 'disabled');
                $.ajax({
                    type: 'POST',
                    url: "{{ route('admin.marzban.token') }}",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: (res) => {
                        if (res.detail) {
                            toastr.error(res.detail);
                        }
                        $('#getTokenBtn').removeAttr('disabled');
                        $('#token_type').val(res.token_type);
                        $('#access_token').val(res.access_token);
                    },
                    error: function(res) {
                        toastr.error('Failed Get Token');
                        $('#getTokenBtn').removeAttr('disabled');
                    }
                });
            });

            $('#refreshUserBtn').click(function() {
                var id = $('#dataForm2 input[name="id"]').val();
                $('#refreshUserBtn').attr('disabled', 'disabled');
                $.ajax({
                    type: 'GET',
                    url: "{{ route('admin.marzban.users', '') }}/" + id,
                    contentType: false,
                    processData: false,
                    success: (res) => {
                        // toastr.success('OK Get Users');
                        $('#refreshUserBtn').removeAttr('disabled');
                        $('.data-table-user tbody').empty();
                        $.each(res.response, function(key, value) {
                            let row = `
                                        <tr>
                                            <td>${key + 1}</td>
                                            <td>${value.username}</td>
                                            <td>${value.status}</td>
                                            <td>${value.expire}</td>
                                            <td width="100px">${value.action}</td>
                                        </tr>
                                        `;
                            $('.data-table-user tbody').append(row);
                        });
                        $('.data-table-user').DataTable();
                    },
                    error: function(response) {
                        toastr.error('Failed Get Users');
                        $('#refreshUserBtn').removeAttr('disabled');
                        $('.data-table-user').DataTable();
                    }
                });
                $.ajax({
                    type: 'GET',
                    url: "{{ route('admin.marzban.system', '') }}/" + id,
                    contentType: false,
                    processData: false,
                    success: (res) => {
                        // toastr.success('OK Get System');
                        $('#refreshUserBtn').removeAttr('disabled');
                        $('.system-group').empty();
                        $.each(res.response, function(key, value) {
                            $('.system-group').append('<tr><td>' + key +
                                '</td><td><strong>' + value +
                                '</strong></td></tr>');
                        });
                        $('.data-table-user').DataTable();
                    },
                    error: function(response) {
                        toastr.error('Failed Get System');
                        $('#refreshUserBtn').removeAttr('disabled');
                        $('.data-table-user').DataTable();
                    }
                });
            });

            $('body').on('click', '.showData', function() {
                var id = $(this).data('id');
                $('#dataForm2 input[name="id"]').val(id);
                $.get("{{ route('admin.vps-server.index') }}" + '/' + id + '/edit', function(data) {
                    $('#modalShowHeading').html(
                        `<i class='fa fa-database'></i> ${data.name}`);
                    $('#modalShow').modal('show');
                    $('#refreshUserBtn').click();
                });
            });

            $('body').on('click', '.editData', function() {
                var id = $(this).data('id');
                $("#vps_country_id").val(null).change();
                $.get("{{ route('admin.vps-server.index') }}" + '/' + id + '/edit', function(data) {
                    $('#modelHeading').html(
                        "<i class='fa-regular fa-pen-to-square'></i> Edit Vps");
                    $('#ajaxModal').modal('show');
                    $('#id').val(data.id);
                    $('#name').val(data.name);
                    $("#vps_country_id").append(new Option(data.vps_country_name, data
                        .vps_country_id)).change();
                    $('#speed').val(data.speed);
                    $('#description').val(data.description);
                    $('#protocol').val(data.protocol).change();
                    $('#hostname').val(data.hostname);
                    $('#ipaddress').val(data.ipaddress);
                    $('#username').val(data.username);
                    $('#password').val(data.password);
                    $('#token_type').val(data.token_type);
                    $('#access_token').val(data.access_token);
                });
            });

            $('body').on('click', '.deleteData', function() {
                var id = $(this).data("id");
                var isConfirmed = confirm("Are You sure want to delete?");

                if (isConfirmed) {
                    $.ajax({
                        type: "DELETE",
                        url: "{{ route('admin.vps-server.store') }}" + '/' + id,
                        success: function(data) {
                            toastr.success('OK');
                            table.draw();
                        },
                        error: function(data) {
                            toastr.error(data);
                            console.log('Error:', data);
                        }
                    });
                }
            });

            $('#dataForm').submit(function(e) {
                e.preventDefault();
                let formData = new FormData(this);
                $('#saveBtn').html('Sending...');
                $.ajax({
                    type: 'POST',
                    url: "{{ route('admin.vps-server.store') }}",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: (response) => {
                        $('#saveBtn').html('Submit');
                        $('#dataForm').trigger("reset");
                        $('#ajaxModal').modal('hide');
                        toastr.success('OK');
                        table.draw();
                    },
                    error: function(response) {
                        $('#saveBtn').html('Submit');
                        $('#dataForm').find(".print-error-msg").find("ul").html('');
                        $('#dataForm').find(".print-error-msg").css('display', 'block');
                        $.each(response.responseJSON.errors, function(key, value) {
                            $('#dataForm').find(".print-error-msg").find("ul")
                                .append('<li>' + value + '</li>');
                            toastr.error(value);
                        });
                    }
                });
            });

            $('body').on('click', '.editData2', function() {
                var id = $(this).data('id');
                var username = $(this).data('username');
                var passwordvmess = $(this).data('passwordvmess');
                var passwordvless = $(this).data('passwordvless');
                var passwordtrojan = $(this).data('passwordtrojan');
                var passwordshadowsocks = $(this).data('passwordshadowsocks');
                var password = $(this).data('password' + $('#dataForm2 select[name="account_proxies"]')
                    .val());
                var expire = $(this).data('expire');
                var data_limit = $(this).data('datalimit');
                var data_limit_reset_strategy = $(this).data('datalimitresetstrategy');
                var status = $(this).data('status');
                var note = $(this).data('note');
                $('#modelHeading2').html(
                    `<i class='fa fa-user'></i> ${username}`);
                $('#saveBtn2').val("edit");
                $('#ajaxModal2').modal('show');
                $('#dataForm2 input[name="username"]').attr('readonly', true);
                $('#dataForm2 input[name="username"]').val(username);
                $('#dataForm2 input[name="passwordvmess"]').val(passwordvmess);
                $('#dataForm2 input[name="passwordvless"]').val(passwordvless);
                $('#dataForm2 input[name="passwordtrojan"]').val(passwordtrojan);
                $('#dataForm2 input[name="passwordshadowsocks"]').val(passwordshadowsocks);
                $('#dataForm2 input[name="password"]').val(password);
                $('#dataForm2 input[name="expire"]').val(expire);
                $('#dataForm2 input[name="data_limit"]').val(data_limit);
                $('#dataForm2 select[name="data_limit_reset_strategy"]').val(data_limit_reset_strategy)
                    .change();
                $('#dataForm2 select[name="status"]').val(status).change();
                $('#dataForm2 input[name="note"]').val(note);
            });

            $('body').on('click', '.deleteData2', function() {
                var id = $(this).data("id");
                var isConfirmed = confirm("Are You sure want to delete?");

                if (isConfirmed) {
                    // $.ajax({
                    //     type: "DELETE",
                    //     url: "{{ route('admin.vps-server.store') }}" + '/' + id,
                    //     success: function(data) {
                    //         toastr.success('OK');
                    //         table.draw();
                    //     },
                    //     error: function(data) {
                    //         toastr.error(data);
                    //         console.log('Error:', data);
                    //     }
                    // });
                }
            });

            $('#dataForm2').submit(function(e) {
                e.preventDefault();
                let formData = new FormData(this);
                $('#saveBtn2').html('Sending...');
                $.ajax({
                    type: 'POST',
                    url: "{{ route('admin.marzban.users-add') }}",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: (response) => {
                        $('#saveBtn2').html('Submit');
                        var id = $('#dataForm2 input[name="id"]').val();
                        $('#dataForm2').trigger("reset");
                        $('#dataForm2').modal('hide');
                        $('#dataForm2 input[name="id"]').val(id);
                        toastr.success('OK');
                        table.draw();
                    },
                    error: function(response) {
                        $('#saveBtn2').html('Submit');
                        $('#dataForm2').find(".print-error-msg").find("ul").html('');
                        $('#dataForm2').find(".print-error-msg").css('display', 'block');
                        $.each(response.responseJSON.errors, function(key, value) {
                            $('#dataForm2').find(".print-error-msg").find("ul")
                                .append('<li>' + value + '</li>');
                            toastr.error(value);
                        });
                    }
                });
            });

            $('#dataForm2 select[name="account_proxies"]').on('change', function() {
                var select = $(this).val();
                $('#dataForm2 input[name="password"]').val($('#dataForm2 input[name="password' + select +
                    '"]').val());
            });

        });
    </script>
@endsection
