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

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

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

  //  print_r($_POST);exit;

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

      $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(
      "category" => Input::getInput("category"),
      "description" => Input::getInput("description"),
      "type" => Input::getInput("type"),
      "subtitle" => Input::getInput("subtitle"),
      "image" => $image,
      "c_order" => Input::getInput("c_order") > 0 ? Input::getInput("c_order") : 0
    ));
    Session::flash("message", '<div class="alert-success" style="padding: 5px;">Category Added.</div><br>');
    Redirect::to("Categories");
  } else if (Input::getInput("categoryId") != "" && Input::getInput("category") != "" && Input::getInput("type") != "") {
    $exst_image = "";
    if (Input::getInput("exst_image") != "") {
      $exst_image = Input::getInput("exst_image");
      $image = $exst_image;
    }
    else{
      $image = "";
    }
    // New upload
    if ( isset($_FILES['image']) && $_FILES['image']['error'] !== UPLOAD_ERR_NO_FILE && is_uploaded_file($_FILES['image']['tmp_name']) ) {
      $uploader = new FileUpload(rtrim($uploadDir, "/"), [
        'type' => ['jpg,jpeg,png,gif'],
        'size' => 2, // In MB
      ], $_FILES['image']);

      $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("Categories?editId='" . Input::getInput("categoryId"));
      }
    }

    $result = Db::getInstance()->update(
      $mainTable,
      array(
        "category" => Input::getInput("category"),
        "description" => Input::getInput("description"),
        "type" => Input::getInput("type"),
        "subtitle" => Input::getInput("subtitle"),
        "image" => $image,
        "c_order" => Input::getInput("c_order") > 0 ? Input::getInput("c_order") : 0
      ),
      array("id" => Input::getInput("categoryId"))

    );

    if ($result === true) {
      Session::flash("message", '<div class="alert-success" style="padding: 5px;">The category data has been edited successfully.</div><br>');
    } elseif ($result === false) {
      Session::flash("message", '<div class="alert-error" style="padding: 5px;">The category data was not edited successfully.</div><br>');
    } elseif ($result === 0) {
      Session::flash("message", '<div class="alert-info" style="padding: 5px;">No rows were updated, possibly because the values were already up to date. No further action is required.</div><br>');
    }

    Redirect::to("Categories");
  } else {
    Session::flash("message", '<div class="alert-error" style="padding: 5px;">Please fill Type and Category.</div><br>');
    Redirect::to("Categories");
  }
}
/****************Add & Edit Process Starts Here**********************/

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

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

    Redirect::to("Categories");
  }
}
/****************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 image from {$mainTable} where id='" . Input::getInput("deleteId") . "'");
    $exstImage = Input::getInput("image", $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 category data has been deleted successfully.</div><br>');
    } elseif ($result === false) {
      Session::flash("message", '<div class="alert-error" style="padding: 5px;">The category data was not deleted successfully.</div><br>');
    }

    Redirect::to("Categories");
  } else {
    Redirect::to("Categories");
  }
}

/****************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(
          "image" => ""
        ),
        array("id" => Input::getInput("id"))
      );

      if ($result === true) {
        Session::flash("message", '<div class="alert-success" style="padding: 5px;">The category image has been deleted successfully.</div><br>');
      } elseif ($result === false) {
        Session::flash("message", '<div class="alert-error" style="padding: 5px;">The category 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("Categories");
    } 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("Categories");
    }
  }
}

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

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Categories - <?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">
  <!-- 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">
  <!-- 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>
          Categories
          <small></small>
        </h1>
        <ol class="breadcrumb">
          <li><a href="Dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
          <li class="active">Categories</li>
        </ol>
      </section>

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

        <div class="row">

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

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

            <a href="Categories?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="Categories" method="post" enctype="multipart/form-data" id="form_">
                  <div class="box-body">

                    <div class="alert-danger" style="padding: 5px;display: none;" id="error">* Fields Required.</div>

                    <div class="form-group">
                      <label for="type">Type *</label>
                      <select name="type" id="type" class="form-control">
                        <?php echo Input::getSelected("type", $populateFields, ['' => '--please select--', 'general' => 'General', 'private' => 'Private']); ?>
                      </select>
                    </div>

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

                    <div class="form-group">
                      <label for="subtitle">Subtitle</label>
                      <input type="text" class="form-control" name="subtitle" id="subtitle" value="<?php echo Input::getInput("subtitle", $populateFields); ?>">
                    </div>

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

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

                    <div class="form-group">
                      <label for="c_order">Order</label>
                      <input type="number" min="1" class="form-control" name="c_order" id="c_order" value="<?php echo Input::getInput("c_order", $populateFields) > 0 ? Input::getInput("c_order", $populateFields) : ''; ?>">
                    </div>

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

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

                    <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">Categories</h3>
              </div>
              <!-- /.box-header -->
              <div class="box-body">
                <table id="example1" class="table table-bordered table-striped">
                  <thead>
                    <tr>
                      <th>No.</th>
                      <th>Category</th>
                      <th>Type</th>
                      <th>Subtitle</th>
                      <th>Image</th>
                      <th>Order</th>
                      <th>Creation Date</th>
                      <th>Edit</th>
                      <th>Delete</th>
                    </tr>
                  </thead>
                  <tbody>

                    <?php $dbFields = Db::getInstance()->get_results("select * from {$mainTable} ORDER BY id DESC");
                    $sno = 1;
                    if (count($dbFields)) {
                      foreach ($dbFields as $dbField) {

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

                        echo '<tr>';
                        echo '<td>' . $sno . '</td>';
                        echo '<td>' . $dbField["category"] . '</td>';
                        echo '<td>' . ucfirst($dbField["type"]) . '</td>';
                        echo '<td>' . $dbField["subtitle"] . '</td>';
                        if ($dbField["image"] != "") {
                          echo '<td><img src="' . $uploadDir . $dbField["image"] . '" width="100" class="list-img"></td>';
                        } else {
                          echo '<td>&nbsp;</td>';
                        }
                        if ($dbField["c_order"] > 0) {
                          echo '<td>'.$dbField["c_order"].'</td>';
                        } else {
                          echo '<td>&nbsp;</td>';
                        }

                        echo '<td>' . $date->format("Y-m-d") . '</td>';

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

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

                    ?>


                    <?php




                        echo '</tr>';

                        $sno++;
                      }
                    }


                    ?>


                  </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>

  <script>
    $(function() {
      $("#example1").DataTable();
      $('#example2').DataTable({
        "paging": true,
        "lengthChange": false,
        "searching": false,
        "ordering": true,
        "info": true,
        "autoWidth": false
      });
    });

    function checkFields() {
      $("#error").hide();
      var type = $("#type").val();
      var category = $("#category").val();
      if (type == "" || category == "") {
        $("#error").show();
        return false;
      }
      else {
        $("#form_").submit();
      }
    }
  </script>


</body>

</html>