<?php
session_start();
//Can't come in without logged in
if (!isset($_SESSION['loggedin'])) {
    header('Location: pages-signin.html');
    exit;
}

if (!isset($_FILES['excel']['error'])) {
    //header("Location: /DataBase/upload.html");
}
if (0 < $_FILES['excel']['error']) {
    echo 'Error: ' . $_FILES['excel']['error'] . '<br>';
} else {
    $filepath = 'uploads/' . $_FILES['excel']['name'];
    move_uploaded_file($_FILES['excel']['tmp_name'], $filepath);
    $project_id = $_POST['projectId'];
    $project_name = $_POST['projectName'];
    $category_id = $_POST['category'];
    $file = $_FILES['excel']['name'];
}
?>
<!doctype html>
<html class="fixed">

<head>
    <!-- Basic -->
    <meta charset="UTF-8">
    <title>設計資料庫匯入工具</title>
    <meta name="keywords" content="HTML5 Admin Template" />
    <meta name="description" content="JSOFT Admin - Responsive HTML5 Template">
    <meta name="author" content="JSOFT.net">

    <script src="/DataBase/assets/vendor/jquery/jquery.js"></script>
    <!-- Mobile Metas -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

    <!-- Web Fonts  -->
    <link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800|Shadows+Into+Light" rel="stylesheet" type="text/css">
    <!-- jstree CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/themes/default/style.min.css">
    <!-- Vendor CSS -->
    <link rel="stylesheet" href="/DataBase/assets/vendor/bootstrap/css/bootstrap.css" />
    <link rel="stylesheet" href="/DataBase/assets/vendor/font-awesome/css/font-awesome.css" />
    <link rel="stylesheet" href="/DataBase/assets/vendor/magnific-popup/magnific-popup.css" />
    <link rel="stylesheet" href="/DataBase/assets/vendor/bootstrap-datepicker/css/datepicker3.css" />
    <link rel="stylesheet" href="/DataBase/assets/vendor/pnotify/pnotify.custom.css" />
    <!-- Specific Page Vendor CSS -->
    <link rel="stylesheet" href="/DataBase/assets/vendor/jquery-ui/css/ui-lightness/jquery-ui-1.10.4.custom.css" />
    <link rel="stylesheet" href="/DataBase/assets/vendor/bootstrap-multiselect/bootstrap-multiselect.css" />
    <link rel="stylesheet" href="/DataBase/assets/vendor/morris/morris.css" />
    <link rel="stylesheet" href="/DataBase/assets/vendor/bootstrap-fileupload/bootstrap-fileupload.min.css" />
    <!-- Theme CSS -->
    <link rel="stylesheet" href="/DataBase/assets/stylesheets/theme.css" />
    <!-- Skin CSS -->
    <link rel="stylesheet" href="/DataBase/assets/stylesheets/skins/default.css" />
    <!-- Theme Custom CSS -->
    <link rel="stylesheet" href="/DataBase/assets/stylesheets/theme-custom.css">
    <!-- Head Libs -->
    <script src="/DataBase/assets/vendor/modernizr/modernizr.js"></script>
    <!-- chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- DataTable -->

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script>
    <!-- Icon -->
    <link rel="shortcut icon" href="/DataBase/assets/images/favicon.ico" />
    <link href="https://js.arcgis.com/4.21/esri/themes/light/main.css" rel="stylesheet">
    <link href="/DataBase/CustomCSS/main.css" rel="stylesheet">
    <script src="/DataBase/script/js/bootstrap.js"></script>
    <script src="/DataBase/script/js/pdfobject.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.4/jstree.min.js"></script>

    <script src="https://js.arcgis.com/4.21/"></script>
    <style>
        body {
            color: #000;
        }

        .row {
            margin-top: -15px;
        }

        .page-header>ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .page-header>ul>li {
            display: inline-block;
            font-size: 25px;
            color: #FFFFFF;
        }

        .page-header>ul>li.right {
            float: right;
            padding-right: 10px;
        }

        .input-search {
            margin-top: 8px;
        }

        .page-header li>label {
            margin-top: 13px;
            border-bottom: 4px solid #0088cc;
            height: 41px;
            padding-left: 40px;
        }

        .sidebar-left {
            box-shadow: 0 0 0;
        }

        .jstree-default .jstree-icon {
            color: #ffe693;
        }

        .jqsfield {
            color: white;
            font: 10px arial, san serif;
            text-align: left;
        }

        .jstree-anchor {
            width: 250px;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
        }

        .jstree-anchor,
        .jstree-anchor:link,
        .jstree-anchor:visited,
        .jstree-anchor:hover,
        .jstree-anchor:active {
            color: #abb4be;
        }

        td,
        th {
            text-align: center;

        }

        #tablepage匯入資訊>thead>tr>th {
            width: 25%;
        }

        #tableform>thead>tr>th {
            width: 50%;
        }

        .nav-main {
            padding: 15px;
        }

        .node-hidden {
            display: none;
        }

        html.fixed .page-header {
            left: 0px;
        }

        html.fixed .content-body {
            margin-left: 0px;
        }

        .sidebar-left {
            width: 0px;
        }

        #viewDiv {
            height: 100%;
            width: 100%;
        }

        #zoom {
            margin-bottom: 5px;
        }

        #actions {
            padding: 5px;
        }

        .container {
            height: 50%;
            width: 100%;
        }

        #createSlideDiv {
            background-color: white;
            opacity: 0.9;
            color: black;
            padding: 6px;
        }

        #slidesDiv {
            background-color: white;
            opacity: 0.9;
            color: black;
            padding: 10px;
            visibility: hidden;
            bottom: 20px;
            overflow-y: auto;
            text-align: center;
            height: 260px;
        }

        #slidesDiv .slide {
            /* Show cursor as pointer when on a slide */
            cursor: pointer;
            margin-bottom: 6px;
        }

        #slidesDiv .slide .title {
            /* Center the title text */
            text-align: center;
        }

        /* Draw active slide with a nice border around the thumbnail */

        #slidesDiv .slide.active img {
            box-shadow: 0px 0px 12px black;
            border-style: solid;
            border-width: thin;
            border-color: black;
        }

        .pdfobject-container {
            height: 730px;
        }

        #topbar {
            background: #fff;
            padding: 10px;
        }

        /* uploadExcel */

        td>label {
            width: 8em;
            text-align: left;
            padding-right: 0.5em;
            /* display: inline-block; */
        }

        .excel {
            font-family: Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        .nav-tabs>li.active>a,
        .nav-tabs>li.active>a:focus,
        .nav-tabs>li.active>a:hover {
            border: 1px solid #000;
        }

        .excel td,
        .excel th {
            border: 1px solid #aaa;
            padding: 8px;
        }

        .excel tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        .excel tr:hover {
            background-color: #ddd;
        }

        .excel th {
            padding-top: 12px;
            padding-bottom: 12px;
            text-align: center;
            background-color: #004B7C;
            color: white;
        }

        table.dataTable tbody tr td.NullClass {
            background-color: #ed9c28;
        }

        table.dataTable tbody tr td.ErrorClass {
            background-color: #d2322d;
        }

        .submit {
            display: inline-block;
            margin-left: auto;
            margin-right: auto;
            width: 20%;
            background-color: #004B7C;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            font-size: 16px;
            margin: 10px;
        }

        .delete {
            background-color: red;
            border: none;
            color: white;
            padding: 5px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
        }

        .center {
            text-align: center;
        }

        .nav-tabs.nav-justified li.active a.error.text-center,
        a.error.text-center:hover {
            border-bottom-color: transparent;
            border-top: 3px solid #d2322d;
            box-shadow: none;
            color: #d2322d;
        }

        a.error.text-center,
        i.error,
        td.error {
            color: #d2322d;
        }

        .nav-tabs.nav-justified li.active a.warning.text-center,
        a.warning.text-center:hover {
            border-bottom-color: transparent;
            border-top: 3px solid #ed9c28;
            box-shadow: none;
            color: #ed9c28;
        }

        a.warning.text-center,
        i.warning,
        td.warning {
            color: #ed9c28;
        }

        .nav-tabs.nav-justified li.active a.info.text-center,
        a.info.text-center:hover {
            border-bottom-color: transparent;
            border-top: 3px solid #0088cc;
            box-shadow: none;
            color: #0088cc;
        }

        a.info.text-center,
        i.info {
            color: #0088cc;
        }

        .nav-tabs.nav-justified li.active a.success.text-center,
        a.success.text-center:hover {
            border-bottom-color: transparent;
            border-top: 3px solid #4a934a;
            box-shadow: none;
            color: #4a934a;
        }

        a.success.text-center,
        i.success {
            color: #4a934a;
        }

        .dataTables_wrapper .dataTables_filter label {
            width: initial;
        }

        .dataTables_wrapper .dataTables_filter input {
            width: initial;
        }
    </style>


</head>

<body>
    <section class="body">
        <!-- start: header -->
        <header class="header">
            <div class="logo-container">
                <div class="banner-txt">設計資料庫匯入工具</div>
                <div class="visible-xs toggle-sidebar-left" data-toggle-class="sidebar-left-opened" data-target="html" data-fire-event="sidebar-left-opened">
                    <i class="fa fa-bars" aria-label="Toggle sidebar"></i>
                </div>
            </div>
            <!-- start: search & user box -->
            <div class="header-right">
                <span class="separator"></span>
                <ul class="notifications">
                    <li>
                        <a href="/DataBase/upload.html" class="notification-icon" data-toggle="tooltip" title="匯入工具" data-placement="bottom">
                            <i class="fa fa-upload"></i>
                        </a>
                        <a href="/Front-Page/home.php" class="notification-icon" data-toggle="tooltip" title="綜合登入入口" data-placement="bottom">
                            <i class="fa fa-home"></i>
                        </a>
                    </li>
                </ul>
                <span class="separator"></span>
                <div id="userbox" class="userbox">
                    <a href="#" data-toggle="dropdown">
                        <figure class="profile-picture"> <img src="/DataBase/assets/images/!logged-user.jpg" alt="Joseph Doe" class="img-circle" data-lock-picture="/DataBase/assets/images/!logged-user.jpg" /> </figure>
                        <div class="profile-info" data-lock-name="John Doe" data-lock-email="johndoe@JSOFT.com"> <span class="name"><?php echo $_SESSION['name'] ?></span> <span class="role">tester</span> </div> <i class="fa custom-caret"></i>
                    </a>
                    <div class="dropdown-menu">
                        <ul class="list-unstyled">
                            <li class="divider"></li>
                            <li> <a role="menuitem" tabindex="-1" href="/DataBase/script/php/Logout.php"><i class="fa fa-power-off"></i> Logout</a> </li>
                        </ul>
                    </div>
                </div>
            </div>
            <!-- end: search & user box -->
        </header>
        <!-- end: header -->
        <div class="inner-wrapper">
            <!-- start: sidebar -->

            <section role="main" class="content-body">
                <header class="page-header">
                    <ul>
                        <li>
                            <label id="header"></label>
                        </li>
                    </ul>
                </header>

                <div class="row">
                    <div class="col-md-4 col-md-offset-8">
                        圖示顏色含意:　<i class="fa fa-info-circle info">匯入確認頁面</i>　<i class="fa fa-check-circle success">此頁面資料正確</i>　<i class="fa fa-exclamation-circle warning">此頁面資料有空</i>　<i class="fa fa-times-circle error">此頁面檔案路徑有誤</i>
                    </div>
                    <div class="col-md-12">
                        <div class="tabs">
                            <ul class="nav nav-tabs nav-justified" id="tabs">

                            </ul>
                            <div class="tab-content" id="tab-content">

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






    </section>
    <script type="text/javascript">
        var val = [];
        var error;
        var tables;
        var test;
        var searchTables = [];
        var tableIndex;
        var confirmMsg = "確定要匯入嗎?";
        var statusList = {
            "error": false,
            "warning": false
        };
        const statusDetail = {
            "error": "錯誤:檔案路徑有誤，請再次檢查檔案路徑是否正確。",
            "warning": "警告:有資料尚未填寫。"
        }
        const icons = {
            'info': 'fa fa-info-circle',
            'success': 'fa fa-check-circle',
            'error': 'fa fa-times-circle',
            'warning': 'fa fa-exclamation-circle',
        };
        var ErrorClass = function(settings, searchData, index, rowData) {
            var $td = searchTables[tableIndex].row(index).nodes().to$().find('td.ErrorClass');
            return $td.length;
        }
        var NullClass = function(settings, searchData, index, rowData) {
            var $td = searchTables[tableIndex].row(index).nodes().to$().find('td.NullClass');
            return $td.length;
        }
        var BothClasses = function(settings, searchData, index, rowData) {
            var $td = searchTables[tableIndex].row(index).nodes().to$().find('td.NullClass,td.ErrorClass');
            return $td.length;
        }

        $(document).ready(function() {
            const queryString = window.location.search;
            const urlParams = new URLSearchParams(queryString);
            var file = '<?= $file ?>';
            var categoryId = '<?= $category_id ?>';
            var projectId = '<?= $project_id ?>';
            var projectName = '<?= $project_name ?>';
            getExcel(file, projectId, projectName, categoryId);

            $('#form').submit(function() {
                var c = confirm(confirmMsg);
                return c;
            });

        });

        function getExcel(file, projectId, projectName, categoryId) {

            $.ajax({
                    url: "./getExcel.php",
                    data: {
                        file: file,
                        projectId: projectId,
                        categoryId: categoryId,
                        projectName:projectName,
                    },
                    async: false,
                    contentType: "application/json",
                    dataType: "json",
                    type: "GET",
                })
                .success(function(response) {
                    tables = response.table;
                    var info = response.info;
                    var statuses = response.statuses;
                    errors = response.errorLists;
                    var projectInfo = tables["匯入資訊"];
                    $("#header").append(projectInfo[1][0] + "-" + projectInfo[1][1]); // 16019-促進民間參與高雄市鳳山溪污水處理廠放流水回收再利用案之興建、移轉、營運

                    for (var tab in tables) {
                        let status = statuses[tab];
                        let active = '';
                        if (tab == "匯入資訊") {
                            active = 'class="active"';
                        }
                        if (statusList[status] != undefined & !statusList[status]) {
                            statusList[status] = true;
                            confirmMsg += "\n" + statusDetail[status];
                        }

                        console.log(status);
                        let icon = icons[status];
                        $('#tabs').append(`<li ${active}><a href="#page${tab}" data-toggle="tab" class="text-center ${status}"><i class="${icon}"></i> ${tab}</a></li>`);
                        $("#tab-content").append(`<div id="page${tab}" class="tab-pane fade"></div>`);
                        appendTable(tables[tab], `page${tab}`);



                    }
                    $(`#page匯入資訊`).append("<form id='form' method='post' action='./insertExcel.php'></form>");
                    appendTable(info, "form");
                    // TODO: add confirm message
                    $("#form").append(`<div class='center'><input class='submit' type='submit' value='開始匯入'><button type='button' class='submit' onClick=\"location.href='/DataBase/upload.html'\" >重新選擇檔案</button></div>`);
                    $("#form").append(`<input id='projectId' name='projectId' type='hidden' value='${projectId}'><input id='projectName' name='projectName' type='hidden' value='${projectName}'><input id='file' name='file' type='hidden' value='${file}'><input id='categoryId' name='categoryId' style='display:none;' value='${categoryId}'>`);
                })
                .error(function(error) {
                    console.log(error);
                })
                .complete(function() {
                    $('#page匯入資訊').addClass('in active')
                    let i = 1;

                    for (var tab in tables) {
                        if (tab != "匯入資訊" && tab != "注意事項") {


                            var errorList = [];

                            if (errors[tab] != "" & errors[tab] != undefined) {
                                errorList = errors[tab].split(',');
                                errorList.shift();
                            }

                            searchTables[tab] = $('#tablepage' + tab).DataTable({
                                dom: '<"#toolbar' + tab + '">lfrtip',
                                "language": {
                                    "processing": "處理中...",
                                    "loadingRecords": "載入中...",
                                    "lengthMenu": "顯示 _MENU_ 項資料",
                                    "zeroRecords": "沒有符合的結果或是沒有資料",
                                    "info": "顯示第 _START_ 至 _END_ 項資料，共 _TOTAL_ 項",
                                    "infoEmpty": "顯示第 0 至 0 項資料，共 0 項",
                                    "infoFiltered": "(從 _MAX_ 項資料中過濾)",
                                    "infoPostFix": "",
                                    "search": "搜尋:",
                                    "paginate": {
                                        "first": '<i class="fa fa-step-backward"></i>',
                                        "previous": '<i class="fa fa-backward"></i>',
                                        "next": '<i class="fa fa-forward"></i>',
                                        "last": '<i class="fa fa-step-forward"></i>'
                                    },
                                    "aria": {
                                        "sortAscending": ": 升冪排列",
                                        "sortDescending": ": 降冪排列"
                                    }
                                },
                                "columnDefs": [{
                                    "targets": -1,
                                    "createdCell": function(td, cellData, rowData, row, col) {
                                        if (errorList.length > 0) {
                                            for (i = 0; i < errorList.length; i++) {
                                                if (errorList[i] == row) {
                                                    $(td).addClass('ErrorClass');
                                                }
                                            }

                                        }
                                    }
                                }, {
                                    "targets": '_all',
                                    "createdCell": function(td, cellData, rowData, row, col) {
                                        if (cellData == "null") {
                                            $(td).addClass('NullClass');
                                        }
                                    }
                                }],
                            });
                            i++;
                            $('#toolbar' + tab).html(`<input name="check${tab}" id="errCheck${tab}" value="error" type="radio" >僅顯示錯誤檔案路徑</input>
                                                    <input name="check${tab}" id="nullCheck${tab}" value="null" type="radio" >僅顯示未填入的資料</input>
                                                    <input name="check${tab}" id="nullCheck${tab}" value="both" type="radio" >顯示所有異常資料</input>
                                                    <input name="check${tab}" id="nullCheck${tab}" value="all" type="radio"  checked="checked">顯示所有資料</input>`);
                            /*$(`input[name='check${tab}']`).on("click", function() {
                                $.fn.dataTable.ext.search.pop();
                                if ($(this).val() == "error") {
                                    $.fn.dataTable.ext.search.push(ErrorClass);
                                } else if ($(this).val() == "null") {
                                    $.fn.dataTable.ext.search.push(NullClass);
                                } else if ($(this).val() == "both") {
                                    $.fn.dataTable.ext.search.push(BothClasses);
                                } else {
                                    $.fn.dataTable.ext.search.pop();
                                }
                                console.log(tab);
                                searchTables["3_設計圖"].draw();


                            });*/
                            
                            if (document.querySelector(`input[name="check${tab}"]`)) {
                                document.querySelectorAll(`input[name="check${tab}"]`).forEach((elem) => {
                                    elem.addEventListener("change", function(event) {
                                       var item = event.target.value;
                                        
                                        tableIndex = event.target.parentElement.id.split('bar')[1];
                                        $.fn.dataTable.ext.search.pop();
                                        if (item == "error") {
                                            $.fn.dataTable.ext.search.push(ErrorClass);
                                        } else if (item == "null") {
                                            $.fn.dataTable.ext.search.push(NullClass);
                                        } else if (item == "both") {
                                            $.fn.dataTable.ext.search.push(BothClasses);
                                        } else {
                                            $.fn.dataTable.ext.search.pop();
                                        }
                                        console.log(tableIndex);

                                        searchTables[tableIndex].draw();
                                    });
                                });
                            }
                           
                        }
                    }



                });
        }

        function appendTable(data, id) {
            let i = 0;
            table = `<table id='table${id}' class='excel'><thead>`;
            for (var tab in data) {
                table += "<tr>";

                for (j = 0; j < data[tab].length; j++) {
                    if (i == 0)
                        table += `<th>${data[tab][j]}</th>` //style="width:33%;"
                    else
                        table += `<td>${data[tab][j]}</td>`
                }

                table += "</tr>";
                if (i == 0) {
                    table += "</thead><tbody>";
                }
                i++;
            }


            table += "</tbody></table>";

            $('#' + id).append(table);
        }
    </script>

</body>

</html>