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

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

/****************Search Filter Start Here***********/
if (!Session::exists("packageFilterQuery")) {
  Session::put("packageFilterQuery", '');
}
if (isset($_POST["filter_province"])) {
  Session::delete("Pfilter_province");

  $filterQuery = "";
  $filterQuery .= 'WHERE ';
  if (Input::getInput("filter_province") != "") {
    Session::put("Pfilter_province", Input::getInput("filter_province"));

    $filterQuery .= " province.id= '" . Input::getInput("filter_province") . "'";
  } else {
    $filterQuery = "";
  }
  Session::put("packageFilterQuery", $filterQuery);
}

/****************Add & Edit Process Starts Here**********************/

if ($_SERVER['REQUEST_METHOD'] === 'POST' && Input::exists() && Token::check(Input::getInput("token"))) {

  if (Input::getInput("packageId") == "" && Input::getInput("package_name") != "" && Input::getInput("price") != "") {
    $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(
      "province_id" => Input::getInput("province_id"),
      "category_id" => Input::getInput("category_id"),
      "package_name" => Input::getInput("package_name"),
      "description" => addslashes(Input::getInput("description")),
      "image" => $image,
      "price" => Input::getInput("price"),
      "mto_fee" => Input::getInput("mto_fee"),
      "hst" => Input::getInput("hst"),
      "display_package" => Input::getInput("display_package"),
      "offer_price" => Input::getInput("offer_price"),
      "icon_class_name" => Input::getInput("icon_class_name"),
      "c_order" => Input::getInput("c_order") > 0 ? Input::getInput("c_order") : 0
    ));
    Session::flash("message", '<div class="alert-success" style="padding: 5px;">Package Added.</div><br>');
    Redirect::to("Packages");
  } else if (Input::getInput("packageId") != "" && Input::getInput("package_name") != "" && Input::getInput("price") != "") {
    $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("Packages?editId='" . Input::getInput("packageId"));
      }
    }

    $result = Db::getInstance()->update(
      $mainTable,
      array(
        "province_id" => Input::getInput("province_id"),
        "category_id" => Input::getInput("category_id"),
        "package_name" => Input::getInput("package_name"),
        "description" => addslashes(Input::getInput("description")),
        "image" => $image,
        "price" => Input::getInput("price"),
        "mto_fee" => Input::getInput("mto_fee"),
        "hst" => Input::getInput("hst"),
        "display_package" => Input::getInput("display_package"),
        "offer_price" => Input::getInput("offer_price"),
        "icon_class_name" => Input::getInput("icon_class_name"),
        "c_order" => Input::getInput("c_order") > 0 ? Input::getInput("c_order") : 0
      ),
      array("id" => Input::getInput("packageId"))
    );

    if ($result === true) {
      Session::flash("message", '<div class="alert-success" style="padding: 5px;">The package data has been edited successfully.</div><br>');
    } elseif ($result === false) {
      Session::flash("message", '<div class="alert-error" style="padding: 5px;">The package 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("Packages");
  } else {
    Session::flash("message", '<div class="alert-error" style="padding: 5px;">Please fill Package Name & Price.</div><br>');
    Redirect::to("Packages?editId='" . Input::getInput("packageId"));
  }
}
/****************Add & Edit Process End 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("Packages");
  }
}
/****************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 package data has been deleted successfully.</div><br>');
    } elseif ($result === false) {
      Session::flash("message", '<div class="alert-error" style="padding: 5px;">The package data was not deleted successfully.</div><br>');
    }

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

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

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

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Packages - <?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">
  <link rel="stylesheet" href="css/dev.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]-->

</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>
          Packages
          <small></small>
        </h1>
        <ol class="breadcrumb">
          <li><a href="Dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
          <li class="active">Packages</li>
        </ol>
      </section>

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

        <div class="row">

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

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

            <a href="Packages?addNew" class="btn btn-primary" style="margin-bottom: 10px;">Add New</a>

            <?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"];
            }

            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="Packages" 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="exampleInputPassword1">Select Location *</label>
                      <select name="province_id" class="form-control">
                        <?php echo Input::getSelected("province_id", $populateFields, $provinces); ?>
                      </select>
                    </div>

                    <?php
                    $dbCategories = Db::getInstance()->get_results("select id,category from categories");

                    $categories = array();
                    if (count($dbCategories)) foreach ($dbCategories as $dbCategory) {
                      $categories[$dbCategory["id"]] = $dbCategory["category"];
                    }
                    ?>

                    <div class="form-group">
                      <label for="exampleInputPassword1">Select Category *</label>
                      <select name="category_id" class="form-control">
                        <?php echo Input::getSelected("category_id", $populateFields, $categories); ?>
                      </select>
                    </div>

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

                    <div class="form-group">
                      <label for="exampleInputPassword1">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="exampleInputPassword1">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="Packages?rmvImg=yes&id='.$_GET["editId"].'&imgFld=image&imgNme=' .base64_encode($exstImage) . '" onclick="return confirm(\'Are you sure you want to delete this package image?\');" title="Remove"><i class="fa fa-trash fa-lg" aria-hidden="true"></i></a></div>';
                        }
                      }
                      ?>
                    </div>

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

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

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

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

                    <div class="form-group">
                      <label for="icon_class_name">Icon Class Name</label>
                      <input type="text" class="form-control" name="icon_class_name" id="icon_class_name" value="<?php echo Input::getInput("icon_class_name", $populateFields); ?>">
                    </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>

                    <div class="form-group">
                      <label>Display Bigger *</label>
                      <select name="display_package" class="form-control col-md-7 col-xs-12" id="display_package"><?php echo Input::getSelected("display_package", $populateFields, array("0" => "Disable", "1" => "Enable")); ?>
                      </select>
                    </div>

                    <input type="hidden" name="packageId" 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">Packages</h3>

                <div class="col-md-12 col-md-offset-3">
                  <?php

                  $newProvinceArray = array("" => "All Locations");
                  $provinces = $newProvinceArray + $provinces;


                  ?>
                  <form id="_filterform" action="Packages" method="post">
                    <div class="col-md-3">
                      <select name="filter_province" class="form-control">
                        <?php echo Input::getSelected("filter_province", Session::get("Pfilter_province"), $provinces); ?>
                      </select>
                    </div>

                    <div class="col-md-3">
                      <button type="submit" class="btn btn-primary" onclick="filterResults();">Filter</button>
                    </div>

                  </form>
                </div>



              </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>Category</th>
                      <th>Package Name</th>
                      <th>Offer Price</th>
                      <th>Price</th>
                      <th>Image</th>
                      <th>Display Bigger</th>
                      <th>Order</th>
                      <th>Creation Date</th>
                      <th>Edit</th>
                      <th>Delete</th>
                    </tr>
                  </thead>
                  <tbody>

                    <?php
                    $dbFields = Db::getInstance()->get_results(
                      "SELECT " . $mainTable . ".*, categories.category, province.province FROM {$mainTable}
                JOIN province ON (province.id=packages.province_id)
                JOIN categories ON (categories.id=packages.category_id)
                " . Session::get("packageFilterQuery") .
                        "ORDER BY packages.id DESC"
                    );
                    if (count($dbFields)) {
                      foreach ($dbFields as $dbField) {

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

                        echo '<tr>';
                        echo '<td>' . $dbField["id"] . '</td>';
                        echo '<td>' . $dbField["province"] . '</td>';
                        echo '<td>' . $dbField["category"] . '</td>';
                        echo '<td>' . $dbField["package_name"] . '</td>';
                        if ($dbField["offer_price"] > 0) {
                          echo '<td>' . $dbField["offer_price"] . '</td>';
                        } else {
                          echo '<td>&nbsp;</td>';
                        }
                        echo '<td>' . $dbField["price"] . '</td>';
                        if ($dbField["image"] != "") {
                          echo '<td><img src="' . $uploadDir . $dbField["image"] . '" width="100" class="list-img"></td>';
                        } else {
                          echo '<td>&nbsp;</td>';
                        }
                        if ($dbField["display_package"] > 0 && $dbField["display_package"] == 1) {
                          echo '<td>Enable</td>';
                        } else {
                          echo '<td>Disable</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="Packages?editId=' . $dbField["id"] . '"> <i class="fa fa-pencil-square-o fa-lg" aria-hidden="true"></i></a> </td>';

                        echo '<td><a href="Packages?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>';
                      }
                    }


                    ?>


                  </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({
        "order": [[0, "desc"]] // Sort by first column (index 0)
      });
    });

    function filterResults() {
      $("#_filterform").submit();
      return true;
    }

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


</body>

</html>