<?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 Buttons</title>
    <meta name="description" content="Add buttons to dashboard to launch applications with one click">
    <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">Add Buttons to Dashboard</div>

                <div class="clearfix"></div>
                <!-- Orders -->
                <div class="orders">
                    <div class="row">
                   <!-- <div class="col-xl-8"> -->
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body">
                                     <div class="tableTitle"><h4 class="box-title">Add buttons to dashboard to launch applications with one click:</h4></div>
                                </div>
                                <div class="card-body--">
                                    <div class="table-stats order-table ov-h">
                                        <table id="linksTable" class="table">
                                            <thead>
                                                <tr>
                                                    <th class="columntitle">No</th>
                                                    <th class="columntitle" title="The place of the button in the ordered list on the dashboard.">Order</th>
                                                    <th class="databaseID">DB ID</th>
                                                    <th class="columntitle" title="The name that will appear on the button.">Name on button</th>
                                                    <th class="columntitle" title="The URL that will be opened by clicking on the button.">Link behind button</th>
                                                    <th class="columntitle" title="The image that will appear on the button in front of the name. Allowed formats: jpg, jpeg, png, svg.">Image on button</th>
                                                    <th class="columntitle"></th>
                                                    <th class="columntitle"></th>
                                                </tr>
                                            </thead>
                                            <tbody id="buttonTableTbody">

                                            <?php

                                              $selbttnquery = $mysqli->query("SELECT id, orderno, nameonbutton, buttonurl, imgname FROM buttons");

                                              $geturls = [];
                                              while ($result_fetch = $selbttnquery->fetch_row()) {
                                                     $inddbid = $result_fetch[0];
                                                     $indorderno = $result_fetch[1];
                                                     $indnameonbutton = $result_fetch[2];
                                                     $indurl = $result_fetch[3];
                                                     $indimgname = $result_fetch[4];
                                                     $geturls[] = [$inddbid, $indorderno, $indnameonbutton, $indurl, $indimgname];
                                              }

                                              $selbttnquery->close();

                                              for ($r = 0; $r < count($geturls); $r++) {
                                                   echo '<tr class="btnTableRow"><td class="currentNo">'.($r + 1).'</td><td><input type="text" class="orderNumber" value="'.$geturls[$r][1].'" disabled="disabled" /></td><td class="databaseID">'.$geturls[$r][0].'</td><td><input type="text" class="nameOnButton" name="nameonbttn" value="'.$geturls[$r][2].'" disabled="disabled" /></td><td><input type="text" class="buttonLink" name="bttnlink" value="'.$geturls[$r][3].'" disabled="disabled" /></td><td><form class="buttonLogoForm" enctype="multipart/form-data"><input type="file" id="buttonImage_'.($r+1).'" class="compPicture" name="compPicture" /></form><span class="showimageurl">'.$geturls[$r][4].'</span></td><td><span class="deleterow ti-close" title="Delete button data from database."></span></td><td><input type="submit" class="saveLinkButton" name="addlinkbttn" value="Edit" title="Edit this row."/></td></tr>';
                                              }

                                            ?>

                                            </tbody>
                                        </table>

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

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

                    </div>
                </div>
                <!-- /.orders -->

<?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();
  $("#addbuttons").css("color", "#03A9F3");

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

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

      $("#linksTable").append('<tr class="btnTableRow"><td class="currentNo">'+currentrowno+'</td><td><input type="text" class="orderNumber" value="" title="The place of the button in the ordered list on the dashboard." /></td><td class="databaseID"></td><td><input type="text" class="nameOnButton" name="nameonbttn" title="The name that will appear on the button." /></td><td><input type="text" class="buttonLink" name="bttnlink" title="The URL that will be opened by clicking on the button." /></td><td><form class="buttonLogoForm" enctype="multipart/form-data"><input type="file" id="buttonImage_'+currentrowno+'" class="compPicture" name="compPicture" title="The image that will appear on the button in front of the name (allowed formats: jpg, jpeg, png, svg; 40px in height preferably)." /></form><span class="showimageurl"></span></td><td><span class="deleterow ti-close" title="Delete this button from the database."></span></td><td><input type="submit" class="saveLinkButton" name="addlinkbttn" value="Save" title="Save input data to the database." /></td></tr>');

  });

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

  $("#linksTable").on("change", ".compPicture", function() {

    var formData = new FormData();
    var fileData = $(this).closest('[class*="btnTableRow"]').find('[class*="compPicture"]').prop('files')[0];
    formData.append('uploadedimage', fileData);

    var rownb = $(this).closest('[class*="btnTableRow"]').find('[class*="currentNo"]').text();
    var imagefileup = $(this).closest('[class*="btnTableRow"]').find('[class*="compPicture"]').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-button-image.php",
                  data: formData,
                  dataType: "JSON",
                  cache: false,
                  processData: false,
                  contentType: false,
                  success: function(result) {

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

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

  });

  $("#linksTable").on("click", ".saveLinkButton", function() {

    var currentrownb = $(this).closest('[class*="btnTableRow"]').find('[class*="currentNo"]').text();

    if ($(this).val() == "Save") {
        var ordernumber = $(this).closest('[class*="btnTableRow"]').find('[class*="orderNumber"]').val();
        var databaseid = $(this).closest('[class*="btnTableRow"]').find('[class*="databaseID"]').text();
        var roleofuser = "<?php print_r($_SESSION['userrole']); ?>";
        var nameofuser = "<?php print_r($_SESSION['login']); ?>";
        var nameonbttninit = $(this).closest('[class*="btnTableRow"]').find('[class*="nameOnButton"]').val();
        var nameonbttnsec = nameonbttninit.replace(/'/g,"&apos;");
        var nameonbttn = nameonbttnsec.replace(/"/g, "&quot;");
        var link = $(this).closest('[class*="btnTableRow"]').find('[class*="buttonLink"]').val();
        var indimgname = $(this).closest('[class*="btnTableRow"]').find('[class*="compPicture"]').val();
        var currentPicName = indimgname.split('\\').pop();

        if ((ordernumber != '') && (roleofuser != '') && (nameofuser != '') && (nameonbttn != '') && (link != '')) {

            $.ajax({
               type: "POST",
               url: "save-button.php",
               dataType: "JSON",
               data: {
                      ordno: ordernumber,
                      dbid: databaseid,
                      userrole: roleofuser,
                      username: nameofuser,
                      nameonbutton: nameonbttn,
                      buttonurl: link,
                      imgname: currentPicName
                     },
               success: function(result) {
                           location.reload();
               },
               error: function(result) {
                           alert(result.messageonsave);
               }
            });

            $(this).closest('[class*="btnTableRow"]').find('[class*="orderNumber"]').attr("disabled", true);
            $(this).closest('[class*="btnTableRow"]').find('[class*="nameOnButton"]').attr("disabled", true);
            $(this).closest('[class*="btnTableRow"]').find('[class*="buttonLink"]').attr("disabled", true);
            $(this).closest('[class*="btnTableRow"]').find('[class*="compPicture"]').attr("disabled", true);
            $(this).attr("value", "Edit");
        } else { alert("Please fill in at least the 'Order', 'Name on button' and 'Link behind button' fields."); }

    } else {

        $(this).closest('[class*="btnTableRow"]').find('[class*="orderNumber"]').attr("disabled", false);
        $(this).closest('[class*="btnTableRow"]').find('[class*="nameOnButton"]').attr("disabled", false);
        $(this).closest('[class*="btnTableRow"]').find('[class*="buttonLink"]').attr("disabled", false);
        $(this).closest('[class*="btnTableRow"]').find('[class*="compPicture"]').attr("disabled", false);
        $(this).attr("value", "Save");
        $(this).prop("title", "Save this row.");
      }
  });


  $("#linksTable").on("click", ".deleterow", function(){
         var iddb = $(this).closest('[class*="btnTableRow"]').find('[class*="databaseID"]').text();

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

             $.ajax({
                 type: "POST",
                 url: "remove-button.php",
                 dataType: "JSON",
                 data: {
                         databaseId: iddb
                       },
                 success: function(response) {
                 },
                 error: function(response) {
                            alert(response.messageondelete);
                 }
             });

             $(this).closest('[class*="btnTableRow"]').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");
}

?>
