<link rel="stylesheet"
      href="<?php echo base_url(); ?>assets/at-admin/css/layouts/view.css?v=<?= rand(10000, 100000) ?>">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/at-admin/css/drag_list.css">
<style>
    .customsearch:hover {
        background-color: #e2e6ea;
    }

    .levleonetext {
        text-align: center;
    }

    .tablerowoddbg {
        background-color: #f1ebf5;
    }

    .levleonetext span {
        color: #616161;
    }
</style>

<!-- Page Breadcrumb -->
<div class="page-breadcrumbs">
    <ul class="breadcrumb">
        <li>
            <i class="fa fa-home"></i>
            <a href="<?= base_url('at-admin/dashboard'); ?>" style="color: #797979">主頁</a>
        </li>
        <li class="active" style="color: #ef4130">主頁設定</li>
    </ul>
</div>
<!-- /Page Breadcrumb -->
<!-- Page Header -->
<div class="page-header position-relative">
    <div class="header-title">
        <h1>
            主頁設定
        </h1>
    </div>
    <!--Header Buttons-->
    <div class="header-buttons">
        <a class="sidebar-toggler" href="#">
            <i class="glyphicon glyphicon-resize-horizontal"></i>
        </a>
        <a class="refresh" id="refresh-toggler" href="#">
            <i class="glyphicon glyphicon-refresh"></i>
        </a>
        <a class="fullscreen" id="fullscreen-toggler" href="#">
            <i class="glyphicon glyphicon-fullscreen"></i>
        </a>
    </div>
    <!--Header Buttons End-->
</div>
<!-- /Page Header -->
<!-- Page Body -->
<div class="page-body">
    <div class="container-fluid py-2" style="min-height:80vh;">
        <!-- <h2 style="color:#7d4495;">正在架設中...敬請期待!</h2> -->

        <!-- dashboard -->
        <div class="row">
            <!-- column -->

            <div class="col">
                <!-- body table -->
                <!-- add button -->
                <div style="" class="menubar2  p-2">
                    <a href="/at-admin/landingmain/edit" class="btn btn-success">
                        新增</a>
                </div>

                <!-- end add button -->

                <!-- drag table test -->
                <section class="box-typical">

                    <div class="fixed-table-toolbar">
                        <div class="bars pull-left">
                            <div id="toolbar"><strong>Landing Page 主目錄</strong></div>
                        </div>
                        <div class="pull-right search"></div>
                    </div>

                    <div id="info" class="content">(Drag the <span style="color:red">red square</span> to re-arrange the
                        order.)
                    </div>
                    <!-- test drag table -->
                    <table width="100%" border="1" cellpadding="2" cellspacing="1" bgcolor="#CCCCCC" class="content">
                        <tbody>
                        <tr bgcolor="#EEEEEE">
                            <td width="30" align="center"></td>
                            <td width="100">顯示次序</td>
                            <td width="200">圖片</td>
                            <td width="180">更新時間</td>
                            <td width="50"></td>
                            <td width="50"></td>
                        </tr>
                        </tbody>
                    </table>
                    <ul id="content-list" class="ui-sortable">
                        <?php
                        foreach ($sliders as $slider) {
                            ?>
                            <li id="listItem_<?php echo $contentrow->id; ?>" class="border border-secondary my-2">
                                <table width="100%" border="1" cellpadding="2" cellspacing="1" bgcolor="#cccccc"
                                       class="content" style="background: rgb(255, 182, 182);">
                                    <tbody>
                                    <tr bgcolor="#FFFFFF" id="<?php echo $contentrow->id; ?>">
                                        <td width="30" align="center">
                                            <div class="handle"></div>
                                        </td>
                                        <td width="100">
                                            <div class="rank_no"><?php echo $contentrow->displayorder; ?></div>
                                        </td>
                                        <td width="200"><?php echo $contentrow->title; ?></td>
                                        <td width="180"><?php echo $contentrow->updated; ?></td>

                                        <td width="50" align="center"><a
                                                    href="<?php echo base_url(); ?>at-admin/landingmain/edit?id=<?php echo $contentrow->id; ?>"
                                                    class="btn btn-primary">更改</a></td>
                                        <td width="50" align="center">
                                            <button type="submit" class="btn btn-danger remove">删除</button>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </li>
                            <?php
                        }//foreach ($test_drag_content as $contentrow) {
                        ?>
                    </ul>
                </section>

                <!-- end body table -->
            </div>
        </div>
        <!-- end dashboard -->
    </div>
</div>

<!-- /Page Body -->
<script defer="" src="<?php echo base_url(); ?>assets/at-admin/js/jquery-ui-min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        rerank()

        var table_name = 'landing_main';
        var rank_name = 'displayorder';
        var id_name = 'id';
        var counter = 0;
        $("#content-list").sortable({
            handle: '.handle',
            update: function () {
                // alert('update');
                rerank()
                var order = $('#content-list').sortable('serialize');
                var postData = {
                    'table_name': table_name,
                    'rank_name': rank_name,
                    'id_name': id_name,
                    'order': order,
                    '<?=$csrf['name'];?>': '<?=$csrf['hash'];?>',
                }
                $.ajax({
                    type: 'POST',                     //GET or POST
                    url: '<?php echo base_url()?>' + '/at-admin/landingmain/update_rank',               //請求的頁面
                    cache: false,                     //防止抓到快取的回應
                    data: postData,      //要傳送到頁面的參數
                    success: function (data) {
                        $("#info").append('<b style="color:red;" class="this_info" id="this_info">更新成功!!</b>');
                        setTimeout(function () {
                            $('.this_info').fadeOut(500);

                        }, 2000);


                    },         //當請求成功後此事件會被呼叫
                    // error: functionFailed,            //當請求失敗後此事件會被呼叫
                    statusCode: {                     //狀態碼處理
                        404: function () {
                            alert("page not found");
                        }
                    }
                });
                // end ajax
            }


        });


        var _preventDefault = function (evt) {
            evt.preventDefault();
        };
        $(".handle").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);

        $('.btn_delete').click(function () {
            var this_id = parseInt($(this).attr('rel'));
            var table_name = 'section';
            var this_id_name = 'section_id';
            var this_table = $(this).closest("table");

            if (confirm("Confirm to delete this content ?")) {
                $.ajax({
                    type: "POST",
                    url: "ajax/delete.php",
                    data: {
                        "table": table_name,
                        "id_name": this_id_name,
                        "del_id": this_id,
                        '<?=$csrf['name'];?>': '<?=$csrf['hash'];?>',
                    },
                    cache: false,
                    success: function (html) {
                        alert($('#info').text());
                        $('#info').html(html);
                        if (html.indexOf('Delete Success') != -1) {
                            this_table.fadeOut(300, function () {
                                this_table.remove();
                                rerank()
                            });
                        }
                    }
                });
            } else {
                return false;
            }
        })
    });


    function closeJS() {
        location.reload();
    }

    function rerank() {
        var i = 1;
        $('.rank_no').each(function () {
            $(this).text(i);
            i = i + 1;
        })
    }

</script>
<script type="text/javascript">
    $(document).ready(function () {

        //add control
        $("#btnSubmit").click(function (event) {
            var forcusitem = "";
            var passCheck = true;

            if ($('#inputadminname').val().length !== 0) {
                $("#inputadminname").addClass(" is-valid ");
                $("#inputadminname").removeClass(" is-invalid ");
            } else {
                if (forcusitem.length === 0) {
                    forcusitem = "#inputadminname";
                }
                passCheck = false;
                $("#inputadminname").addClass(" is-invalid ");
                $("#inputadminname").removeClass(" is-valid ");
            }

            if ($('#inputloginname').val().length !== 0) {
                $("#inputloginname").addClass(" is-valid ");
                $("#inputloginname").removeClass(" is-invalid ");
            } else {
                if (forcusitem.length === 0) {
                    forcusitem = "#inputloginname";
                }
                passCheck = false;
                $("#inputloginname").addClass(" is-invalid ");
                $("#inputloginname").removeClass(" is-valid ");
            }

            if ($('#inputPassword').val().length !== 0) {
                $("#inputPassword").addClass(" is-valid ");
                $("#inputPassword").removeClass(" is-invalid ");
            } else {
                if (forcusitem.length === 0) {
                    forcusitem = "#inputPassword";
                }
                passCheck = false;
                $("#inputPassword").addClass(" is-invalid ");
                $("#inputPassword").removeClass(" is-valid ");
            }

            if ($('#inputRePassword').val().length !== 0 || ($('#inputRePassword').val() !== $('#inputPassword').val())) {
                $("#inputRePassword").addClass(" is-valid ");
                $("#inputRePassword").removeClass(" is-invalid ");
            } else {
                if (forcusitem.length === 0) {
                    forcusitem = "#inputRePassword";
                }
                passCheck = false;
                $("#inputRePassword").addClass(" is-invalid ");
                $("#inputRePassword").removeClass(" is-valid ");
            }


            //   alert("1");
            if (passCheck == true) {


                var GlobalVariables = {
                    'csrfToken': '123',
                    'baseUrl': 'http://notesvision.at-webs.hk',
                    'destUrl': 'http://notesvision.at-webs.hk/api/v1/admins/post',
                    'AJAX_SUCCESS': 'SUCCESS',
                    'AJAX_FAILURE': 'FAILURE'
                };

                event.preventDefault();
                var postUrl = GlobalVariables.baseUrl + '/api/v1/admins/post';
                // var postData ={
                //       'csrfToken' :'',
                //       'custname' : $('#name').val(),
                //       'tel' : $('#tel').val(),
                //       'email' : $('#email').val(),
                //       'wechat' : $('#wechat').val(),
                //       'birthday' : $('#birthday').val(),
                //       // 'selectedBox' :$('.css-checkbox:checked').val()
                //       'selectedBox' :selectBox1

                // }
                var postData = {
                    'inputadminname': $('#inputadminname').val(),
                    'inputloginname': $('#inputloginname').val(),
                    'inputPassword': $('#inputPassword').val()
                }
                $.ajax({
                    method: "POST",
                    url: postUrl,
                    dataType: "json",
                    data: postData,
                    success: function (data) {

                        // alert("posted");
                        // // alert('formsubmit');
                        // alert(data);

                        // alert(data['recordstatus']);
                        // alert(data['msg']);
                        if (data['recordstatus'] == "SUCCESS") {
                            $('#feedback').remove();
                            $('#newmsg').append('<p class="text-primary" id="feedback">' + data['msg'] + '</p>');
                            setTimeout(function () {
                                location.reload();
                            }, 3000);
                            // location.reload();

                        }
                        if (data['recordstatus'] == "FAILURE") {
                            $('#feedback').remove();
                            $('#newmsg').append('<p class="text-danger"  id="feedback">' + data['msg'] + '</p>');
                            //   $( '#modal-bodymsg' ).empty();
                            //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-center" style="color: #a03d49;">請稍後再嘗試。</h5>' );
                            //   $('#finishModal').modal('show');
                            // }
                            // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
                            //     window.location.href=GlobalVariables.destUrl;
                            // } else {
                            //     $('.alert').text("登入錯誤");
                            //    $('.alert').removeClass('hidden');
                        }
                    }
                });

            }//if(passCheck==true){
        });//$("#btnSubmit").click(function(event) {


        //edit submit button

        $("#btneditSubmit").click(function (event) {
            var forcusitem = "";
            var passCheck = true;

            if ($('#inputadminnameedit').val().length !== 0) {
                $("#inputadminnameedit").addClass(" is-valid ");
                $("#inputadminnameedit").removeClass(" is-invalid ");
            } else {
                if (forcusitem.length === 0) {
                    forcusitem = "#inputadminnameedit";
                }
                passCheck = false;
                $("#inputadminnameedit").addClass(" is-invalid ");
                $("#inputadminnameedit").removeClass(" is-valid ");
            }

            if ($('#inputloginnameedit').val().length !== 0) {
                $("#inputloginnameedit").addClass(" is-valid ");
                $("#inputloginnameedit").removeClass(" is-invalid ");
            } else {
                if (forcusitem.length === 0) {
                    forcusitem = "#inputloginnameedit";
                }
                passCheck = false;
                $("#inputloginnameedit").addClass(" is-invalid ");
                $("#inputloginnameedit").removeClass(" is-valid ");
            }

            //   if($('#inputPassword').val().length !== 0){
            //     $("#inputPassword").addClass(" is-valid ");
            //     $("#inputPassword").removeClass(" is-invalid ");
            //   }
            //   else{
            //     if(forcusitem.length===0){
            //        forcusitem="#inputPassword";
            //     }
            //     passCheck=false;
            //     $("#inputPassword").addClass(" is-invalid ");
            //    $("#inputPassword").removeClass(" is-valid ");
            //   }

            if ($('#inputPasswordedit').val().length !== 0) {
                if ($('#inputRePasswordedit').val().length !== 0 && ($('#inputRePasswordedit').val() === $('#inputPasswordedit').val())) {
                    $("#inputRePasswordedit").addClass(" is-valid ");
                    $("#inputRePasswordedit").removeClass(" is-invalid ");
                } else {
                    if (forcusitem.length === 0) {
                        forcusitem = "#inputRePasswordedit";
                    }
                    passCheck = false;
                    $("#inputRePasswordedit").addClass(" is-invalid ");
                    $("#inputRePasswordedit").removeClass(" is-valid ");
                }
            }//if($('#inputPasswordedit').val().length !== 0){


            //   alert("1");
            if (passCheck == true) {


                var GlobalVariables = {
                    'csrfToken': '123',
                    'baseUrl': 'http://notesvision.at-webs.hk',
                    'destUrl': 'http://notesvision.at-webs.hk/api/v1/admins/edit',
                    'AJAX_SUCCESS': 'SUCCESS',
                    'AJAX_FAILURE': 'FAILURE'
                };

                event.preventDefault();
                var postUrl = GlobalVariables.baseUrl + '/api/v1/admins/edit';
                // var postData ={
                //       'csrfToken' :'',
                //       'custname' : $('#name').val(),
                //       'tel' : $('#tel').val(),
                //       'email' : $('#email').val(),
                //       'wechat' : $('#wechat').val(),
                //       'birthday' : $('#birthday').val(),
                //       // 'selectedBox' :$('.css-checkbox:checked').val()
                //       'selectedBox' :selectBox1

                // }
                var postData = {
                    'inputadminnameedit': $('#inputadminnameedit').val(),
                    'inputloginnameedit': $('#inputloginnameedit').val(),
                    'inputPasswordedit': $('#inputPasswordedit').val(),
                    'inputadminid': $('#inputadminid').val()
                }
                $.ajax({
                    method: "POST",
                    url: postUrl,
                    dataType: "json",
                    data: postData,
                    success: function (data) {

                        // alert("posted");
                        // alert('formsubmit');
                        // alert(data);

                        // alert(data['recordstatus']);
                        // alert(data['msg']);
                        if (data['recordstatus'] == "SUCCESS") {
                            $('#feedback').remove();
                            $('#editmsg').append('<p class="text-primary" id="feedback">' + data['msg'] + '</p>');
                            setTimeout(function () {
                                location.reload();
                            }, 3000);
                            // location.reload();

                        }
                        if (data['recordstatus'] == "FAILURE") {
                            $('#feedback').remove();
                            $('#editmsg').append('<p class="text-danger"  id="feedback">' + data['msg'] + '</p>');
                            //   $( '#modal-bodymsg' ).empty();
                            //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-center" style="color: #a03d49;">請稍後再嘗試。</h5>' );
                            //   $('#finishModal').modal('show');
                            // }
                            // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
                            //     window.location.href=GlobalVariables.destUrl;
                            // } else {
                            //     $('.alert').text("登入錯誤");
                            //    $('.alert').removeClass('hidden');
                        }
                    }
                });

            }//if(passCheck==true){
        });  //$("#btneditSubmit").click(function(event) {
        //end edit submit button


        //delete submit button
        $("#btndeleteSubmit").click(function (event) {
            var forcusitem = "";
            var passCheck = true;
            //check delete have value
            // var checkboxvalue = $('.checkbox').val();

            var checkboxvalue = [];
            // $("input.checkbox[type=checkbox]:checked").each(function(i){
            //     alert(i.value );
            // checkboxvalue.push( i.value );
            // });

            $('input.checkbox:checkbox:checked').each(function () {

                // alert($(this).val());
                checkboxvalue.push($(this).val());

            });
            var postData = {
                'inputdeletecheckboxvalue': checkboxvalue
            }
            var GlobalVariables = {
                'csrfToken': '123',
                'baseUrl': 'http://notesvision.at-webs.hk',
                'destUrl': 'http://notesvision.at-webs.hk/api/v1/admins/delete',
                'AJAX_SUCCESS': 'SUCCESS',
                'AJAX_FAILURE': 'FAILURE'
            };

            event.preventDefault();
            var postUrl = GlobalVariables.baseUrl + '/api/v1/admins/delete';
            //end　check delete have value
            $.ajax({
                method: "POST",
                url: postUrl,
                dataType: "json",
                data: postData,
                success: function (data) {

                    // alert("posted");
                    // alert('formsubmit');
                    // alert(data);

                    // alert(data['recordstatus']);
                    // alert(data['msg']);
                    if (data['recordstatus'] == "SUCCESS") {

                        $('#feedback').remove();
                        $('#deletemsg').append('<p class="text-primary" id="feedback">' + data['msg'] + '</p>');
                        setTimeout(function () {
                            location.reload();
                        }, 3000);
                        // location.reload();

                    }
                    if (data['recordstatus'] == "FAILURE") {
                        $('#feedback').remove();
                        $('#deletemsg').append('<p class="text-danger"  id="feedback">' + data['msg'] + '</p>');
                        //   $( '#modal-bodymsg' ).empty();
                        //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-center" style="color: #a03d49;">請稍後再嘗試。</h5>' );
                        //   $('#finishModal').modal('show');
                        // }
                        // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
                        //     window.location.href=GlobalVariables.destUrl;
                        // } else {
                        //     $('.alert').text("登入錯誤");
                        //    $('.alert').removeClass('hidden');
                    }
                }
            });

        });  //$("#btndeleteSubmit").click(function(event) {
        //end delete submit button


        //Pop up edit box
        // $( "#deletebutton" ).click(function() {
        //     $('#editModalCenter').modal({
        //         show: true,
        //     });

        // });
        // $('#myform').on('submit', function(ev) {
        //     $('#my-modal').modal({
        //         show: 'false'
        //     });


        //     var data = $(this).serializeObject();
        //     json_data = JSON.stringify(data);
        //     $("#results").text(json_data);
        //     $(".modal-body").text(json_data);

        // $("#results").text(data);

        // ev.preventDefault();
        // });
        //end pop up edit box

        //get edit modal data
        $('#editModalCenter').on('show.bs.modal', function (e) {
            var user_id = $(e.relatedTarget).data('user_id');
            var GlobalVariables = {
                'csrfToken': '123',
                'baseUrl': 'http://notesvision.at-webs.hk',
                'destUrl': 'http://notesvision.at-webs.hk/api/v1/admins/getadmindata',
                'AJAX_SUCCESS': 'SUCCESS',
                'AJAX_FAILURE': 'FAILURE'
            };


            $.ajax(
                {
                    type: 'POST',
                    url: GlobalVariables.destUrl, //Here you will fetch records     
                    dataType: "json",
                    data: 'user_id=' + user_id, //Pass $user_id           
                    success: function (result) {


                        $("#inputadminnameedit").val(result[0].fullName);
                        $("#inputloginnameedit").val(result[0].login);


                        // $("#inputadminnameedit").val('123');
// 						alert('success'+result);
//                         alert(result[0]);
//                         var obj = jQuery.parseJSON( '{ "name": "John" }' );
// alert( obj.name );
//                         var json = $.parseJSON(result);
//                         //now json variable contains data in json format
//                         //let's display a few items
//                         for (var i=0;i<json.length;++i)
//                         {
//                             alert(json[0]);
//                         }
                        // $('.fetched_user').html(result); //Show fetched data from database
                    },
                    error: function (result) {
                        alert('error' + result);
                    }
                });


        });

        //end get edit modal data


    });//$( document ).ready(function() {


    //show edit modal
    function showeditmodal($id) {


        var GlobalVariables = {
            'csrfToken': '123',
            'baseUrl': 'http://notesvision.at-webs.hk',
            'destUrl': 'http://notesvision.at-webs.hk/api/v1/admins/getadmindata',
            'AJAX_SUCCESS': 'SUCCESS',
            'AJAX_FAILURE': 'FAILURE'
        };

        $.ajax(
            {
                type: 'POST',
                url: GlobalVariables.destUrl, //Here you will fetch records     
                dataType: "json",
                data: 'user_id=' + $id, //Pass $user_id           
                success: function (result) {


                    $("#inputadminnameedit").val(result[0].fullName);
                    $("#inputloginnameedit").val(result[0].login);
                    $("#inputadminid").val($id);

                    $('#editModalCenter').modal({
                        show: true,
                    });

                    // $("#inputadminnameedit").val('123');
                    // 						alert('success'+result);
                    //                         alert(result[0]);
                    //                         var obj = jQuery.parseJSON( '{ "name": "John" }' );
                    // alert( obj.name );
                    //                         var json = $.parseJSON(result);
                    //                         //now json variable contains data in json format
                    //                         //let's display a few items
                    //                         for (var i=0;i<json.length;++i)
                    //                         {
                    //                             alert(json[0]);
                    //                         }
                    // $('.fetched_user').html(result); //Show fetched data from database
                },
                error: function (result) {
                    alert('error' + result);
                }
            });

    }

    //end show edit modal

    //show delete modal
    function showdeletemodal() {
        checkboxes = document.getElementsByName('admincheck');
        var favorite = [];
        $count = 0;
        $.each($("input[name='admincheck']:checked"), function () {
            favorite.push($(this).val());
            $count = $count + 1;
        });
        // alert(1);
        // alert("My favourite sports are: " + favorite.join(", "));
        document.getElementById("deletenum").innerHTML = $count;
        $('#deleteModalCenter').modal({
            show: true,
        });
    }//function showdeletemodal() {
    //end show delete modal

    //end control


</script>
<script>
    function myFunction() {
        var x = document.getElementById("myInput");
        if (x.type === "password") {
            x.type = "text";
        } else {
            x.type = "password";
        }
    }
</script>
<script type="text/javascript">
    $(".remove").click(function () {
        var id = $(this).parents("tr").attr("id");


        if (confirm('Are you sure to remove this record ?')) {
            $.ajax({
                url: '/at-admin/landingmain/delete/' + id,
                type: 'DELETE',
                error: function () {
                    alert('Something is wrong');
                },
                success: function (data) {
                    $("#" + id).remove();
                    alert("Record removed successfully");
                }
            });
        }
    });


</script>
