<?php
include("core/init.php");
include("session.php");
require_once('classes/FileUpload.php');

/***********Table Used**********/
$mainTable = "content_manager"; //Module main table name.
$uploadDir = "../uploads/cms/"; //Module folder name.

/****************Add & Edit Process Starts Here**********************/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && Input::exists() && Token::check(Input::getInput("token"))) {

  if (Input::getInput("cmsId") == "" && Input::getInput("page_name") != "") {
    $image = "";
    if ( isset($_FILES['headerImage']) && $_FILES['headerImage']['error'] !== UPLOAD_ERR_NO_FILE && is_uploaded_file($_FILES['headerImage']['tmp_name']) ) {
      $uploader = new FileUpload(rtrim($uploadDir, "/"), [
        'type' => ['jpg,jpeg,png,gif'],
        'size' => 2, // In MB
      ], $_FILES['headerImage']);

      $uploader->upload();

      if ($uploader->passed()) {
        $imageArr = $uploader->getName();
        $image = $imageArr[0];
      } else {
        Session::flash("message", '<div class="alert-error" style="padding: 5px;">' . $uploader->displayErrors() . '</div><br>');
      }
    }

    Db::getInstance()->insert($mainTable, array(
      "page_name" => addslashes(Input::getInput("page_name")),
      "url" => addslashes(str_replace(" ", "", Input::getInput("url"))),
      "page_title" => addslashes(Input::getInput("page_title")),
      "meta_keyword" => addslashes(Input::getInput("meta_keyword")),
      "meta_description" => addslashes(Input::getInput("meta_description")),
      "extra_tags" => addslashes(Input::getInput("extra_tags")),
      "status" => addslashes(Input::getInput("status")),
      "headerImage" => addslashes($image),
      "page_description" => addslashes(Input::getInput("page_description")),
      "province_id" => addslashes(Input::getInput("province_id"))
    ));
    Session::flash("message", '<div class="alert-success" style="padding: 5px;">CMS Added.</div><Br>');
    Redirect::to("Cms");
  } else if (Input::getInput("cmsId") != "" && Input::getInput("page_name") != "") {
    $exst_image = "";
    if (Input::getInput("exst_image") != "") {
      $exst_image = Input::getInput("exst_image");
      $image = $exst_image;
    }
    else{
      $image = "";
    }
    // New upload
    if ( isset($_FILES['headerImage']) && $_FILES['headerImage']['error'] !== UPLOAD_ERR_NO_FILE && is_uploaded_file($_FILES['headerImage']['tmp_name']) ) {
      $uploader = new FileUpload(rtrim($uploadDir, "/"), [
        'type' => ['jpg,jpeg,png,gif'],
        'size' => 2, // In MB
      ], $_FILES['headerImage']);

      $uploader->upload();

      if ($uploader->passed()) {
        $imageArr = $uploader->getName();
        $image = $imageArr[0];
        // Delete existing image
        if ($exst_image != "") {
          $filepath = $uploadDir . $exst_image;

          if (file_exists($filepath)) {
              unlink($filepath);
          }
        }
      } else {
        Session::flash("message", '<div class="alert-error" style="padding: 5px;">' . $uploader->displayErrors() . '</div><br>');
        Redirect::to("Cms?editId='" . Input::getInput("cmsId"));
      }
    }
    
    Db::getInstance()->update(
      $mainTable,
      $arrdata = array(
        "page_name" => addslashes(Input::getInput("page_name")),
        "url" => addslashes(str_replace(" ", "", Input::getInput("url"))),
        "page_title" => addslashes(Input::getInput("page_title")),
        "meta_keyword" => addslashes(Input::getInput("meta_keyword")),
        "meta_description" => addslashes(Input::getInput("meta_description")),
        "extra_tags" => addslashes(Input::getInput("extra_tags")),
        "status" => addslashes(Input::getInput("status")),
        "headerImage" => addslashes($image),
        "page_description" => addslashes(Input::getInput("page_description")),
        "province_id" => addslashes(Input::getInput("province_id"))
      ),
      array("id" => Input::getInput("cmsId"))
    );

    Session::flash("message", '<div class="alert-success" style="padding: 5px;">CMS Edited Successfully.</div><Br>');
    Redirect::to("Cms");
  } else {
    Session::flash("message", '<div class="alert-error" style="padding: 5px;">Please Fill Title.</div><Br>');
    Redirect::to("Cms");
  }
}
/****************Add & Edit Process Starts Here**********************/

/****************Edit Populate**********************/
$populateCms = null;
if (Input::particularInputExists("get", "editId")) {

  if (Db::getInstance()->num_rows("select id from {$mainTable} where id='" . Input::getInput("editId") . "'") > 0) {
    $populateCms = Db::getInstance()->get_row("select * from {$mainTable} where id='" . Input::getInput("editId") . "'");
  } else {

    Redirect::to("Cms");
  }
}
/****************Edit Populate Ends**********************/

/****************Delete**********************/
if (Input::particularInputExists("get", "deleteId")) {

  if (Db::getInstance()->num_rows("select id from {$mainTable} where id='" . Input::getInput("deleteId") . "'") > 0) {
    // Delete image
    $rowData = Db::getInstance()->get_row("select headerImage from {$mainTable} where id='" . Input::getInput("deleteId") . "'");
    $exstImage = Input::getInput("headerImage", $rowData);
    if ($exstImage != "") {
      $filepath = $uploadDir . $exstImage;

      if (file_exists($filepath)) {
          unlink($filepath);
      }
    }

    $result = Db::getInstance()->delete($mainTable, array("id" => Input::getInput("deleteId")));

    if ($result === true) {
      Session::flash("message", '<div class="alert-success" style="padding: 5px;">The CMS data has been deleted successfully.</div><br>');
    } elseif ($result === false) {
      Session::flash("message", '<div class="alert-error" style="padding: 5px;">The CMS data was not deleted successfully.</div><br>');
    }

    Redirect::to("Cms");
  } else {
    Redirect::to("Cms");
  }
}
/****************Delete Ends**********************/

/****************Delete Single Image Start**********************/

if (Input::particularInputExists("get", "rmvImg")) {
  if (Input::getInput("rmvImg") == "yes" && Input::getInput("id") > 0 && Input::getInput("imgFld") != "" && Input::getInput("imgNme") != "") {
    if (Db::getInstance()->num_rows("select id from {$mainTable} where id='" . Input::getInput("id") . "'") > 0) {
      $filepath = $uploadDir . base64_decode(Input::getInput("imgNme"));

      if (file_exists($filepath)) {
          unlink($filepath);
      }

      $result = Db::getInstance()->update(
        $mainTable,
        array(
          "headerImage" => ""
        ),
        array("id" => Input::getInput("id"))
      );

      if ($result === true) {
        Session::flash("message", '<div class="alert-success" style="padding: 5px;">The CMS header image has been deleted successfully.</div><br>');
      } elseif ($result === false) {
        Session::flash("message", '<div class="alert-error" style="padding: 5px;">The CMS header image was not deleted successfully.</div><br>');
      } elseif ($result === 0) {
        Session::flash("message", '<div class="alert-info" style="padding: 5px;">No rows were updated, possibly because the value was already blank. No further action is required.</div><br>');
      }
      Redirect::to("Cms");
    } else {
      Session::flash("message", '<div class="alert-error" style="padding: 5px;">The required data for image deletion is missing. Please contact the development support team for assistance.</div><br>');
      Redirect::to("Cms");
    }
  }
}

/****************Delete Single Image Ends**********************/
?>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Cms - <?php echo Config::get("project/site_title"); ?></title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <link rel="shortcut icon" href="dist/img/admin-panel.png">
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <!-- Bootstrap 3.3.6 -->
  <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

  <?php include("includes/inc-editor-css.php"); ?>

  <!-- Theme style -->
  <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">


  <link rel="stylesheet" href="dist/css/AdminLTE.min.css">
  <!-- AdminLTE Skins. Choose a skin from the css/skins
       folder instead of downloading all of them to reduce the load. -->
  <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->


  <Style>
    #result {
      margin-left: 5px;
    }

    .short {
      color: #FF0000;
    }

    .weak {
      color: #E66C2C;
    }

    .good {
      color: #2D98F3;
    }

    .strong {
      color: #006400;
    }
  </Style>

</head>

<body class="hold-transition skin-blue sidebar-mini">
  <div class="wrapper">




    <?php include("includes/header.php"); ?>






    <?php include("includes/sidebar.php"); ?>


    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
      <section class="content-header">
        <h1>
          CMS
          <small></small>
        </h1>
        <ol class="breadcrumb">
          <li><a href="Dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
          <li class="active">CMS</li>
        </ol>
      </section>

      <!-- Main content -->
      <section class="content">

        <div class="row">


          <div class="col-md-12">

            <?php echo Session::flashDisplay("message"); ?>

            <a href="Cms?addNew" class="btn btn-primary" style="margin-bottom: 10px;">Add New</a>
            <?php if (isset($_GET["addNew"]) || isset($_GET["editId"])) { ?>
              <!-- general form elements -->
              <div class="box box-primary">
                <div class="box-header with-border">

                </div>
                <!-- /.box-header -->
                <!-- form start -->
                <form role="form" action="Cms" method="post" id="form_" enctype="multipart/form-data">
                  <div class="box-body">
                    <div class="alert-danger" style="padding: 5px;display: none;" id="error">* Fields Required.</div>
                    <?php

                    $dbProvinces = Db::getInstance()->get_results("select id,province from province where isActive=1");

                    $provinces = array();
                    if (count($dbProvinces)) foreach ($dbProvinces as $dbProvince) {
                      $provinces[$dbProvince["id"]] = $dbProvince["province"];
                    }
                    // print_r($provinces);
                    ?>


                    <div class="form-group">
                      <label for="exampleInputPassword1">Select Location *</label>
                      <select name="province_id" class="form-control">
                        <?php echo Input::getSelected("province_id", $populateCms, $provinces); ?>
                      </select>


                    </div>

                    <div class="form-group">
                      <label for="exampleInputPassword1">Page Name *</label>
                      <input type="text" class="form-control" name="page_name" id="page_name" value="<?php echo Input::getInput("page_name", $populateCms); ?>">
                    </div>




                    <div class="form-group">
                      <label for="exampleInputPassword1">Url *</label>
                      <input type="text" class="form-control" name="url" id="url" value="<?php echo Input::getInput("url", $populateCms); ?>">
                    </div>

                    <div class="form-group">
                      <label for="exampleInputPassword1">Page Title *</label>
                      <input type="text" class="form-control" name="page_title" id="page_title" value="<?php echo Input::getInput("page_title", $populateCms); ?>">
                    </div>




                    <div class="form-group">
                      <label for="exampleInputPassword1">Meta Keywords </label>
                      <textarea type="text" class="form-control" name="meta_keyword" id="meta_keyword"><?php echo Input::getInput("meta_keyword", $populateCms); ?></textarea>
                    </div>


                    <div class="form-group">
                      <label for="exampleInputPassword1">Meta Description </label>
                      <textarea type="text" class="form-control" name="meta_description" id="meta_description"><?php echo Input::getInput("meta_description", $populateCms); ?></textarea>
                    </div>


                    <div class="form-group">
                      <label for="exampleInputPassword1">Extra Tags </label>
                      <textarea type="text" class="form-control" name="extra_tags" id="extra_tags"><?php echo Input::getInput("extra_tags", $populateCms); ?></textarea>
                    </div>


                    <div class="form-group">
                      <label for="exampleInputPassword1">Header Image </label>

                      <input type="file" class="form-control" name="headerImage" id="headerImage">
                      <?php
                      if (isset($_GET["editId"])) {
                        $exstImage = Input::getInput("headerImage", $populateCms);
                        if ($exstImage != "") {
                          echo '<div class="thumb-image"><img src="' . $uploadDir . $exstImage . '" width="100"></div>';
                          echo '<div class="remove-image"><a href="Cms?rmvImg=yes&id=' . $_GET["editId"] . '&imgFld=headerImage&imgNme=' . base64_encode($exstImage) . '" onclick="return confirm(\'Are you sure you want to delete this CMS header image?\');" title="Remove"><i class="fa fa-trash fa-lg" aria-hidden="true"></i></a></div>';
                        }
                      }
                      ?>
                    </div>



                    <div class="form-group">
                      <label for="exampleInputPassword1">Page Content *</label>
                      <textarea type="text" class="form-control page_description" name="page_description" id="editor1"><?php echo Input::getInput("page_description", $populateCms); ?></textarea>
                    </div>


                    <div class="form-group">
                      <label>Display Link </label>

                      <select name="status" class="form-control col-md-7 col-xs-12" id="status"><?php echo Input::getSelected("status", $populateCms, array("1" => "Enable", "0" => "Disable")); ?>
                      </select>

                    </div>

                    <input type="hidden" name="cmsId" value="<?php echo Input::getInput("id", $populateCms); ?>">

                    <input type="hidden" name="exst_image" value="<?php echo Input::getInput("headerImage", $populateCms); ?>">

                    <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
                  </div>
                  <!-- /.box-body -->

                  <div class="box-footer">
                    <button type="submit" class="btn btn-primary" onclick="checkFields();return false;">Submit</button>
                  </div>
                </form>
              </div>
              <!-- /.box -->
            <?php } ?>



          </div>
          <!-- /.col -->



          <div class="col-md-12">
            <div class="box">
              <div class="box-header">
                <h3 class="box-title">Pages</h3>
              </div>
              <!-- /.box-header -->
              <div class="box-body">
                <table id="example1" class="table table-bordered table-striped">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>Location</th>
                      <th>Page Name</th>
                      <th>Page Url</th>
                      <th>Header Image</th>
                      <th>Creation Date</th>
                      <th>Edit</th>
                      <th>Delete</th>
                    </tr>
                  </thead>
                  <tbody>

                    <?php $cmss = Db::getInstance()->get_results("select content_manager.*,province.province from content_manager
LEFT JOIN province ON (province.id=content_manager.province_id) order by content_manager.id desc");
                    if (count($cmss)) {
                      foreach ($cmss as $cms) {

                        $date = new DateTime($cms["date_time"]);

                        echo '<tr>';
                        echo '<td>' . $cms["id"] . '</td>';

                        echo '<td>' . $cms["province"] . '</td>';
                        echo '<td>' . $cms["page_name"] . '</td>';
                        echo '<td>' . $cms["url"] . '</td>';
                        if ($cms["headerImage"] != "") {
                          echo '<td><img src="' . $uploadDir . $cms["headerImage"] . '" width="100" class="list-img"></td>';
                        } else {
                          echo '<td>&nbsp;</td>';
                        }
                        echo '<td>' . $date->format("Y-m-d") . '</td>';

                        echo '<td><a href="Cms?editId=' . $cms["id"] . '"> <i class="fa fa-pencil-square-o fa-lg" aria-hidden="true"></i></a> </td>';

                        echo '<td><a href="Cms?deleteId=' . $cms["id"] . '" onclick="return confirm(\'Are you sure you want to delete Page?\');"> <i class="fa fa-trash fa-lg" aria-hidden="true"></i></a> </td>';

                    ?>


                    <?php




                        echo '</tr>';
                      }
                    }


                    ?>


                  </tbody>

                </table>
              </div>
              <!-- /.box-body -->
            </div>

          </div>










        </div>





      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <?php include("includes/footer.php"); ?>


    <!-- Add the sidebar's background. This div must be placed
       immediately after the control sidebar -->
    <div class="control-sidebar-bg"></div>
  </div>
  <!-- ./wrapper -->




  <!-- jQuery 2.2.3 -->
  <script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
  <!-- Bootstrap 3.3.6 -->
  <script src="bootstrap/js/bootstrap.min.js"></script>
  <!-- Slimscroll -->
  <script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
  <!-- FastClick -->
  <script src="plugins/fastclick/fastclick.js"></script>
  <!-- AdminLTE App -->
  <script src="dist/js/app.min.js"></script>
  <!-- AdminLTE for demo purposes -->
  <script src="dist/js/demo.js"></script>
  <script src="plugins/datatables/jquery.dataTables.min.js"></script>
  <script src="plugins/datatables/dataTables.bootstrap.min.js"></script>

  <?php include("includes/inc-editor-js.php"); ?>

  <script>
    $(function() {
      $("#example1").DataTable({
        "order": [[0, "desc"]] // Sort by first column (index 0)
      });
    });

    function checkFields() {
      $("#error").hide();
      var page_name = $("#page_name").val();
      var url = $("#url").val();
      var page_title = $("#page_title").val();
      var page_description = CKEDITOR.instances.editor1.getData();

      if (page_name == "" || url == "" || page_title == "" || page_description == "") {

        $("#error").show();
        return false;
      }
      else {

        $("#form_").submit();

      }
    }
  </script>

</body>

</html>