<?php
/**
 * Document Signing System - Setup Wizard
 * This file guides you through initial setup including database creation
 */

session_start();

// Step tracking
$current_step = isset($_GET['step']) ? intval($_GET['step']) : 1;
$setup_complete = false;
$error = '';
$success = '';

// Check if config.php exists and is editable
$config_exists = file_exists('config.php');

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_db_config') {
        // Save database configuration
        $db_host = $_POST['db_host'] ?? 'localhost';
        $db_user = $_POST['db_user'] ?? '';
        $db_pass = $_POST['db_pass'] ?? '';
        $db_name = $_POST['db_name'] ?? '';

        if (empty($db_user) || empty($db_name)) {
            $error = 'Database user and name are required';
        } else {
            // Store in session for now (will update config.php later)
            $_SESSION['db_config'] = [
                'host' => $db_host,
                'user' => $db_user,
                'pass' => $db_pass,
                'name' => $db_name
            ];

            $_SESSION['setup_step'] = 2;
            header('Location: setup.php?step=2');
            exit;
        }
    }

    if ($action === 'test_connection') {
        // Test database connection
        $db_host = $_POST['db_host'] ?? 'localhost';
        $db_user = $_POST['db_user'] ?? '';
        $db_pass = $_POST['db_pass'] ?? '';
        $db_name = $_POST['db_name'] ?? '';

        try {
            $pdo = new PDO(
                "mysql:host=$db_host",
                $db_user,
                $db_pass
            );
            $success = '✓ Connection successful!';
            $_SESSION['db_config'] = [
                'host' => $db_host,
                'user' => $db_user,
                'pass' => $db_pass,
                'name' => $db_name
            ];
        } catch (PDOException $e) {
            $error = 'Connection failed: ' . $e->getMessage();
        }
    }

    if ($action === 'create_database') {
        // Create new database
        $db_host = $_POST['db_host'] ?? 'localhost';
        $db_user = $_POST['db_user'] ?? '';
        $db_pass = $_POST['db_pass'] ?? '';
        $db_name = $_POST['db_name'] ?? '';

        if (empty($db_name)) {
            $error = 'Database name is required';
        } else {
            try {
                $pdo = new PDO(
                    "mysql:host=$db_host",
                    $db_user,
                    $db_pass
                );

                // Create database
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

                // Select the database
                $pdo->exec("USE `$db_name`");

                // Import database.sql
                $sql_file = 'database.sql';
                if (file_exists($sql_file)) {
                    $sql = file_get_contents($sql_file);
                    $pdo->exec($sql);
                    $success = '✓ Database created and tables imported successfully!';

                    $_SESSION['db_config'] = [
                        'host' => $db_host,
                        'user' => $db_user,
                        'pass' => $db_pass,
                        'name' => $db_name
                    ];

                    $_SESSION['setup_step'] = 3;
                    header('Location: setup.php?step=3');
                    exit;
                } else {
                    $error = 'database.sql file not found. Please ensure it\'s in the same directory as setup.php';
                }
            } catch (PDOException $e) {
                $error = 'Error: ' . $e->getMessage();
            }
        }
    }

    if ($action === 'import_database') {
        // Import database.sql to existing database
        $db_host = $_POST['db_host'] ?? 'localhost';
        $db_user = $_POST['db_user'] ?? '';
        $db_pass = $_POST['db_pass'] ?? '';
        $db_name = $_POST['db_name'] ?? '';

        try {
            $pdo = new PDO(
                "mysql:host=$db_host;dbname=$db_name",
                $db_user,
                $db_pass
            );

            // Import database.sql
            $sql_file = 'database.sql';
            if (file_exists($sql_file)) {
                $sql = file_get_contents($sql_file);
                $pdo->exec($sql);
                $success = '✓ Database tables created successfully!';

                $_SESSION['db_config'] = [
                    'host' => $db_host,
                    'user' => $db_user,
                    'pass' => $db_pass,
                    'name' => $db_name
                ];

                $_SESSION['setup_step'] = 3;
                header('Location: setup.php?step=3');
                exit;
            } else {
                $error = 'database.sql file not found';
            }
        } catch (PDOException $e) {
            $error = 'Error: ' . $e->getMessage();
        }
    }

    if ($action === 'update_config') {
        // Update config.php with database settings
        $encryption_key = $_POST['encryption_key'] ?? bin2hex(random_bytes(16));
        $hmac_key = $_POST['hmac_key'] ?? bin2hex(random_bytes(16));
        $base_url = $_POST['base_url'] ?? 'http://localhost/document-signing/';
        $smtp_host = $_POST['smtp_host'] ?? 'smtp.gmail.com';
        $smtp_user = $_POST['smtp_user'] ?? '';
        $smtp_pass = $_POST['smtp_pass'] ?? '';

        if (!$config_exists) {
            $error = 'config.php not found. Please ensure it\'s in the same directory.';
        } else {
            // Read current config
            $config_content = file_get_contents('config.php');

            // Update database credentials
            $db_config = $_SESSION['db_config'] ?? [];
            $config_content = preg_replace(
                "/define\('DB_HOST', '.*?'\);/",
                "define('DB_HOST', '" . ($db_config['host'] ?? 'localhost') . "');",
                $config_content
            );
            $config_content = preg_replace(
                "/define\('DB_USER', '.*?'\);/",
                "define('DB_USER', '" . ($db_config['user'] ?? '') . "');",
                $config_content
            );
            $config_content = preg_replace(
                "/define\('DB_PASS', '.*?'\);/",
                "define('DB_PASS', '" . ($db_config['pass'] ?? '') . "');",
                $config_content
            );
            $config_content = preg_replace(
                "/define\('DB_NAME', '.*?'\);/",
                "define('DB_NAME', '" . ($db_config['name'] ?? '') . "');",
                $config_content
            );

            // Update security keys
            $config_content = preg_replace(
                "/define\('ENCRYPTION_KEY', '.*?'\);/",
                "define('ENCRYPTION_KEY', '$encryption_key');",
                $config_content
            );
            $config_content = preg_replace(
                "/define\('HMAC_KEY', '.*?'\);/",
                "define('HMAC_KEY', '$hmac_key');",
                $config_content
            );

            // Update URLs and email
            $config_content = preg_replace(
                "/define\('BASE_URL', '.*?'\);/",
                "define('BASE_URL', '$base_url');",
                $config_content
            );
            $config_content = preg_replace(
                "/define\('SMTP_HOST', '.*?'\);/",
                "define('SMTP_HOST', '$smtp_host');",
                $config_content
            );
            $config_content = preg_replace(
                "/define\('SMTP_USER', '.*?'\);/",
                "define('SMTP_USER', '$smtp_user');",
                $config_content
            );
            $config_content = preg_replace(
                "/define\('SMTP_PASS', '.*?'\);/",
                "define('SMTP_PASS', '$smtp_pass');",
                $config_content
            );

            // Write updated config
            if (file_put_contents('config.php', $config_content)) {
                $success = '✓ Configuration saved successfully!';
                $_SESSION['setup_step'] = 4;
                header('Location: setup.php?step=4');
                exit;
            } else {
                $error = 'Could not write to config.php. Check file permissions.';
            }
        }
    }

    if ($action === 'complete_setup') {
        // Mark setup as complete
        $_SESSION['setup_complete'] = true;
        $setup_complete = true;
    }
}

// Get stored config from session
$db_config = $_SESSION['db_config'] ?? [];
$setup_step = $_SESSION['setup_step'] ?? 1;

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Setup Wizard - Document Signing System</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .wizard-container {
            max-width: 700px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .wizard-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .wizard-header h1 { margin-bottom: 10px; }
        .wizard-header p { opacity: 0.9; }

        .progress-bar {
            height: 4px;
            background: #e0e0e0;
            position: relative;
        }
        .progress-fill {
            height: 100%;
            background: #667eea;
            width: 25%;
            transition: width 0.3s;
        }

        .wizard-content {
            padding: 40px;
            min-height: 400px;
        }

        .step-title {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin-bottom: 20px;
        }

        .step-description {
            color: #666;
            margin-bottom: 30px;
            line-height: 1.6;
        }

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

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .button-group {
            display: flex;
            gap: 10px;
            margin-top: 30px;
        }

        button {
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #667eea;
            color: white;
            flex: 1;
        }

        .btn-primary:hover {
            background: #5568d3;
        }

        .btn-secondary {
            background: #e0e0e0;
            color: #333;
        }

        .btn-secondary:hover {
            background: #d0d0d0;
        }

        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .alert-error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .alert-success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .option-box {
            border: 2px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .option-box:hover {
            border-color: #667eea;
            background: #f9f9ff;
        }

        .option-box input[type="radio"] {
            margin-right: 10px;
        }

        .option-title {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }

        .option-description {
            color: #999;
            font-size: 13px;
        }

        .success-message {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .code-box {
            background: #f5f5f5;
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
            overflow-x: auto;
            margin: 15px 0;
            word-break: break-all;
        }

        .step-indicator {
            text-align: center;
            color: #999;
            font-size: 12px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="wizard-container">
        <div class="wizard-header">
            <h1>🔧 Setup Wizard</h1>
            <p>Configure your Document Signing System</p>
        </div>

        <div class="progress-bar">
            <div class="progress-fill" style="width: <?php echo ($current_step / 4) * 100; ?>%"></div>
        </div>

        <div class="wizard-content">

            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>

            <!-- STEP 1: Database Setup -->
            <?php if ($current_step == 1): ?>
                <h2 class="step-title">Step 1: Database Setup</h2>
                <p class="step-description">Choose how you'd like to set up your database:</p>

                <form method="POST">
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; margin-bottom: 15px;">
                            <div class="option-box" style="margin: 0;">
                                <input type="radio" name="db_method" value="create" checked>
                                <div class="option-title">Create New Database (Recommended)</div>
                                <div class="option-description">I'll create a new database for you automatically</div>
                            </div>
                        </label>

                        <label style="display: block;">
                            <div class="option-box" style="margin: 0;">
                                <input type="radio" name="db_method" value="existing">
                                <div class="option-title">Use Existing Database</div>
                                <div class="option-description">I already have a database ready (tables will be imported)</div>
                            </div>
                        </label>
                    </div>

                    <h3 style="margin-top: 30px; margin-bottom: 15px;">Database Connection Details</h3>

                    <div class="form-group">
                        <label>Database Host</label>
                        <input type="text" name="db_host" value="localhost" required>
                        <small style="color: #999;">Usually 'localhost' for shared hosting</small>
                    </div>

                    <div class="form-group">
                        <label>Database Username *</label>
                        <input type="text" name="db_user" placeholder="e.g., db_username" required>
                        <small style="color: #999;">Check your hosting control panel → Database Users</small>
                    </div>

                    <div class="form-group">
                        <label>Database Password</label>
                        <input type="password" name="db_pass" placeholder="Leave empty if no password">
                    </div>

                    <div class="form-group">
                        <label>Database Name *</label>
                        <input type="text" name="db_name" placeholder="e.g., document_signing" required>
                        <small style="color: #999;">Create this in your hosting control panel if using existing database</small>
                    </div>

                    <div class="button-group">
                        <button type="submit" formaction="setup.php?step=1" name="action" value="test_connection" class="btn-secondary">🔗 Test Connection</button>
                        <button type="submit" name="action" value="create_database" class="btn-primary" id="next_btn">Create Database →</button>
                    </div>

                    <script>
                        document.querySelectorAll('input[name="db_method"]').forEach(radio => {
                            radio.addEventListener('change', function() {
                                const nextBtn = document.getElementById('next_btn');
                                nextBtn.value = this.value === 'create' ? 'create_database' : 'import_database';
                                nextBtn.textContent = this.value === 'create' ? 'Create Database →' : 'Import Tables →';
                            });
                        });
                    </script>
                </form>

            <!-- STEP 2: Verification -->
            <?php elseif ($current_step == 2): ?>
                <h2 class="step-title">Step 2: Database Verified ✓</h2>
                <div class="success-message">
                    <strong>✓ Database connection successful!</strong><br>
                    Your database is ready for use.
                </div>

                <p class="step-description">Database Details:</p>
                <div class="code-box">
                    Host: <?php echo htmlspecialchars($db_config['host'] ?? 'localhost'); ?><br>
                    User: <?php echo htmlspecialchars($db_config['user'] ?? ''); ?><br>
                    Name: <?php echo htmlspecialchars($db_config['name'] ?? ''); ?>
                </div>

                <p class="step-description" style="margin-top: 30px;">Next, let's configure your application settings.</p>

                <form method="POST">
                    <input type="hidden" name="action" value="update_config">

                    <h3 style="margin-bottom: 15px;">Application Configuration</h3>

                    <div class="form-group">
                        <label>Website Base URL *</label>
                        <input type="url" name="base_url" value="http://localhost/document-signing/" placeholder="https://yoursite.com/document-signing/" required>
                        <small style="color: #999;">Where you'll access the system from</small>
                    </div>

                    <h3 style="margin: 25px 0 15px;">Email Configuration (Gmail Example)</h3>

                    <div class="form-group">
                        <label>SMTP Host</label>
                        <input type="text" name="smtp_host" value="smtp.gmail.com">
                        <small style="color: #999;">smtp.gmail.com for Gmail, smtp.office365.com for Outlook</small>
                    </div>

                    <div class="form-group">
                        <label>Email Address</label>
                        <input type="email" name="smtp_user" placeholder="your-email@gmail.com">
                    </div>

                    <div class="form-group">
                        <label>Email Password / App Password</label>
                        <input type="password" name="smtp_pass" placeholder="Gmail app password (not regular password)">
                        <small style="color: #999;">
                            For Gmail: Go to <a href="https://myaccount.google.com/security" target="_blank">myaccount.google.com/security</a> →
                            App passwords → Get 16-character code
                        </small>
                    </div>

                    <div class="form-group">
                        <label>Encryption Key (Auto-generated)</label>
                        <input type="text" name="encryption_key" value="<?php echo bin2hex(random_bytes(16)); ?>" readonly>
                        <small style="color: #999;">Randomly generated for security</small>
                    </div>

                    <div class="form-group">
                        <label>HMAC Key (Auto-generated)</label>
                        <input type="text" name="hmac_key" value="<?php echo bin2hex(random_bytes(16)); ?>" readonly>
                        <small style="color: #999;">Randomly generated for security</small>
                    </div>

                    <div class="button-group">
                        <button type="submit" class="btn-primary">Save Configuration →</button>
                    </div>
                </form>

            <!-- STEP 3: Configuration Saved -->
            <?php elseif ($current_step == 3): ?>
                <h2 class="step-title">Step 3: Configuration Saved ✓</h2>
                <div class="success-message">
                    <strong>✓ Configuration saved successfully!</strong><br>
                    Your system is now configured and ready to use.
                </div>

                <h3 style="margin: 30px 0 15px;">Next Steps:</h3>
                <ol style="line-height: 1.8; margin-left: 20px; color: #666;">
                    <li><strong>Download Required Libraries:</strong>
                        <ul style="margin-top: 8px; margin-left: 20px;">
                            <li>TCPDF (PDF generation): <a href="https://tcpdf.org/" target="_blank">https://tcpdf.org/</a></li>
                            <li>PHPMailer (Email): <a href="https://github.com/PHPMailer/PHPMailer" target="_blank">https://github.com/PHPMailer/PHPMailer</a></li>
                        </ul>
                    </li>
                    <li style="margin-top: 15px;"><strong>Extract to correct folders:</strong>
                        <div class="code-box">
TCPDF → /document-signing/TCPDF/<br>
PHPMailer → /document-signing/PHPMailer/
                        </div>
                    </li>
                    <li style="margin-top: 15px;"><strong>Create directories:</strong>
                        <div class="code-box">
uploads/<br>
uploads/pdfs/<br>
uploads/signatures/
                        </div>
                    </li>
                    <li style="margin-top: 15px;"><strong>Set file permissions:</strong>
                        <div class="code-box">
chmod 755 uploads/<br>
chmod 755 uploads/pdfs/<br>
chmod 755 uploads/signatures/
                        </div>
                    </li>
                </ol>

                <form method="POST" style="margin-top: 30px;">
                    <input type="hidden" name="action" value="complete_setup">
                    <div class="button-group">
                        <button type="submit" class="btn-primary">Complete Setup →</button>
                    </div>
                </form>

            <!-- STEP 4: Complete -->
            <?php elseif ($current_step == 4 || $setup_complete): ?>
                <h2 class="step-title">Setup Complete! 🎉</h2>
                <div class="success-message">
                    <strong>✓ Your Document Signing System is ready!</strong>
                </div>

                <h3 style="margin: 30px 0 15px;">Quick Links:</h3>
                <ul style="line-height: 2; margin-left: 20px; color: #666;">
                    <li><a href="login.php" style="color: #667eea; text-decoration: none;">📝 Go to Login Page →</a></li>
                    <li><a href="register.php" style="color: #667eea; text-decoration: none;">➕ Create Your First Account →</a></li>
                    <li><a href="README.md" style="color: #667eea; text-decoration: none;">📚 View Documentation →</a></li>
                </ul>

                <h3 style="margin: 30px 0 15px;">First Steps:</h3>
                <ol style="line-height: 1.8; margin-left: 20px; color: #666;">
                    <li>Click "Create Account" and register as admin</li>
                    <li>Log in with your credentials</li>
                    <li>Go to "Create Document" to start signing documents</li>
                    <li>Draw a signature and submit to generate PDF</li>
                    <li>Check your email for the signed document</li>
                </ol>

                <div style="background: #f0f7ff; border-left: 4px solid #667eea; padding: 15px; margin-top: 30px; border-radius: 5px;">
                    <strong>💡 Pro Tip:</strong> Keep the README.md and QUICK_START.md files handy for reference. They contain detailed setup and troubleshooting information.
                </div>

            <?php endif; ?>

            <div class="step-indicator">
                Step <?php echo $current_step; ?> of 4
            </div>
        </div>
    </div>
</body>
</html>
