<?php

session_start();
include ('connect.php');

if(empty($_SESSION['user_login'])){

	header("Location: login.php");
}else{

  $start = 0 ;
  $limite = 50;
  $pageNow = 1;

  if(isset($_GET['page'])){
    if($_GET['page'] == 1){

      $start = 0 ;
      $pageNow = 1;

    }else{
      $start = ($_GET['page']-1)* $limite;
      $limite = 50;
      $pageNow = $_GET['page'];
    }
  }
  $filterby ="";
  $addUrl ="";

  if(isset($_GET['filterbydate'])){
    $date = explode("-",$_GET['filterbydate']);
    $startDate = date('Y-m-d',strtotime($date[0]));
    $endDate = date('Y-m-d',strtotime($date[1]));

    $filterby = "and request_date >= '$startDate' and request_date <= '$endDate'";

    $addUrl = "&filterbydate=".$_GET['filterbydate'];
    
  }

  // $inicio = ($pg * $limite) - $limite;


  $sql = "SELECT * FROM  requests WHERE span_status = '0' and delete_status=0 $filterby order by id desc limit $start,$limite";
	  
  $result = mysqli_query($conn,$sql);


  $sql = "SELECT count(id) as total FROM  requests WHERE span_status = '0' and delete_status=0 $filterby";     
  $total = mysqli_query($conn,$sql);
  $totalRes = mysqli_fetch_assoc($total);

	
}

if (!empty($_POST["spanRequests"])) {
  $sql = "update requests set span_status = '1' where id = '".$_POST['id']."'";      
  $result = mysqli_query($conn,$sql);
  $data['status'] = 'success';
  $data['message'] = 'Request Sent to Spam Successfully!';
  echo json_encode($data);    die;
}

if (!empty($_POST["deleteRequests"])) {
  $sql = "update requests set delete_status = '1' where id = '".$_POST['id']."'";      
  $result = mysqli_query($conn,$sql);  
  $data['status'] = 'success';
  $data['message'] = 'Request Deleted Successfully!';
  echo json_encode($data);  die;
}
?>


<!DOCTYPE html>

<html
  lang="en"
  class="light-style layout-menu-fixed"
  dir="ltr"
  data-theme="theme-default"
  data-assets-path="assets/"
  data-template="vertical-menu-template-free"
>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"
    />

    <title>Microsites</title>

    <meta name="description" content="" />

    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="assets/img/favicon/favicon.ico" />

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap"
      rel="stylesheet"
    />

   
    <link rel="stylesheet" href="assets/vendor/fonts/boxicons.css" />

    <!-- Core CSS -->
    <link rel="stylesheet" href="assets/vendor/css/core.css" class="template-customizer-core-css" />
    <link rel="stylesheet" href="assets/vendor/css/theme-default.css" class="template-customizer-theme-css" />
    <link rel="stylesheet" href="assets/css/demo.css" />

    <!-- Vendors CSS -->
    <link rel="stylesheet" href="assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.css" />

    <script src="assets/vendor/js/helpers.js"></script>

    <script src="assets/js/config.js"></script>

    <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js" defer></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    <script type="text/javascript">
      $(function() {
      
          var start = moment().subtract(29, 'days');
          var end = moment();
      
          function cb(start, end) {
          
              $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
          
          }
      
          $('#reportrange').daterangepicker({
              startDate: start,
              endDate: end,
              ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
              }
          }, cb);
      
          cb(start, end);

          var filterdate = '<?php if(isset($_GET['filterbydate'])){ echo $_GET['filterbydate'];}else{ echo "" ;}; ?>';
          if(filterdate != "" && filterdate != null){
            $('#reportrange span').html(filterdate);
          }
      
      });
      
      

    </script>

  
  </head>

  <body>
    <!-- Layout wrapper -->
    <div class="layout-wrapper layout-content-navbar">
      <div class="layout-container">
        

        <!-- Layout container -->
        <div class="layout-page">
          <!-- Navbar -->

          <?php include('navbar.php'); ?>

          <!-- / Navbar -->

          <!-- Content wrapper -->
          <div class="content-wrapper">
            <!-- Content -->

            <div class="container-xxl flex-grow-1 container-p-y">
            <div class="card" id="offerAcceptDenyResultDiv">
            <span style="color:red;text-align: center;" id="offerAcceptDenyResult" ></span>
            </div>

            <div id="reportrange" style="background: #fff; cursor: pointer; padding: 10px 10px; border: 1px solid #ccc; width:30%; border-radius: 5px;     font-size: 18px;">
                <i class="fa fa-calendar"></i>&nbsp;
                <span><?php if(isset($_GET['filterbydate'])){ echo $_GET['filterbydate'];} ?></span> <i class="fa fa-caret-down"></i>
            </div>
              
              <!-- Basic Bootstrap Table -->
              <div class="card" style="margin-top: 20px;">
               <!--  <h5 class="card-header">Table Basic</h5> -->
               <div class="table-responsive">
                <!--<div class="table-responsive text-nowrap" style="white-space: norap !important;">-->
                  <table class="table">
                    <thead>                   
                      <tr>
                        <th>ID</th>
                        <th>Project</th>
                        <th>Sender</th>
                        <th>Source</th>
                        <th>Date</th>
                        <th>Location</th>
                        <th>Mobile</th>
                        <th>IP</th>
                        <th>Email</th>
                        <th>Action</th>
                      </tr>
                    
                    </thead>
                    <tbody class="table-border-bottom-0">

                    	<?php 

                      if(mysqli_num_rows($result) > 0){

          						while($row=mysqli_fetch_array($result))
                       
          						{?>

	                      <tr id="tr<?=$row['id']?>">
	                        <td><?php echo $row['id']?></td>
                          <td><?php echo $row['project_name']?></td>
                          <td><?php echo $row['name']?></td>
                          <td><?php echo (!empty($row['utm_source'])) ? $row['utm_source'] : "N/A" ?></td>
                          <td><?php echo $row['request_datetime']?></td>
                          <td><?php echo $row['city']." (".$row['country'].")"?></td>
                         <td><?php echo "(".$row['calling_code'].") XXXXXX".substr($row['mobile'], -4);?></td>
                          <td><?php echo $row['ip_address']?></td>
                          <td><?php echo substr($row['email'], 0,3)."xxxx@gmail.com";?></td>
                          <td><a href="javascript:void(0);" onclick="sendSpam(<?=$row['id']?>)" title="Send Spam">
                          <img src="assets\img\spam.jpg" width="24px;">
                          </a>
                          <?php if($_SESSION['admin_id'] == 1){ ?>
                          <span onclick="deletefunction(<?=$row['id']?>)" title="Delete"><img src="assets\img\delete.jpg" width="24px;"></span>
                          <?php } ?>
                        </td>                  

	                        
	                      </tr>

                       <?php } } else{ echo '<tr><td colspan="8" style="text-align:center;">No Found Data</td></tr>'; }?>
                      
                     
                    </tbody>
                  </table>

                 
                </div>

                 <!-- (E2) PAGINATION -->
                <div class="pagination">
                <?php

                  $totalpages = ceil($totalRes['total']/$limite);
                  
                  if($totalpages > 1){
                    echo '<a class="btn btn-primary" href = "?page=1'.$addUrl.'">First</a>';
                  }
                  $num = 1;
                  $showbuttoncount = 1;
                  if($pageNow > 2) {
                    $startfor = $pageNow -2;
                    $showbuttoncount = 3;
                    for($num =  $startfor; $num < ($startfor+2); $num ++) {                     
                     
                      if($pageNow==$num){
                        echo '<a class="btn btn-dark active mx-1" href = "?page=' . $num . $addUrl.'">' . $num . ' </a>';
                        } else{
                        echo '<a class="btn btn-primary mx-1" href = "?page=' . $num .$addUrl. '">' . $num . ' </a>';
                        }
                    }
                       
                    
                  }
                  
                  for($num =  $num; $num <= $totalpages; $num++) { 
                    $showbuttoncount++;
                      if($showbuttoncount > 5){                         
                        break;
                      }

                      if($pageNow==$num){
                      echo '<a class="btn btn-dark active mx-1" href = "?page=' . $num . $addUrl.'">' . $num . ' </a>';
                      } else{
                      echo '<a class="btn btn-primary mx-1" href = "?page=' . $num .$addUrl. '">' . $num . ' </a>';
                      }  
                  } 

                  if($totalpages > 1){
                    echo '<a class="btn btn-primary" href = "?page='.$totalpages.$addUrl.'">Last</a>';
                  }
                ?>
               
                  
                </div>

              </div>
          

            </div>
            <!-- / Content -->


            <div class="content-backdrop fade"></div>
          </div>
          <!-- Content wrapper -->
        </div>
        <!-- / Layout page -->
      </div>

      
    </div>
    

    <script src="assets/vendor/libs/jquery/jquery.js"></script>
    <script src="assets/vendor/libs/popper/popper.js"></script>
    <script src="assets/vendor/js/bootstrap.js"></script>
    <script src="assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js"></script>

    <script src="assets/vendor/js/menu.js"></script>
    <!-- endbuild -->

    <!-- Vendors JS -->

    <!-- Main JS -->
    <script src="assets/js/main.js"></script>

    <!-- Page JS -->

    <!-- Place this tag in your head or just before your close body tag. -->
    <script async defer src="https://buttons.github.io/buttons.js"></script>
    <script type="text/javascript">
      function sendSpam(id){
          if(confirm("Are you sure you want to send in spam?"))
        {
        document.getElementById('tr'+id).style.display = "none";
        var spanRequests = "true";
        $.ajax({
            header: { 'Access-Control-Allow-Origin':'*'},
            url : "microsites.php",
            data: {'spanRequests':spanRequests,'id':id},                              
            cache: 'false',
            type: 'post',
            dataType: "json",
              success: function(data){
                if (data.status == 'success') {
                    $("#offerAcceptDenyResultDiv").addClass('alert-success').show();
                    $("#offerAcceptDenyResult").text(data.message);
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                }
                else {

                    $("#offerAcceptDenyResultDiv").addClass('alert-danger').show();
                    $("#offerAcceptDenyResult").text('Some error occurred, Please try again');

                }
                
            }
              
        })
      }
      }

      function deletefunction(id){

        if(confirm("Are you sure you want to delete this?"))
        {
          document.getElementById('tr'+id).style.display = "none";
          var deleteRequests = "true";
            $.ajax({
                header: { 'Access-Control-Allow-Origin':'*'},
                url : "microsites.php",
                data: {'deleteRequests':deleteRequests,'id':id},                              
                cache: 'false',
                type: 'post',
                dataType: "json",
              success: function(data){
                if (data.status == 'success') {
                    $("#offerAcceptDenyResultDiv").addClass('alert-success').show();
                    $("#offerAcceptDenyResult").text(data.message);
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                }
                else {

                    $("#offerAcceptDenyResultDiv").addClass('alert-danger').show();
                    $("#offerAcceptDenyResult").text('Some error occurred, Please try again');

                }
                
            }
                  
            })
        }
      }

      $('#reportrange').on('apply.daterangepicker', function(ev, picker) {
          var date = $('#reportrange span').text();
          var url = "microsites.php?filterbydate="+date;
          window.location.href = url;
      });

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

