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

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

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

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

    $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 = Db::getInstance();

    $max = $db->get_row("SELECT MAX(position) FROM banners WHERE cms_id='0'");

    $db->insert($mainTable, array(
      "banner_name" => $image,
      "description" => Input::getInput("description"),
      "cms_id" => '0',
      "position" => ($max[0] + 1)
    ));

    Session::flash("message", '<div class="alert-success" style="padding: 5px;">Banner Added.</div><br>');

    Redirect::to("Banners");

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

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

    $result = Db::getInstance()->update(
      $mainTable,
      array(
        "banner_name" => $image,
        "description" => Input::getInput("description"),
        "cms_id" => '0',
      ),
      array("id" => Input::getInput("bannerId"))
    );

    if ($result === true) {
      Session::flash("message", '<div class="alert-success" style="padding: 5px;">The banner data has been edited successfully.</div><br>');
    } elseif ($result === false) {
      Session::flash("message", '<div class="alert-error" style="padding: 5px;">The banner 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("Banners");
  } else {
    Session::flash("message", '<div class="alert-error" style="padding: 5px;">Please choose Banner.</div><br>');
    Redirect::to("Banners");
  }
}

/****************Edit Process Starts**********************/
$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("Banners");
  }
}
/****************Edit Process Ends**********************/

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

    Redirect::to("Banners");

  } else {
    Redirect::to("Banners");
  }
}
/****************Banner Delete Ends**********************/
?><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Banners - <?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">

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

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

      <div class="row">

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

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

          <a href="Banners?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="Banners" method="post" id="banner_form" enctype="multipart/form-data">
              <div class="box-body">
                <div class="alert-danger" style="padding: 5px;display: none;"  id="error">* Fields Are Required</div><br>


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


                </div>-->

                <div class="form-group">
                  <label for="exampleInputPassword1">Banner <?php if (!isset($_GET["editId"])) { echo '*'; } ?></label>
                  <input type="file"  class="form-control" name="banner"  id="banner" value="<?php echo Input::getInput("banner_name",$populateFields); ?>">
                  <?php
                  if (isset($_GET["editId"])) {
                    $exstImage = Input::getInput("banner_name", $populateFields);
                    if ($exstImage != "") {
                      echo '<div class="thumb-image"><img src="' . $uploadDir . $exstImage . '" width="100"></div>';
                    }
                  }
                  ?>
                </div>


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

                  <textarea class="form-control" name="description" id="editor2"><?php echo Input::getInput("description",$populateFields); ?></textarea>

                </div>

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

                <input type="hidden" name="exst_image" value="<?php echo Input::getInput("banner_name", $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" <?php if (!isset($_GET["editId"])) { echo '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">Banners</h3>
            </div>
            <!-- /.box-header -->
            <div class="box-body">
              <table id="example1" class="table table-bordered table-striped">
                <thead>
                <tr>
                  <th>ID</th>
                  <th>Banner</th>
                  <th>Position</th>
                  <th>Creation Date</th>
                  <th>Edit</th>
                  <th>Delete</th>
                </tr>
                </thead>
                <tbody>

                <?php $banners=Db::getInstance()->get_results("select * from {$mainTable} order by id desc");
                if(count($banners)) {
                  foreach ($banners as $banner) {

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

                    echo '<tr>';
                    echo '<td>' . $banner["id"] . '</td>';
                    echo '<td><img src="' . $uploadDir . $banner["banner_name"] . '" width="100" class="list-img"></td>';

                    echo '<td><input type="text" value="'.$banner["position"].'" size="1" style="padding:5px;marging-left:5px;" onchange="updatePosition('.$banner["id"].');" id="'.$banner["id"].'"></td>';

                    echo '<td>' . $date->format("Y-m-d") . '</td>';
                    echo '<td><a href="Banners?editId='.$banner["id"].'"> <i class="fa fa-pencil-square-o fa-lg" aria-hidden="true"></i></a> </td>';
                    echo '<td><a href="Banners?deleteId='.$banner["id"].'" onclick="return confirm(\'Are you sure you want to delete Banner?\');"> <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 banner=$("#banner").val();

    if(banner=="")
    {

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

    else{

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

    }
  }

  function updatePosition(id)
  {
    var position=$("#"+id).val();
    $.post("requestHandler",{bannerId:id,position:position});
  }
</script>


</body>
</html>
