<?php include_once('header.php'); ?>
<?php
  $action = '';
  $cat_id = '';
  if(isset($_GET['action']) && isset($_GET['cat_id'])){
    $action = $_GET['action'];
    $cat_id = $_GET['cat_id'];
  }
?>
<style type="text/css">
    .error{
        border-color: #ecbeb6;
        color: #b55351;
        text-transform: capitalize;
        text-align: left !important;
    }
    #error{
        width: 100%;
    }
    .alert{
        width: 100%;
        text-align: left;
    }
</style>
<div class="container">
  <div class="card-deck mb-3 text-center">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mt-3 mb-3 border-bottom" style="width: 100%;">
        <h1 class="h2">News Categories</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
          <div class="btn-group mr-2">
            <a class="btn btn-sm btn-outline-secondary" id="" href="news.php">News Posts</a>      
            <a class="btn btn-sm btn-outline-secondary" href="create-post.php">New Post</a>
          </div>
        </div>
      </div>

      <div id="error"></div>
      <!-- new user section -->

      <div class="row text-left">
        <div id="live_data" class="col-md-8"></div>
        <div class="col-md-4">
          <div id="err"></div>
          <?php if(!isset($_GET['action']) && !isset($_GET['cat_id'])){ ?>
          <h4 style="text-align: left;">Create New Category</h4><br>
          <form class="needs-validation" style="text-align: left;" id="create-user" method="post">
            <div class="row">
              <div class="col-md-12 mb-3">
                <label for="firstName" style="text-align:left; float:left">category name</label>
                <input type="text" class="form-control" id="category" name="category" required>
              </div>
              <div class="col-md-8 mb-3">
                <button class="btn btn-primary btn-md form-control" type="submit" name="create_category" id="create_category" style="float: left; margin-right: 5px;">
                   Create Category
                </button>
              </div>
              <div class="col-md-4 mb-3">
                <button class="btn btn-primary btn-md form-control" type="reset" name="reset" id="reset" style="float: left; margin-right: 5px;">
                   Clear
                </button>
              </div>
            </div>
          </form>

        <?php } elseif($action == 'edit_category'){
          $query = $con->getRows('blog_categories', array('where'=>'category_id="'.$cat_id.'"','return_type'=>'single'));

        ?>
        <h4 style="text-align: left;">Update Category</h4><br>
        <form class="needs-validation" style="text-align: left;" id="update-category" method="post">
          <div class="row">
            <div class="col-md-12 mb-3">
              <label for="firstName" style="text-align:left; float:left">category name</label>
              <input type="text" class="form-control" id="category" name="category" value="<?php echo $query['category'];  ?>" required>
            </div>
            <div class="col-md-8 mb-3">
              <input type="hidden" name="cat_id" value="<?php echo $cat_id; ?>" >
              <button class="btn btn-primary btn-md form-control" type="submit" name="update_category" id="update_category" style="float: left; margin-right: 5px;">
                 Update Category
              </button>
            </div>
          </div>
        </form>

      <?php } ?>
        </div>
      </div>
  </div>

</div>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script>window.jQuery || document.write('<script src="../../js/vendor/jquery-slim.min.js"><\/script>')</script>
    <script src="../../js/vendor/popper.min.js"></script>
    <script src="../../js/bootstrap.min.js"></script>
    <script src="../../js/vendor/holder.min.js"></script>
    <script type="text/javascript" src="../../js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="../../js/validation.min.js"></script>
    <script src="../../js/tables/jquery.dataTables.js"></script>
    <script src="../../js/tables/dataTables.bootstrap4.js"></script>

     <!--  summernote JS
        ============================================ -->
    <script src="../../js/summernote/summernote-updated.min.js"></script>
    <script src="../../js/summernote/summernote-active.js"></script>


        <script>
          (function($) {
          'use strict';
          $(function() {
            $('#order-listing').DataTable({
              "aLengthMenu": [
              [10, 20, 35, -1],
              [10, 20, 35, "All"]
              ],
              "iDisplayLength": 10
            });
          });
        })(jQuery);


        function fetchData(){
          $.ajax({
              url:"select-categories.php",
              method:"POST",
              success:function(data){
                   $('#live_data').html(data);
              }
             });
        }

        function clearData(id){
          $('#'+id)[0].reset();
        }
          $(document).ready(function(){

            //loads system users
            $.ajax({
              url:"select-categories.php",
              method:"POST",
              success:function(data){
                   $('#live_data').html(data);
              }
             });

            //Create a new category
           /* validation */
           $("#create-user").validate({
              rules:
            {
              category: {required: true}
             },
            messages:
             {
                    category: "Please enter category name.."

               },
             submitHandler: submitForm
               });
             /* validation */

             /* login submit */
             function submitForm()
             {
              var data = $("#create-user").serialize();

              $.ajax({

              type : 'POST',
              url  : 'sql_statements.php',
              data : data,
              beforeSend: function()
              {
                $("#err").fadeOut();
                $("#create_category").html('<i class="fa fa-spin fa-spinner"></i> Adding Category ...');
              },
              success :  function(response)
                 {  //alert(response);

                  //if the response returns true
                  if(response == 1){
                    $("#err").fadeIn(1000, function(){
                      $("#err").html('<div class="alert alert-success"> <button type="button" class="close" data-dismiss="alert">×</button><span class="icon icon-ok-circle"></span> A post category has been created!</div>');
                      });
                    //$("#")[0].reset();
                    $("#err").delay(6000).fadeOut(function(){});
                    //$("#create-user")[0].reset();
                    //$("#new-user").fadeOut(9000,function(){});
                    $("#create_category").html('Create Category');
                    clearData('create-user')
                    fetchData();

                  }
                  else if(response == 2){
                    $("#err").fadeIn(1000, function(){
                      $("#err").html('<div class="alert alert-warning"> <button type="button" class="close" data-dismiss="alert">×</button><span class="icon icon-lock"></span> There was an error creating a category, Please try again!</div>');
                    $("#create_category").html('Create Category');
                          });
                    $("#err").delay(6000).fadeOut(function(){});
                  }

                }
              });
                return false;
            }
             /* login submit */
          });

          //update a new category
         /* validation */
         $("#update-category").validate({
            rules:
          {
            category: {required: true}
           },
          messages:
           {
                  category: "Please enter category name.."

             },
           submitHandler: editCat
             });
           /* validation */

           /* login submit */
           function editCat()
           {
            var data = $("#update-category").serialize();

            $.ajax({

            type : 'POST',
            url  : 'sql_statements.php',
            data : data,
            beforeSend: function()
            {
              $("#err").fadeOut();
              $("#create_category").html('<i class="fa fa-spin fa-spinner"></i> Adding Category ...');
            },
            success :  function(response)
               {  alert(response);

                //if the response returns true
                if(response == 1){
                  $("#err").fadeIn(1000, function(){
                    $("#err").html('<div class="alert alert-success"> <button type="button" class="close" data-dismiss="alert">×</button><span class="icon icon-ok-circle"></span> A post category has been created! Clear the form to add a new category.</div>');
                    });
                  $("#err").delay(6000).fadeOut(function(){});
                  //$("#new-user").fadeOut(9000,function(){});
                  $("#create_category").html('Update Category');
                  fetchData();

                }
                else if(response == 2){
                  $("#err").fadeIn(1000, function(){
                    $("#err").html('<div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">×</button><span class="icon icon-lock"></span> There was an error creating a category, Please try again!</div>');
                  $("#create_category").html('Update Category');
                        });
                  $("#err").delay(6000).fadeOut(function(){});
                }

              }
            });
              return false;
          }


          //delete user details
          $(document).on('click', '.btn_delete', function(){
                 var id=$(this).data("id3");
                 var action="delete_category";
                 //alert(user+" "+id);
                 if(confirm("Are you sure you want to remove this category?"))
                 {
                      $.ajax({
                           url:"sql_statements.php",
                           method:"POST",
                           data:{cat_id:id, action:action},
                           dataType:"text",
                           success:function(data){
                                //alert(data);
                              if(data == 1){
                                  $("#error").fadeIn(2000, function(){
                                  $("#error").html('<div class="alert alert-success"> <button type="button" class="close" data-dismiss="alert">×</button><span class="icon icon-ok-circle"></span>&nbsp;A post category has been removed!</div>');
                          });//Your username/password entered doesn't match
                          $("#error").fadeOut(5000,function(){});
                                }
                                fetchData();
                           }
                      });
                 }
            });
          Holder.addTheme('thumb', {
            bg: '#55595c',
            fg: '#eceeef',
            text: 'Thumbnail'
          });

        </script>
  </body>
</html>
