<?php
/**
 * @copyright 2024 Double Bastion LLC <www.doublebastion.com>
 *
 * @author Double Bastion LLC
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

define('ACCESSCONST', TRUE);

require('db-connect.php');

session_start();

if (($_SESSION['loggedtorspanel'] == true) && ($_SESSION['userrole'] == 'superadmin')) {

?>

<!doctype html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Add Components</title>
    <meta name="description" content="Edit Components List">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="shortcut icon" type="image/png" href="images/favicon.png" />
    <link rel="stylesheet" href="assets/css/normalize.min.css">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/font-awesome-4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="assets/css/themify-icons/themify-icons.css">
    <link rel="stylesheet" href="assets/css/cs-skin-elastic.css">
    <link rel="stylesheet" href="assets/css/style.css">

    <script type="text/javascript" src="assets/js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="assets/js/jquery.min.js"></script>

    <script type="text/javascript" src="assets/js/popper.min.js"></script>
    <script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="assets/js/jquery.matchHeight.min.js"></script>
    <script type="text/javascript" src="assets/js/main.js"></script>
    <script type="text/javascript" src="assets/js/moment.min.js"></script>

    <script type="text/javascript" src="assets/js/settingsmenu.js"></script>
    <script type="text/javascript" src="assets/js/arrow-up.js"></script>
</head>

<body>

<?php include 'panels.php'; ?>

        <!-- Content -->

        <div class="content">

                <div class="pagetitle">Edit Components List</div>

                <div class="clearfix"></div>
                <div class="orders">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="tableTitle"><h4 class="box-title">Edit the list of suite components:</h4></div>
                                </div>
                                <div class="card-body--">
                                    <div class="table-stats order-table ov-h">
                                        <table id="compTable" class="table">
                                            <thead>
                                                <tr>
                                                    <th class="columntitle">No</th>
                                                    <th class="columntitle" title="The place of the component in the ordered list on the dashboard.">Order</th>
                                                    <th class="databaseID">DB ID</th>
                                                    <th class="columntitle" title="The name of the component as it will appear on the dashboard list.">Component name</th>
                                                    <th class="columntitle" title="Whether the application is a kernel, a shell or a hull component. The background color for each type will be different.">Component role</th>
                                                    <th class="columntitle" title="The level of indentation of the application on the dashboard list: the first level is for the operating system, the second level is for the applications installed directly inside the operating system, such as WordPress, and the third level is for the applications installed inside the preceding second level applications, such as WooCommerce which is installed inside WordPress.">Indentation</th>
                                                    <th class="columntitle" title="The image that will appear in front of the name. Allowed formats: jpg, jpeg, png, svg.">Component logo</th>
                                                    <th class="columntitle" title="The name of the script located in the 'version-scripts' folder that is run on page load to check and display the version of the application.">Version script</th>
                                                    <th class="columntitle" title="The component description that will appear as an info popup.">Info</th>
                                                    <th class="columntitle"></th>
                                                    <th class="columntitle"></th>
                                                </tr>
                                            </thead>
                                            <tbody id="buttonTableTbody">

                                            <?php

                                              $compquery = $mysqli->query("SELECT id, orderno, component, componentrole, componentplace, imagename, versionscript,
                                                                           info FROM components");

                                              $getcompname = [];
                                              while ($result_fetch = $compquery->fetch_row()) {
                                                     $inddbid = $result_fetch[0];
                                                     $indorderno = $result_fetch[1];
                                                     $componentname = $result_fetch[2];
                                                     $componentrole = $result_fetch[3];
                                                     $componentplace = $result_fetch[4];
                                                     $imagename = $result_fetch[5];
                                                     $versionscript = $result_fetch[6];
                                                     $infopopup = $result_fetch[7];
                                                     $getcompname[] = [$inddbid, $indorderno, $componentname, $componentrole, $componentplace, $imagename, $versionscript, $infopopup];
                                              }

                                              $compquery->close();

                                              $rolearr = ["Kernel Component", "Shell Component", "Hull Component"];
                                              $placearr = ["First Level", "Second Level", "Third Level"];

                                              for ($r = 0; $r < count($getcompname); $r++) {

                                                   $roleopt2init = array_values(array_diff($rolearr, array($getcompname[$r][3])));
                                                   $roleopt2 = $roleopt2init[0];
                                                   $roleopt2sec = $roleopt2init[1];

                                                   $placeopt2init = array_values(array_diff($placearr, array($getcompname[$r][4])));
                                                   $placeopt2 = $placeopt2init[0];
                                                   $placeopt2sec = $placeopt2init[1];

                                                   echo '<tr class="compTableRow"><td class="currentNo">'.($r + 1).'</td><td><input type="text" class="orderNumber" value="'.$getcompname[$r][1].'" disabled="disabled" /></td><td class="databaseID">'.$getcompname[$r][0].'</td><td><input type="text" class="componentName" name="componentName" value="'.$getcompname[$r][2].'" disabled="disabled" /></td><td><select class="componentRole" name="componentRole" disabled="disabled"><option value="'.$getcompname[$r][3].'">'.$getcompname[$r][3].'</option><option value="'.$roleopt2.'">'.$roleopt2.'</option><option value="'.$roleopt2sec.'">'.$roleopt2sec.'</option></select></td><td><select class="componentPlace" name="componentPlace" disabled="disabled"><option value="'.$getcompname[$r][4].'">'.$getcompname[$r][4].'</option><option value="'.$placeopt2.'">'.$placeopt2.'</option><option value="'.$placeopt2sec.'">'.$placeopt2sec.'</option></select></td><td class="uploadcompimg"><form class="compImageForm" enctype="multipart/form-data"><input type="file" id="componentImage_'.($r+1).'" class="compImage" name="compImage" /></form><span class="imagenameshow">'.$getcompname[$r][5].'</span></td><td><input type="text" class="versionScript" value="'.$getcompname[$r][6].'" disabled="disabled" /></td><td><textarea rows="2" cols="50" class="infoPopup" disabled="disabled" >'.$getcompname[$r][7].'</textarea></td><td><span class="deleterow ti-close" title="Delete component from database."></span></td><td><input type="submit" class="saveCompButton" name="saveCompButton" value="Edit" title="Edit this row."/></td></tr>';
                                              }

                                            ?>

                                            </tbody>
                                        </table>

                                        <input type="button" id="addNewButton" value="Add Component"/>

                                    </div> <!-- /.table-stats -->
                                </div>
                            </div> <!-- /.card -->
                        </div>  <!-- /.col-lg-12 -->


                    </div>
                </div>

<?php include 'about.php'; ?>

        </div>

        <!-- /.content -->

        <div class="clearfix"></div>

<?php include 'footer.php'; ?>

    </div>
    <!-- /#right-panel -->

    <button id="upBttn"></button>


<script type="text/javascript">

  $("#settingsdroparea").show();
  $("#editcomponents").css("color", "#03A9F3");

  $("#addNewButton").on("click", function() {

      var firstrowno = $("#compTable tr:last-child").closest('[class*="compTableRow"]').find('[class*="currentNo"]').text();
      if (firstrowno != '') {
          var currentrowno = parseInt(firstrowno) + 1;
      } else {
          var currentrowno = 1;
        }

      $("#compTable").append('<tr class="compTableRow"><td class="currentNo">'+currentrowno+'</td><td><input type="text" class="orderNumber" value="" title="The place of the component in the ordered list on the dashboard." /></td><td class="databaseID"></td><td><input type="text" class="componentName" name="componentName" title="The name of the component as it will appear on the dashboard list." /></td><td><select class="componentRole" name="componentRole" title="Whether the application is a kernel, shell or hull component. Kernel components will have blue background, shell components will have purple background and hull components will have green background."><option value="Kernel Component">Kernel Component</option><option value="Shell Component">Shell Component</option><option value="Hull Component">Hull Component</option></select></td><td><select class="componentPlace" name="componentPlace" title="The level of indentation of the application on the dashboard list: the first level is for the operating system, the second level is for the applications installed directly inside the operating system, such as WordPress, and the third level is for the applications installed inside the preceding second level applications, such as WooCommerce which is installed inside WordPress."><option value="First Level">First Level</option><option value="Second Level">Second Level</option><option value="Third Level">Third Level</option></select></td><td class="uploadcompimg"><form class="compImageForm" enctype="multipart/form-data"><input type="file" id="componentImage_'+currentrowno+'" class="compImage" name="compImage" title="The image that will appear in front of the name (allowed formats: jpg, jpeg, png, svg; 40px in height preferably)." /></form><span class="imagenameshow"></span></td><td><input type="text" class="versionScript" title="The name of the script located in the `version-scripts` folder that is run on page load to check and display the version of the application." /></td><td><textarea rows="2" cols="50" class="infoPopup" title="The component description that will appear in the info popup."></textarea></td><td><span class="deleterow ti-close" title="Delete this component from the database."></span></td><td><input type="submit" class="saveCompButton" name="saveCompButton" value="Save" /></td></tr>');

  });

  $(".compImage").attr("disabled", true);

  $("#compTable").on("change", ".compImage", function() {

    var formData = new FormData();

    var fileData = $(this).closest('[class*="compTableRow"]').find('input[type=file]')[0].files[0];
    formData.append('uploadedcompimage', fileData);

    var rownb = $(this).closest('[class*="compTableRow"]').find('[class*="currentNo"]').text();
    var imagefileup = $(this).closest('[class*="compTableRow"]').find('input[type=file]').val();

    var extension = imagefileup.replace(/^.*\./, '');

    if (extension == imagefileup) {
        extension = "";
    } else {
         extension = extension.toLowerCase();
      }

    var validExtensions = ["jpg", "jpeg", "png", "svg"];

    if (fileData != '') {

       if (jQuery.inArray(extension, validExtensions) != -1) {

                $.ajax({
                  type: "POST",
                  url: "upload-component-image.php",
                  data: formData,
                  dataType: "JSON",
                  cache: false,
                  processData: false,
                  contentType: false,
                  success: function(response) {

                           if (response.messagetosend == '') {
                               alert("File uploaded successfully !");
                           } else {
                               alert(response.messagetosend);
                             }
                  },
                  error: function() {
                         alert("An error occurred while uploading the file !");
                         $(this).closest('[class*="compTableRow"]').find('[class*="compImage"]').val("");
                  }
                });

       } else {
            alert('The file type ' + imagefileup + '    is not supported ! Supported formats are "jpg", "jpeg" "png" and "svg".');
            $(this).closest('[class*="compTableRow"]').find('[class*="compImage"]').val("");
         }
    }

  });


  $("#compTable").on("click", ".saveCompButton", function() {

    if ($(this).val() == "Save") {
        var ordernumber = $(this).closest('[class*="compTableRow"]').find('[class*="orderNumber"]').val();
        var databaseid = $(this).closest('[class*="compTableRow"]').find('[class*="databaseID"]').text();
        var roleofuser = "<?php print_r($_SESSION['userrole']); ?>";
        var nameofuser = "<?php print_r($_SESSION['login']); ?>";
        var nameofcompinit = $(this).closest('[class*="compTableRow"]').find('[class*="componentName"]').val();
        var nameofcompsec = nameofcompinit.replace(/'/g,"&apos;");
        var nameofcomp = nameofcompsec.replace(/"/g, "&quot;");
        var comprole = $(this).closest('[class*="compTableRow"]').find('[class*="componentRole"]').val();
        var compplace = $(this).closest('[class*="compTableRow"]').find('[class*="componentPlace"]').val();
        var picturename = $(this).closest('[class*="compTableRow"]').find('input[type=file]').val();
        var indimagename = picturename.split('\\').pop();
        var indversionscript = $(this).closest('[class*="compTableRow"]').find('[class*="versionScript"]').val();
        var indinfopopupinit = $(this).closest('[class*="compTableRow"]').find('[class*="infoPopup"]').val();
        var indinfopopupsec = indinfopopupinit.replace("\'","&apos;");
        var indinfopopup = indinfopopupsec.replace("\"","&quot;");

        if ((ordernumber != '') && (roleofuser != '') && (nameofuser != '') && (nameofcomp != '')) {
            $.ajax({
               type: "POST",
               url: "save-component.php",
               dataType: "JSON",
               data: {
                      ordno: ordernumber,
                      dbid: databaseid,
                      userrole: roleofuser,
                      username: nameofuser,
                      componentname: nameofcomp,
                      componentrole: comprole,
                      componentplace: compplace,
                      imagename: indimagename,
                      versionscript: indversionscript,
                      infopopup: indinfopopup
                     },
               success: function(result) {
                     location.reload();
               },
               error: function(result) {
                     alert(result.responsave);
               }
            });

            $(this).closest('[class*="compTableRow"]').find('[class*="orderNumber"]').attr("disabled", true);
            $(this).closest('[class*="compTableRow"]').find('[class*="componentName"]').attr("disabled", true);
            $(this).closest('[class*="compTableRow"]').find('[class*="componentRole"]').attr("disabled", true);
            $(this).closest('[class*="compTableRow"]').find('[class*="componentPlace"]').attr("disabled", true);
            $(this).closest('[class*="compTableRow"]').find('[class*="compImage"]').attr("disabled", true);
            $(this).closest('[class*="compTableRow"]').find('[class*="versionScript"]').attr("disabled", true);
            $(this).closest('[class*="compTableRow"]').find('[class*="infoPopup"]').attr("disabled", true);
            $(this).attr("value", "Edit");
        } else { alert("Please fill in at least the 'Order' and 'Component name' fields."); }

    } else {
        $(this).closest('[class*="compTableRow"]').find('[class*="orderNumber"]').attr("disabled", false);
        $(this).closest('[class*="compTableRow"]').find('[class*="componentName"]').attr("disabled", false);
        $(this).closest('[class*="compTableRow"]').find('[class*="componentRole"]').attr("disabled", false);
        $(this).closest('[class*="compTableRow"]').find('[class*="componentPlace"]').attr("disabled", false);
        $(this).closest('[class*="compTableRow"]').find('[class*="compImage"]').attr("disabled", false);
        $(this).closest('[class*="compTableRow"]').find('[class*="versionScript"]').attr("disabled", false);
        $(this).closest('[class*="compTableRow"]').find('[class*="infoPopup"]').attr("disabled", false);
        $(this).attr("value", "Save");
        $(this).prop("title", "Save this row.");
      }
  });


  $("#compTable").on("click", ".deleterow", function(){

         var DBid = $(this).closest('[class*="compTableRow"]').find('[class*="databaseID"]').text();

         if (confirm("Do you really want to delete this component from the database ?")) {

             $.ajax({
                 type: "POST",
                 url: "remove-component.php",
                 dataType: "JSON",
                 data: {
                        database_id: DBid
                       },
                 success: function(compresponse) {
                 },
                 error: function(compresponse) {
                    alert(compresponse.messagedelcom);
                }
             });

             $(this).closest('[class*="compTableRow"]').hide();
         }
  });

</script>

</body>
</html>

<?php

} elseif (empty($_SESSION['loggedtorspanel'])) {

      header("Location: panel-login.php");

} elseif (($_SESSION['loggedtorspanel'] == true) && ($_SESSION['userrole'] != 'superadmin'))  {

      header("Location: index.php");
}

?>

