<?php
include("core/init.php");
include("session.php");
    if(!Session::exists("filterQuery")) {
      Session::put("filterQuery", '');
    }



/****************Delete All Action***********/
    if(isset($_POST["scheduleDelId"]) && count($_POST["scheduleDelId"])) {

      foreach ($_POST["scheduleDelId"] as $scheduleId)
      {
        //echo $scheduleId;
        Db::getInstance()->delete("schedule",array("id"=>$scheduleId));
      }

      Session::flash("message",'<div class="alert-success" style="padding: 5px;">Schedule Deleted.</div><Br>');
      Redirect::to("Schedule");
    }

/*****************************************/




/****************Search Filter Start Here***********/
if(isset($_POST["filter_month"]) && isset($_POST["filter_province"]))
{
  Session::delete("Sfilter_province");
  Session::delete("filter_month");
  $filterQuery="";
  $filterQuery .= 'WHERE ';
  if(Input::getInput("filter_month")!="" && Input::getInput("filter_province")=="") {
    Session::put("filter_month",Input::getInput("filter_month"));

    $filterQuery .= " schedule.month= '".Input::getInput("filter_month")."'";

        }

  else if(Input::getInput("filter_month")=="" && Input::getInput("filter_province")!="") {
    Session::put("Sfilter_province",Input::getInput("filter_province"));

    $filterQuery .= " province.id= '".Input::getInput("filter_province")."'";

  }


  else if(Input::getInput("filter_month")!="" && Input::getInput("filter_province")!="") {
    Session::put("filter_month",Input::getInput("filter_month"));
    Session::put("Sfilter_province",Input::getInput("filter_province"));


    $filterQuery .= " schedule.month= '".Input::getInput("filter_month")."'";
    $filterQuery .=" AND ";
    $filterQuery .= " province.id= '".Input::getInput("filter_province")."'";
  }


            else{
            $filterQuery="";
        }


  Session::put("filterQuery",$filterQuery);

}

/***********Table Used**********/
$mainTable="schedule";

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

if(Input::exists() && Token::check(Input::getInput("token"))) {


 // print_r($_POST);exit;

  if(Input::getInput("scheduleId")=="")
  {
    Db::getInstance()->insert($mainTable,array("date"=>addslashes(Input::getInput("date")),
        "description"=>addslashes(Input::getInput("description")),
        "time"=>addslashes(Input::getInput("time")),
        "package_id"=>Input::getInput("package_id"),
        "month"=>addslashes(Input::getInput("month")),
        "year"=>addslashes(Input::getInput("year"))));
    $lastInsertId=Db::getInstance()->lastid();

      Session::put("month",addslashes(Input::getInput("month")));
    foreach($_POST["province_id"] as $provinceId)
    {
      Db::getInstance()->insert("schedule_province",array("schedule_id"=>$lastInsertId,
          "province_id"=>$provinceId));
    }



    Session::flash("message",'<div class="alert-success" style="padding: 5px;">Schedule Added.</div><Br>');
    Redirect::to("Schedule");
  }


  else if(Input::getInput("scheduleId")!="" && Input::getInput("safe_submit")=="yes")
  {
      Db::getInstance()->insert($mainTable,
          array( "date"=>addslashes(Input::getInput("date")),
              "description"=>addslashes(Input::getInput("description")),
              "time"=>addslashes(Input::getInput("time")),
              "package_id"=>Input::getInput("package_id"),
              "month"=>addslashes(Input::getInput("month")),
              "year"=>addslashes(Input::getInput("year")))
      );
      $lastInsertId=Db::getInstance()->lastid();

      foreach($_POST["province_id"] as $provinceId)
      {
          Db::getInstance()->insert("schedule_province",array("schedule_id"=>$lastInsertId,
              "province_id"=>$provinceId));
          Db::getInstance()->delete("schedule_province",array("schedule_id"=>Input::getInput("scheduleId"),
              "province_id"=>$provinceId));

      }

      Session::flash("message",'<div class="alert-success" style="padding: 5px;">Schedule Edited Successfully.</div><Br>');
      Redirect::to("Schedule");
  }


  else if(Input::getInput("scheduleId")!="" )
  {
    Db::getInstance()->update($mainTable,
        array( "date"=>addslashes(Input::getInput("date")),
            "description"=>addslashes(Input::getInput("description")),
            "time"=>addslashes(Input::getInput("time")),
            "package_id"=>Input::getInput("package_id"),
            "month"=>addslashes(Input::getInput("month")),
            "year"=>addslashes(Input::getInput("year"))),
        array("id"=>Input::getInput("scheduleId"))

    );


    Db::getInstance()->delete("schedule_province",array("schedule_id"=>Input::getInput("scheduleId")));

    foreach($_POST["province_id"] as $provinceId)
    {
      Db::getInstance()->insert("schedule_province",array("schedule_id"=>Input::getInput("scheduleId"),
          "province_id"=>$provinceId));
    }

    Session::flash("message",'<div class="alert-success" style="padding: 5px;">Schedule Edited Successfully.</div><Br>');
    Redirect::to("Schedule");
  }





  else {
    Session::flash("message",'<div class="alert-error" style="padding: 5px;">Please Fill Category.</div><Br>');
    Redirect::to("Schedule");
  }


}
/****************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("Schedule");
  }
}
/**************** Edit Populate Ends**********************/





/****************Delete**********************/


if(Input::particularInputExists("get","deleteId")) {

  if (Db::getInstance()->num_rows("select id from {$mainTable} where id='" . Input::getInput("deleteId") . "'") > 0) {
    Db::getInstance()->delete($mainTable,array("id"=>Input::getInput("deleteId")));

    Session::flash("message",'<div class="alert-success" style="padding: 5px;">Schedule Deleted.</div><Br>');
    Redirect::to("Schedule");

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

/****************Delete Ends**********************/



?><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Schedule - <?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="plugins/datepicker/datepicker3.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="plugins/select2/select2.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>
    .select2-selection__choice{background-color:#367FA9 !important;};
    #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>
        Schedule
        <small></small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="Dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active">Schedule</li>
      </ol>
    </section>

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

      <div class="row">


        <div class="col-md-12">
          
          <?php  echo  Session::flashDisplay("message");  ?>

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


          $populateLocation=null;

          $locationArray=null;
          if(Input::particularInputExists("get","editId"))
          {
            $resultArrays=Db::getInstance()->get_results("select schedule_id,province_id  from schedule_province where schedule_id='".Input::getInput("editId")."'");

            foreach($resultArrays as $resultArray)
            {
              $locationArray[$resultArray["province_id"]]=$resultArray["province_id"];
            }


          }



          $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"];
          }
          $monthArray=array(
              "1"=>"Jan",
              "2"=>"Feb",
              "3"=>"Mar",
              "4"=>"Apr",
              "5"=>"May",
              "6"=>"Jun",
              "7"=>"Jul",
              "8"=>"Aug",
              "9"=>"Sep",
              "10"=>"Oct",
              "11"=>"Nov",
              "12"=>"Dec");
              
              
        /* $yearArray=array(
                  "2019"=>"2019",
              "2020"=>"2020",
              "2021"=>"2021"
              ); */      

          $yearArray=array(
              "2021"=>"2021",
              "2022"=>"2022",
              "2023"=>"2023",
              "2024"=>"2024",
              "2025"=>"2025",
              "2026"=>"2026",
              "2027"=>"2027",
              "2028"=>"2028"
              );

          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="Schedule" method="post" id="scheduleForm">
              <div class="box-body">
                <div class="alert-error" style="padding: 5px; display: none;" id="error">Please Fill All The Fields.</div>
                


                <div class="form-group">
                  <label for="exampleInputPassword1">Select Location *</label>
                  <select name="province_id[]" class="form-control " id="province" multiple  >
                    <?php echo Input::getMultiSelected("province_id",$locationArray,$provinces); ?>
                  </select>
                  
                 <input type="checkbox" id="checkbox" >Select All

                </div>





                <?php

                $dbPackages=Db::getInstance()->get_results("select id,package_name from packages");
                $packages=array();
                if(count($dbPackages)) foreach($dbPackages as $dbPackage)
                {
                  $packages[$dbPackage["id"]]=$dbPackage["package_name"];
                }

                ?>


                <div class="form-group" style="display: none;">
                  <label for="exampleInputPassword1">Select Package To Redirect *</label>
                  <select name="package_id" class="form-control">
                    <?php echo Input::getSelected("package_id",$populateFields,$packages); ?>
                  </select>


                </div>









                <div class="form-group">

                  <label for="exampleInputPassword1">Date *</label>
                  <!--<div class="input-group date">-->
                    <!--<div class="input-group-addon">
                      <i class="fa fa-calendar"></i>
                    </div>-->
                    <input type="text" class="form-control" id="datepicker" value="<?php echo Input::getInput("date",$populateFields); ?>" name="date">
                  <!--</div>-->
                </div>





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


                </div>





                <div class="form-group">
                  <label for="exampleInputPassword1">Time *</label>
                 <!-- <div class="input-group date">-->
                    <!--<div class="input-group-addon">
                      <i class="fa fa-clock-o"></i>
                    </div>-->
                    <input type="text" class="form-control" value="<?php echo Input::getInput("time",$populateFields); ?>" name="time" id="time">
                  <!--</div>-->
                </div>





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


                </div>


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


                  </div>



                <input type="hidden" name="scheduleId" value="<?php echo Input::getInput("id",$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('false'); return false;">Save</button>
                  <?php if(Input::particularInputExists("get","editId")){ ?>
                  <button type="submit" class="btn btn-warning" onclick="checkFields('true'); return false;">Overwrite</button> <?php } ?>

              </div>
            </form>
          </div>
          <!-- /.box -->

          <?php } ?>


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






        <div class="col-md-12">
          <div class="box">
            <div class="box-header">
              <h3 class="box-title">Schedule</h3>
              <div class="col-md-12 col-md-offset-3">
<?php
$newMonthArray=array(""=>"All Months");
$monthArray=$newMonthArray+$monthArray;
$newProvinceArray=array(""=>"All Locations");
$provinces=$newProvinceArray+$provinces;


?>
                <form id="_filterform" action="schedule" method="post">
                <div class="col-md-3">
                  <select name="filter_province" class="form-control">
                    <?php echo Input::getSelected("filter_province",Session::get("Sfilter_province"),$provinces); ?>
                  </select>
                </div>
                <div class="col-md-3">
              <select name="filter_month" class="form-control">
                <?php echo Input::getSelected("filter_month",Session::get("filter_month"),$monthArray); ?>
              </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">
              <form action="schedule" method="POST" id="_deleteForm">
              <table id="example1" class="table table-bordered table-striped">

                <thead>
                <tr>
                    <Th>No.</Th>
                  <?php if(Session::exists("filter_month") && Session::exists("Sfilter_province"))
                  { ?><th ><label><input type="checkbox" id="checkAll"/> Check all</label></th><?php } ?>
                  <th>Schedule Date</th>
                  <th>Month</th>
                    <th>Year</th>
                  <th>Schedule Time</th>
                  <th>Location</th>
                  <th>Position</th>
                  <th>Creation Date</th>
                  <th>Edit</th>
                  <th>Delete</th>
                  <th>Status</th>
                </tr>
                </thead>
                <tbody>


                <?php $sno=1; $q="select schedule.*,GROUP_CONCAT(province.province SEPARATOR ',') as province,packages.package_name from {$mainTable}
                JOIN schedule_province ON (schedule_province.schedule_id=schedule.id)
                JOIN province ON (province.id=schedule_province.province_id)
                LEFT JOIN packages ON (schedule.package_id=packages.id)  ".Session::get("filterQuery") ." GROUP BY schedule.id ORDER BY schedule.date_time DESC";

                $dbFields=Db::getInstance()->get_results($q);
                $sno=1;
                if(count($dbFields)) {
                  foreach ($dbFields as $dbField) {

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

                    echo '<tr>';
                      echo "<td>$sno</td>";
                    if(Session::exists("filter_month") && Session::exists("Sfilter_province")) {
                      echo '<Td><input type="checkbox" name="scheduleDelId[]" value="'.$dbField["id"].'"></Td>';
                    }
                      echo '<Td>' . $dbField["date"] . '</Td>';
                    echo '<td>'.date('F', mktime(0, 0, 0, $dbField["month"], 10)).'</td>';
                      echo '<Td>' . $dbField["year"] . '</Td>';
                    echo '<Td>' . $dbField["time"] . '</Td>';
                    echo '<Td>' . $dbField["province"] . '</Td>';

                 
                    if(Session::exists("filter_month") && Session::exists("Sfilter_province"))
                    {echo '<Td><span class="hide">'.$dbField["id"].'</span><input type="text" id="position'.$dbField["id"].'" value="'.$dbField["position"].'" size="2" style="margin-left:10px;" onchange="updatePosition('.$dbField["id"].');" > </Td>';}
                    else{
                      echo '<Td>&nbsp;</Td>';
                    }


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

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

                   /* echo '<Td><A href="Schedule?deleteId='.$dbField["id"].'" onclick="return confirm(\'Are you sure you want to delete Schedule?\');"> <i class="fa fa-trash fa-lg" aria-hidden="true"></i></A> </Td>';*/ ?>
                <Td><A  onclick="loadLinkedLocations(<?php echo $dbField["id"]; ?>);return false;" href="#"> <i class="fa fa-trash fa-lg" aria-hidden="true"></i></A> </Td>


                   <?php  if($dbField["status"]==0) {
                      echo '<Td><A href="#" onclick="updateStatus(' . $dbField["id"] . '); return false;" ><i class="fa fa-remove fa-lg text-danger" id="icon' . $dbField["id"] . '"></i></A></Td>';
                    }
                    else {

                      echo '<Td><A href="#" onclick="updateStatus(' . $dbField["id"] . ');return false;" ><i class="fa fa-check fa-lg text-success" id="icon' . $dbField["id"] . '"></i></A></Td>';

                    }

 echo '</tr>';

                    $sno++;

                  }
                }


                ?>


                </tbody>
                <?php if(Session::exists("filter_month") && Session::exists("Sfilter_province"))
                { ?><tfoot>
                <Tr><Td><input  type="submit" class="btn btn-primary" value="Delete Selected" onclick="submitDelete();return false;">

                  </Td></Tr>
                </tfoot>
<?php } ?>

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

        </div>





        <div class="modal fade" id="myModal" role="dialog">

            <div class="modal-dialog">


            <!-- Modal content-->
            <div class="modal-content">
              <div class="modal-header">
                  <h5 class="alert alert-danger">Warning: Please Select Multiple Locations To Delete The Schedule. </h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>

              </div>
              <div class="modal-body">
                <div class="table-responsive">
                  <Table class="table" id="linkedLocationTable">

                  </Table>
                </div>


              </div>
              <div class="modal-footer">
                 <button type="submit" class="btn btn-danger pull-left" onclick="deleteLinkedLocations();return false;"><span class="glyphicon glyphicon-remove" ></span> Delete Selected</button>
                <button type="submit" class="btn btn-default btn-default pull-right" data-dismiss="modal"> Cancel</button>

              </div>
            </div>
          </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="plugins/datepicker/bootstrap-datepicker.js"></script>
<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 src="plugins/select2/select2.min.js"></script>

<script>
  $(function () {
    $("#checkAll").change(function () {
      $("input:checkbox").prop('checked', $(this).prop("checked"));
    });
$("#province").select2();
    $("#example1").DataTable();
    $('#example2').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": true,
      "info": true,
      "autoWidth": false
    });


  });

  function checkFields(safesubmit)
  {
      //alert(safesubmit);
      //return false;
    var province=$("#province").val();
    var formdate=$("#datepicker").val();
    var description=$("#description").val();
    var formtime=$("#time").val();

   // alert(province);return false;
   // alert(formdate + " " + description + " " + formtime);return false;
    if(formdate=="" || description=="" || formtime=="" || province==null)
    {
      $("#error").show();
      return false;

    }
    else{
        if(safesubmit=="true")
        {
            $("#scheduleForm").append("<input type='hidden' name='safe_submit' value='yes'>");
        }
      $("#scheduleForm").submit();
      return true;
    }
  }








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

  function submitDelete()
  {
    var confirmDelete=confirm("Are You Sure? Action Cant Be Undo.");
    if(confirmDelete==true) {
      $("#_deleteForm").submit();
      return true;
    }

      return false;

    }

  function updateStatus(id)
  {


    $.post("requestHandler",{scheduleId:id}).
    done(function(data){


      $("#icon"+id).removeClass();
      $("#icon"+id).addClass(data);



    });



  }


 function updatePosition(id)
  {

    position=$("#position"+id).val();

    $.post("requestHandler",{updatePositionId:id,
      position:position})



  }
  
 $("#checkbox").click(function(){
    if($("#checkbox").is(':checked') ){
        $("#province > option").prop("selected","selected");
        $("#province").trigger("change");
    }else{
        $("#province > option").removeAttr("selected");
         $("#province").trigger("change");
     }
});


  function loadLinkedLocations(id)
  {

    $.post("requestHandler",{linkedScheduleId:id}).done(function (data) {
      $("#linkedLocationTable").html(data);
      $("#myModal").modal();
    });
  }

  function deleteLinkedLocations()
  {
    var locationArray=[];
    $('input[name="linkedLocations"]:checked').each(function() {
      locationArray.push(this.value);
    });
    if(locationArray.length!=0) {
      $.post("requestHandler", {deleteLocationIds: locationArray.toString()}).done(function (data) {
        location.reload();
      });
    }
  }

</script>


</body>
</html>
