<?php 
/**
* Note: This file may contain artifacts of previous malicious infection.
* However, the dangerous code has been removed, and the file is now safe to use.
*/
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Install Pebble <?php echo PEBBLE_TIER === 'pro' ? 'Pro' : 'Core'; ?> <?php echo PEBBLE_VERSION; ?></title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: system-ui, -apple-system, sans-serif; background: #f8fafc; min-height: 100vh; padding: 2rem; }
        .container { max-width: 600px; margin: 0 auto; }
        .card { background: white; border-radius: 12px; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1); padding: 2rem; margin-bottom: 1.5rem; }
        h1 { font-size: 1.5rem; color: #0f172a; margin-bottom: 0.5rem; }
        .version { color: #64748b; font-size: 0.875rem; margin-bottom: 1.5rem; }
        .tier-badge { display: inline-block; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; }
        .tier-core { background: #e0f2fe; color: #0369a1; }
        .tier-pro { background: #fef3c7; color: #92400e; }
        .step { display: none; }
        .step.active { display: block; }
        .requirement { display: flex; align-items: center; padding: 0.75rem; border-radius: 8px; margin-bottom: 0.5rem; }
        .requirement.pass { background: #f0fdf4; }
        .requirement.fail { background: #fef2f2; }
        .requirement.warn { background: #fffbeb; }
        .requirement-icon { width: 20px; height: 20px; margin-right: 0.75rem; }
        .requirement.pass .requirement-icon { color: #22c55e; }
        .requirement.fail .requirement-icon { color: #ef4444; }
        .requirement.warn .requirement-icon { color: #f59e0b; }
        button { background: #06b6d4; color: white; border: none; padding: 0.75rem 1.5rem; border-radius: 8px; font-size: 1rem; cursor: pointer; width: 100%; margin-top: 1rem; }
        button:hover { background: #0891b2; }
        button:disabled { background: #94a3b8; cursor: not-allowed; }
        .btn-secondary { background: #e2e8f0; color: #475569; }
        .btn-secondary:hover { background: #cbd5e1; }
        .success-box { text-align: center; padding: 2rem; }
        .success-icon { font-size: 4rem; margin-bottom: 1rem; }
        .auth-key { font-family: monospace; background: #f1f5f9; padding: 1rem; border-radius: 8px; word-break: break-all; margin: 1rem 0; }
        input[type="text"], input[type="password"], select { width: 100%; padding: 0.75rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 1rem; margin-top: 0.5rem; }
        label { display: block; font-weight: 500; color: #374151; margin-top: 1rem; }
        label:first-child { margin-top: 0; }
        .form-hint { font-size: 0.75rem; color: #6b7280; margin-top: 0.25rem; }
        .error { color: #dc2626; margin-top: 0.5rem; font-size: 0.875rem; }
        .loading { text-align: center; padding: 2rem; }
        .spinner { width: 40px; height: 40px; border: 3px solid #e2e8f0; border-top-color: #06b6d4; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 1rem; }
        @keyframes spin { to { transform: rotate(360deg); } }
        .step-header { margin-bottom: 1.5rem; }
        .step-header h2 { font-size: 1.125rem; color: #0f172a; margin-bottom: 0.25rem; }
        .step-header p { color: #64748b; font-size: 0.875rem; }
        .timezone-row { display: flex; gap: 0.5rem; align-items: flex-end; }
        .timezone-row select { flex: 1; }
        .timezone-row button { width: auto; margin-top: 0; padding: 0.75rem 1rem; }
        /* Toggle switch */
        .toggle-row { margin-top: 1rem; }
        .toggle-label { display: flex; align-items: center; cursor: pointer; user-select: none; }
        .toggle-input { position: absolute; opacity: 0; width: 0; height: 0; }
        .toggle-switch { position: relative; width: 44px; height: 24px; background: #e2e8f0; border-radius: 12px; transition: background 0.2s; flex-shrink: 0; }
        .toggle-switch::after { content: ''; position: absolute; top: 2px; left: 2px; width: 20px; height: 20px; background: white; border-radius: 50%; transition: transform 0.2s; box-shadow: 0 1px 3px rgba(0,0,0,0.2); }
        .toggle-input:checked + .toggle-switch { background: #06b6d4; }
        .toggle-input:checked + .toggle-switch::after { transform: translateX(20px); }
        .toggle-text { margin-left: 0.5rem; font-weight: 500; color: #374151; }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h1>
                Install Pebble
                <span class="tier-badge tier-<?php echo PEBBLE_TIER; ?>"><?php echo PEBBLE_TIER; ?></span>
            </h1>
            <div class="version">Version <?php echo PEBBLE_VERSION; ?></div>

            <!-- Step 1: Requirements Check -->
            <div id="step-requirements" class="step active">
                <div class="loading">
                    <div class="spinner"></div>
                    <p>Checking requirements...</p>
                </div>
            </div>

            <!-- Step 2: Ready to Install -->
            <div id="step-ready" class="step">
                <div id="requirements-list"></div>
                <button id="btn-continue">Continue</button>
            </div>

            <!-- Step 3: Configuration -->
            <div id="step-config" class="step">
                <div class="step-header">
                    <h2>Configure Your Installation</h2>
                    <p>Set up your admin credentials and timezone.</p>
                </div>

                <label for="username">Username</label>
                <input type="text" id="username" placeholder="admin" autocomplete="username">
                <div class="form-hint">Leave blank to use auth key only</div>

                <label for="password">Password</label>
                <input type="password" id="password" placeholder="Enter a secure password" autocomplete="new-password">
                <div class="form-hint">Minimum 4 characters if using password login</div>

                <label for="timezone">Timezone</label>
                <div class="timezone-row">
                    <select id="timezone">
                        <option value="auto">Auto-detect from browser</option>
                        <option value="UTC">UTC</option>
                        <option value="America/New_York">America/New_York (Eastern)</option>
                        <option value="America/Chicago">America/Chicago (Central)</option>
                        <option value="America/Denver">America/Denver (Mountain)</option>
                        <option value="America/Los_Angeles">America/Los_Angeles (Pacific)</option>
                        <option value="America/Toronto">America/Toronto</option>
                        <option value="America/Vancouver">America/Vancouver</option>
                        <option value="Europe/London">Europe/London</option>
                        <option value="Europe/Paris">Europe/Paris</option>
                        <option value="Europe/Berlin">Europe/Berlin</option>
                        <option value="Asia/Tokyo">Asia/Tokyo</option>
                        <option value="Asia/Shanghai">Asia/Shanghai</option>
                        <option value="Asia/Singapore">Asia/Singapore</option>
                        <option value="Australia/Sydney">Australia/Sydney</option>
                        <option value="Pacific/Auckland">Pacific/Auckland</option>
                    </select>
                    <button type="button" id="btn-detect-tz" class="btn-secondary">Detect</button>
                </div>
                <div class="form-hint" id="detected-tz"></div>

                <?php if (PEBBLE_TIER === 'pro'): ?>
                <div class="toggle-row" style="margin-top: 1.5rem;">
                    <label class="toggle-label">
                        <input type="checkbox" id="white-label" class="toggle-input">
                        <span class="toggle-switch"></span>
                        <span class="toggle-text">White-label mode</span>
                    </label>
                    <div class="form-hint" style="margin-left: 52px; margin-top: 0.25rem;">Hide Pebble branding (for agency deployments)</div>
                </div>
                <?php endif; ?>

                <div id="config-error" class="error" style="display: none;"></div>
                <button id="btn-install">Install Pebble</button>
            </div>

            <!-- Step 4: Existing Website Warning -->
            <div id="step-existing" class="step">
                <div class="step-header">
                    <h2>Existing Files Detected</h2>
                    <p>We found existing website files. What would you like to do?</p>
                </div>
                <button id="btn-skip-starter" class="btn-secondary">Keep Existing Files</button>
                <button id="btn-create-starter">Create Starter Page (overwrites index.html)</button>
            </div>

            <!-- Step 5: Installing -->
            <div id="step-installing" class="step">
                <div class="loading">
                    <div class="spinner"></div>
                    <p>Installing Pebble...</p>
                </div>
            </div>

            <?php if (PEBBLE_TIER === 'pro'): ?>
            <!-- Step 5: License Activation (Pro only) -->
            <div id="step-license" class="step">
                <h2 style="margin-bottom: 1rem;">Activate Pro License</h2>
                <p style="margin-bottom: 1rem; color: #64748b;">Enter your license key to unlock Pro features.</p>
                <label for="license-key">License Key</label>
                <input type="text" id="license-key" placeholder="PEBBLE-XXXX-XXXX-XXXX-XXXX">
                <div id="license-error" class="error" style="display: none;"></div>
                <button id="btn-activate">Activate License</button>
                <button id="btn-skip-license" class="btn-secondary">Skip for Now</button>
            </div>
            <?php endif; ?>

            <!-- Step 7: Success -->
            <div id="step-success" class="step">
                <div class="success-box">
                    <div class="success-icon">✓</div>
                    <h2>Installation Complete!</h2>
                    <p style="margin-top: 1rem; color: #64748b;">Your auth key (backup login):</p>
                    <div class="auth-key" id="auth-key-display"></div>
                    <p id="auth-note" style="color: #64748b; font-size: 0.875rem;">Save this key! Add <code>#login</code> to any page URL to enable editing.</p>
                    <button id="btn-view-site">View Your Site</button>
                    <button id="btn-delete-installer" class="btn-secondary">Delete Installer (Recommended)</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const tier = '<?php echo PEBBLE_TIER; ?>';
        let authKey = '';
        let skipStarterPage = false;
        let existingFiles = [];
        let hasPassword = false;

        // Show a step
        function showStep(stepId) {
            document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));
            document.getElementById('step-' + stepId).classList.add('active');
        }

        // Detect timezone
        function detectTimezone() {
            try {
                const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
                return tz || 'auto';
            } catch (e) {
                return 'auto';
            }
        }

        // Check requirements on load
        async function checkRequirements() {
            try {
                const formData = new FormData();
                formData.append('action', 'check_requirements');

                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    displayRequirements(data.requirements, data.can_install);
                    existingFiles = data.requirements.existing_website?.files || [];
                }
            } catch (error) {
                console.error('Check failed:', error);
            }
        }

        function displayRequirements(requirements, canInstall) {
            const list = document.getElementById('requirements-list');
            list.innerHTML = '';

            for (const [key, req] of Object.entries(requirements)) {
                const status = req.required ? (req.status ? 'pass' : 'fail') : (req.status ? 'pass' : 'warn');
                const icon = status === 'pass' ? '✓' : (status === 'fail' ? '✗' : '!');

                list.innerHTML += `
                    <div class="requirement ${status}">
                        <span class="requirement-icon">${icon}</span>
                        <span>${req.message}</span>
                    </div>
                `;
            }

            document.getElementById('btn-continue').disabled = !canInstall;
            showStep('ready');
        }

        // Continue to config
        document.getElementById('btn-continue').addEventListener('click', () => {
            // Auto-detect timezone
            const tz = detectTimezone();
            const tzSelect = document.getElementById('timezone');
            const tzHint = document.getElementById('detected-tz');

            // Try to select the detected timezone
            for (let i = 0; i < tzSelect.options.length; i++) {
                if (tzSelect.options[i].value === tz) {
                    tzSelect.selectedIndex = i;
                    tzHint.textContent = 'Detected: ' + tz;
                    break;
                }
            }
            if (tzSelect.value === 'auto') {
                tzHint.textContent = 'Detected: ' + tz + ' (using auto-detect)';
            }

            showStep('config');
        });

        // Detect timezone button
        document.getElementById('btn-detect-tz')?.addEventListener('click', () => {
            const tz = detectTimezone();
            const tzSelect = document.getElementById('timezone');
            const tzHint = document.getElementById('detected-tz');

            for (let i = 0; i < tzSelect.options.length; i++) {
                if (tzSelect.options[i].value === tz) {
                    tzSelect.selectedIndex = i;
                    tzHint.textContent = 'Detected: ' + tz;
                    return;
                }
            }
            tzHint.textContent = 'Detected: ' + tz + ' (not in list, using auto-detect)';
            tzSelect.value = 'auto';
        });

        // Install button (from config step)
        document.getElementById('btn-install').addEventListener('click', () => {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            const errorEl = document.getElementById('config-error');

            // Validate
            if (username && !password) {
                errorEl.textContent = 'Please enter a password if using username login';
                errorEl.style.display = 'block';
                return;
            }
            if (password && password.length < 4) {
                errorEl.textContent = 'Password must be at least 4 characters';
                errorEl.style.display = 'block';
                return;
            }

            errorEl.style.display = 'none';

            if (existingFiles.length > 0) {
                showStep('existing');
            } else {
                performInstall(false);
            }
        });

        // Existing website options
        document.getElementById('btn-skip-starter')?.addEventListener('click', () => {
            performInstall(true);
        });

        document.getElementById('btn-create-starter')?.addEventListener('click', () => {
            performInstall(false);
        });

        async function performInstall(skip) {
            skipStarterPage = skip;
            showStep('installing');

            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            const timezone = document.getElementById('timezone').value;
            const whiteLabelEl = document.getElementById('white-label');
            const whiteLabel = whiteLabelEl ? whiteLabelEl.checked : false;

            try {
                const formData = new FormData();
                formData.append('action', 'install');
                formData.append('skip_starter_page', skip ? 'true' : 'false');
                formData.append('username', username);
                formData.append('password', password);
                formData.append('timezone', timezone);
                formData.append('white_label', whiteLabel ? 'true' : 'false');

                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    authKey = data.auth_key;
                    hasPassword = data.has_password;
                    document.getElementById('auth-key-display').textContent = authKey;

                    // Update success message based on login method
                    const authNote = document.getElementById('auth-note');
                    if (authNote) {
                        if (hasPassword) {
                            authNote.innerHTML = 'Login with your username and password, or use the auth key above.';
                        } else {
                            authNote.innerHTML = 'Save this key! Add <code>#login</code> to any page URL to enable editing.';
                        }
                    }

                    if (tier === 'pro') {
                        showStep('license');
                    } else {
                        showStep('success');
                    }
                } else {
                    alert('Installation failed: ' + (data.error || 'Unknown error'));
                    showStep('config');
                }
            } catch (error) {
                alert('Installation failed: ' + error.message);
                showStep('config');
            }
        }

        // License activation (Pro)
        document.getElementById('btn-activate')?.addEventListener('click', async () => {
            const licenseKey = document.getElementById('license-key').value.trim().toUpperCase();
            const errorEl = document.getElementById('license-error');

            if (!licenseKey) {
                errorEl.textContent = 'Please enter a license key';
                errorEl.style.display = 'block';
                return;
            }

            try {
                const formData = new FormData();
                formData.append('action', 'activate_license');
                formData.append('license_key', licenseKey);

                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    showStep('success');
                } else {
                    errorEl.textContent = data.error || 'Activation failed';
                    errorEl.style.display = 'block';
                }
            } catch (error) {
                errorEl.textContent = 'Connection failed';
                errorEl.style.display = 'block';
            }
        });

        document.getElementById('btn-skip-license')?.addEventListener('click', () => {
            showStep('success');
        });

        // Success actions
        document.getElementById('btn-view-site')?.addEventListener('click', () => {
            const url = skipStarterPage ? 'pebble/' : 'index.html';
            window.location.href = url;
        });

        document.getElementById('btn-delete-installer')?.addEventListener('click', async () => {
            if (!confirm('Delete installer file? This cannot be undone.')) return;

            try {
                const formData = new FormData();
                formData.append('action', 'delete_installer');

                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    const url = skipStarterPage ? 'pebble/' : 'index.html';
                    window.location.href = url;
                } else {
                    alert('Could not delete installer. Please delete it manually.');
                }
            } catch (error) {
                alert('Could not delete installer. Please delete it manually.');
            }
        });

        // Start
        checkRequirements();
    </script>
</body>
</html>