<?php

  $pass = "55jfbikiC6YaOgLhgW2eRv";

  use Medoo\Medoo;

  require_once("Kakatoxyinya.php");

  require_once("vpisdostup.php");



  function modifyLocations($keyvals) {
    $url = $_SERVER['REQUEST_URI'];
    foreach($keyvals as $key => $val) {
      $url = modifyLocation($key, $val, $url);
    }
    return $url;
  }
  function modifyLocation($var, $val, $url = false) {
    if (!$url) $url = $_SERVER['REQUEST_URI'];
    $urlComponents = parse_url($url);
    parse_str($urlComponents['query'], $queryParams);
    if (isset($queryParams[$var])) {
        $queryParams[$var] = $val;
    } else {
        $queryParams[$var] = $val;
    }
    if ($val == "unset") unset($queryParams[$var]);
    $newQuery = http_build_query($queryParams);
    $modifiedUrl = $urlComponents['path'] . '?' . $newQuery;
    return $modifiedUrl;
  }

  $db = new Medoo([
      'type' => 'mysql',
      'host' => DB_HOST,
      'port' => DB_PORT,
      'database' => DB_NAME,
      'username' => DB_USER,
      'password' => DB_PASSWORD,
      'charset' => 'utf8mb4'
  ]);

  if ($db->error) dieWithCode(404, "db connect error");
  
  $logged = false;

  if(isset($_GET["action"])) {
    if ($_GET["action"] == "clear") {
      file_put_contents("stat.dat", "");
      header("location:index.php?pass=".base64_encode($pass));
    }
  }
  if(isset($_GET["pass"]) && base64_decode($_GET["pass"]) == $pass) {
    echo "<script>const base_url='index.php?pass=".base64_encode($pass)."';</script>";
    $logged = true;
  }
?>

<!DOCTYPE html>
<html>
<head>
  <title>Statistics</title>
  <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="favicon.ico" rel="shortcut icon" />

    <style type="text/tailwindcss">
      .stat{
        @apply w-full bg-white;
      }
      .stat td, .stat th {
        @apply p-2 border;
      }   
      .stat th {
        border-bottom:4px solid #333;
        @apply bg-gray-200;
      } 
      .stat tbody tr:hover{
        @apply bg-gray-100;
      }
      .pagination {
        @apply mb-4;
      }
      .pagination li {
        list-style-type:none;
        @apply text-2xl font-bold mr-4 hover:text-blue-500;
      }
      .pagination li.active {
        @apply text-green-500;
      }
    </style>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="p-8 bg-gray-100">

  <?php if(!$logged): ?>
    <h1 class="text-2xl font-bold">Enter password</h1>
    <div class="h-4"></div>
    <input class="border-2 border-black h-12 w-full px-4 text-xl" type="text" name="link" id="pass" value="">
    <div class="h-4"></div>
    <button class="bg-black border-none text-white text-xl h-12 px-12 rounded-sm hover:bg-blue-600 login">Submit</button>

    <script>
      const loginBtn = document.querySelector(".login");
      if (loginBtn) {
        loginBtn.addEventListener("click", (e) => {
          const pass = document.getElementById("pass").value.trim();
          window.location.href="index.php?pass="+btoa(pass);
        })
      }
    </script>

  <?php endif; ?>

  <?php if ($logged): ?>
  
    <h1 class="font-bold text-2xl">Download Statistics</h1>

    <div class="h-8"></div>

    <div class="flex items-center">
      <a href="<?php echo modifyLocations(["filter"=>"unset", "page"=>1]); ?>" class="flex items-center justify-center bg-blue-600 border-none text-white h-10 px-6 rounded-sm hover:bg-blue-900 filter">All</a>
      <div class="w-4"></div>
      <a href="<?php echo modifyLocations(["filter"=>"action,Download", "page"=>1]); ?>" class="flex items-center justify-center bg-blue-600 border-none text-white h-10 px-6 rounded-sm hover:bg-blue-900 filter">Downloads</a>
      <div class="w-4"></div>
      <a href="<?php echo modifyLocations(["filter"=>"action,Visit", "page"=>1]); ?>" class="flex items-center justify-center bg-blue-600 border-none text-white h-10 px-6 rounded-sm hover:bg-blue-900 filter">Visits</a>
      <div class="w-4"></div>
      <a href="<?php echo modifyLocations(["filter"=>"useragent,Windows", "page"=>1]); ?>" class="flex items-center justify-center bg-blue-600 border-none text-white h-10 px-6 rounded-sm hover:bg-blue-900 filter">WIN</a>
      <div class="w-4"></div>
      <a href="<?php echo modifyLocations(["filter"=>"useragent,Macintosh", "page"=>1]); ?>" class="flex items-center justify-center bg-blue-600 border-none text-white h-10 px-6 rounded-sm hover:bg-blue-900 filter">MAC</a>
      <div class="w-4"></div>
      <a href="<?php echo modifyLocations(["filter"=>"useragent,Android", "page"=>1]); ?>" class="flex items-center justify-center bg-blue-600 border-none text-white h-10 px-6 rounded-sm hover:bg-blue-900 filter">Android</a>
      <div class="w-4"></div>
      <a href="<?php echo modifyLocations(["filter"=>"useragent,iPhone", "page"=>1]); ?>" class="flex items-center justify-center bg-blue-600 border-none text-white h-10 px-6 rounded-sm hover:bg-blue-900 filter">iPhone</a>
    </div>

    <div class="h-8"></div>

    <div class="flex">
      <select id="where" class="px-4 border-black border-2">
        <option value="useragent">Browser</option>
        <option value="ip">IP</option>
        <option value="date">Date</option>
        <option value="action">Action</option>
      </select>
      <div class="w-4"></div>
      <input type="text" id="what" placeholder="Search for..." class="px-4 border-black border-2">
      <div class="w-4"></div>
      <a href="#" id="go" class="flex items-center justify-center bg-blue-600 border-none text-white h-10 px-6 rounded-sm hover:bg-blue-900 filter">Go</a>
    </div>
    <div class="h-4"></div>

    <table class="stat">
      <thead>
      <tr>
        <th>Action</th>
        <th>Date</th>
        <th>IP</th>
        <th>Browser</th>
      </tr>
      </thead>
      <tbody>
    <?php 

        $page = isset($_GET["page"]) ? $_GET["page"] : 1;
        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $where = [
          "LIMIT" => [$offset, $perPage],
          "ORDER" => [
            "date" => "DESC"
          ]
        ];

        if (isset($_GET["clear"])) {
          $db->delete("stat", "*");
          echo "<script>window.location.href = '".modifyLocation("clear","unset")."';</script>";
          die();
        }

        if(isset($_GET["filter"])) {
          $ex = explode(",", $_GET["filter"]);
          $where[$ex[0]."[~]"] = trim($ex[1]);
        }

        $where_no_pagination = $where;
        unset ($where_no_pagination["LIMIT"]);
        $existingRowCount = $db->count("stat", "*", $where_no_pagination);

        $existing = $db->select("stat", "*", $where);

        $totalRows = $db->count("stat");

        $rows = $totalRows;
        
        if (isset($_GET["filter"])) {
          $rows = $existingRowCount;
        }
        
        $totalPages = ceil($rows / $perPage);
        
        if ($existing) {
            
          
          foreach($existing as $item) {
              $clr = "#00cc00";
              if ($item["action"] == "Download") $clr = "#F04903";
              echo "<tr><td><b style='color:".$clr."'>".$item["action"]."</b></td><td>".$item["date"]."</td><td>".$item["ip"]."</td><td>".$item["useragent"]."</td></tr>";
          }
        }
    ?> 
      </tbody>
    </table>
    <div class="h-8"></div>
    <div class="flex items center pagination">
      <?php
      $visiblePages = 10;
      $startPage = max(1, $page - floor($visiblePages / 2));
      $endPage = min($startPage + $visiblePages - 1, $totalPages);

      if ($endPage - $startPage + 1 < $visiblePages) {
          $startPage = max(1, $endPage - $visiblePages + 1);
      }

      if ($startPage > 1) {
          echo '<li><a href="'.modifyLocation("page", 1).'">1</a></li>';
          if ($startPage > 2) {
              echo '<li><span>...</span></li>';
          }
      }

      for ($i = $startPage; $i <= $endPage; $i++) {
          echo '<li';
          if ($i == $page) {
              echo ' class="active"';
          }
          echo '><a href="' . modifyLocation("page", $i) . '">' . $i . '</a></li>';
      }

      if ($endPage < $totalPages) {
          if ($endPage < $totalPages - 1) {
              echo '<li><span>...</span></li>';
          }
          echo '<li><a href="' . modifyLocation("page",$totalPages) . '">' . $totalPages . '</a></li>';
      }

      ?>
    </div>
    <div class="flex items center">
      <div class="text-2xl mr-4">Rows:</div>
      <div class="matches text-2xl font-bold"><?php echo $rows; ?></div>
    </div>
    <div class="h-8"></div>
    <a href="<?php echo modifyLocation("clear","1"); ?>" class="flex items-center justify-center w-64 font-bold bg-black border-none text-red-500 text-xl h-12 px-12 rounded-sm hover:bg-red-500 hover:text-white">Clear statistics</a>

    <script type="text/javascript">
      $(document).ready(function(){
      
        $("#go").click(() => {
          const where = $("#where").val();
          const what = $("#what").val();
          window.location.href=`${base_url}&filter=${where},${what}`;
        })
      })
    </script>



  <?php endif; ?>
</body>
</html>