<?php 
// Start the session
session_start();
// Include the database connection file
include "../dbc.php";

// Check if the user is logged in
if(!isset($_SESSION["login"])){
  header("Location:login.php");
}

// Check if the form is submitted
if(isset($_POST["submit"])){

  // Get form data
  $filename = $_POST["filename"];
  $expiry = date("Y-m-d H:i:s", strtotime($_POST["expiry"]));
  $access = $_POST["access"];
  $remark = $_POST["remark"];
  $uagent = $_POST["uagent"]; // User-agent string(s)
  $checker = $_POST["checker"];
  $username = $_POST["username"]; // New username field

  // Generate keytoken based on filename
  $keytoken = bin2hex(random_bytes(2));
  $status = 1;
  $created_at = date("Y-m-d H:i:s");

  // Insert the data into the database
  $sql = "INSERT INTO page (keytoken, filename, accessable_count, created_at, expiry_at, status, remark, uagent, count_checker, username) VALUES ('$keytoken', '$filename', '$access', '$created_at', '$expiry', '$status', '$remark', '$uagent', '$checker', '$username')";
  $result = mysqli_query($conn, $sql);

  // Check if insertion was successful
  if($result){
    echo "<script>
      alert('Successfully created!');
      window.location.href='page-list.php';
      </script>";
  } else {
    echo "<script>
      alert('Error: Unable to create URL link.');
      </script>";
  }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php include "inc-dashboard-header.php"; ?>
  <style>
    #filename-container,
    #uagent-container,
    #checker-container {
      display: none;
    }
    .breadcrumb-buttons a {
      text-decoration: none;
    }
    .breadcrumb-buttons .btn {
      margin: 0 4px;
    }
  </style>
</head>

<body id="page-top">

  <?php include "inc-dashboard-topbar.php"; ?>

  <div id="wrapper">

    <div id="content-wrapper">

      <div class="container-fluid">

        <!-- Breadcrumbs-->
        <ol class="breadcrumb breadcrumb-buttons">
          <li class="breadcrumb-item">
            <b>Create New Page: </b>
            <a href="page-list.php" class="btn btn-outline-secondary btn-sm ml-2">Back to Page List</a>
          </li>
        </ol>

        <div class="tab-content" id="nav-tabContent">

          <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
            <div class="card mb-3">
              <div class="card-header">
                <i class="fas fa-table"></i>
                Create
              </div>
              <div class="card-body">
                <button type="button" class="btn btn-outline-info" onclick="populateTVM()">Create TVM</button>
                <button type="button" class="btn btn-outline-info" onclick="populateOTT()">Create OTT</button>
                <form class="form-subscribe mt-3" method="POST" action="" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col">
                          <label for="expiry" style="font-size: 16px;">Expiry Date</label>
                          <input class="form-control" id="expiry" name="expiry" type="datetime-local" value="" placeholder="Expiry Date" required />
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col">
                          <label for="access" style="font-size: 16px;">Access Count</label>
                          <input class="form-control" id="access" name="access" type="number" value="" placeholder="Access Count" required />
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col">
                          <label for="username" style="font-size: 16px;">Username</label>
                          <input class="form-control" id="username" name="username" type="text" value="" placeholder="Username" required />
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col">
                          <label for="remark" style="font-size: 16px;">Remark</label>
                          <textarea class="form-control" id="remark" name="remark"></textarea>
                          <small class="form-text text-muted"><font color="red">*** TVM | @username</font></small>
                          <small class="form-text text-muted"><font color="red"> / OTT | @username</font></small>
                        </div>
                    </div>
                    <div id="filename-container" class="row mt-2">
                        <div class="col">
                          <label for="filename" style="font-size: 16px;">Restore Point</label>
                          <input class="form-control" id="filename" name="filename" type="text" value="" placeholder="Page Name" required="" />
                          <small class="form-text text-muted">TVM: https://app.wvclouds.me/TVM/TiviMate_X.tmb</small>
                          <small class="form-text text-muted">OTT: https://app.wvclouds.me/OTT/OTT.RESTORE.1716</small>
                        </div>
                    </div>
                    <div id="uagent-container" class="row mt-2">
                        <div class="col">
                          <label for="uagent" style="font-size: 16px;">User Agent Allow</label>
                          <input class="form-control" id="uagent" name="uagent" type="text" value="" placeholder="User Agent" required="" />
                          <small class="form-text text-muted">Exp: okhttp/4.12.0<font color="red"> ** must separate each agent by comma</font></small>
                          <small class="form-text text-muted">Exp: OTT Navigator/1.7.1.6<font color="red"> ** must separate each agent by comma</font></small>
                        </div>
                    </div>
                    <div id="checker-container" class="row mt-2">
                        <div class="col">
                          <label for="checker" style="font-size: 16px;">Count Checker</label><br>
                          <label class="radio-inline" style="font-size: 15px;">
                            <input type="radio" name="checker" value="session" checked> Session
                          </label>
                          <label class="radio-inline" style="font-size: 15px; margin-left: 10px;">
                            <input type="radio" name="checker" value="ip"> IP
                          </label>
                        </div>
                    </div>
                    <div class="row mt-3 ml-1">
                        <div class="text-center">
                          <input class="btn btn-success" type="submit" name="submit" value="Create">
                        </div>
                    </div>
                </form>
              </div>
            </div>
          </div>

        </div>

      </div>
      <!-- /.container-fluid -->

      <!-- Sticky Footer -->
      <?php include "inc-dashboard-footer.php"; ?>

    </div>
    <!-- /.content-wrapper -->

  </div>
  <!-- /#wrapper -->

  <?php include "inc-dashboard-bottom.php"; ?>

  <script type="text/javascript">
    $(document).ready(function() {
        $('#dataTable1').DataTable();
    });

    $(document).ready(function(){
      $('[data-toggle="tooltip"]').tooltip();
    });

    function populateTVM() {
      const now = new Date();
      const expiryDate = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 24 hours from now
      
      const year = expiryDate.getFullYear();
      const month = String(expiryDate.getMonth() + 1).padStart(2, '0');
      const day = String(expiryDate.getDate()).padStart(2, '0');
      const hours = String(expiryDate.getHours()).padStart(2, '0');
      const minutes = String(expiryDate.getMinutes()).padStart(2, '0');
      
      const formattedExpiryDate = `${year}-${month}-${day}T${hours}:${minutes}`; // Format as YYYY-MM-DDTHH:MM

      document.getElementById('filename').value = 'https://app.wvclouds.me/TVM/TiviMate_X.tmb';
      document.getElementById('expiry').value = formattedExpiryDate;
      document.getElementById('access').value = 10;
      document.getElementById('remark').value = 'TVM | ';
      document.getElementById('uagent').value = 'okhttp/4.12.0,T-,T2-';
      document.querySelector('input[name="checker"][value="session"]').checked = true;
    }

    function populateOTT() {
      const now = new Date();
      const expiryDate = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 24 hours from now
      
      const year = expiryDate.getFullYear();
      const month = String(expiryDate.getMonth() + 1).padStart(2, '0');
      const day = String(expiryDate.getDate()).padStart(2, '0');
      const hours = String(expiryDate.getHours()).padStart(2, '0');
      const minutes = String(expiryDate.getMinutes()).padStart(2, '0');
      
      const formattedExpiryDate = `${year}-${month}-${day}T${hours}:${minutes}`; // Format as YYYY-MM-DDTHH:MM

      document.getElementById('filename').value = 'https://app.wvclouds.me/OTT/OTT.RESTORE.1716';
      document.getElementById('expiry').value = formattedExpiryDate;
      document.getElementById('access').value = 10;
      document.getElementById('remark').value = 'OTT | ';
      document.getElementById('uagent').value = 'OTT Navigator/1.7.1.6';
      document.querySelector('input[name="checker"][value="session"]').checked = true;
    }
  </script>

</body>

</html>