<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Database Installation - MAFIA MAILER</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .install-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 600px;
            width: 100%;
            overflow: hidden;
        }
        
        .install-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px 30px;
            text-align: center;
        }
        
        .install-header h1 {
            font-size: 32px;
            margin-bottom: 10px;
            font-weight: 700;
        }
        
        .install-header p {
            font-size: 16px;
            opacity: 0.9;
        }
        
        .install-body {
            padding: 40px 30px;
        }
        
        .form-section {
            margin-bottom: 30px;
        }
        
        .form-section h2 {
            font-size: 18px;
            color: #2d3748;
            margin-bottom: 15px;
            font-weight: 600;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #4a5568;
            font-weight: 500;
            font-size: 14px;
        }
        
        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .form-help {
            font-size: 12px;
            color: #718096;
            margin-top: 5px;
        }
        
        .btn-install {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }
        
        .btn-install:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }
        
        .btn-install:active {
            transform: translateY(0);
        }
        
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .alert-error {
            background: #fed7d7;
            color: #c53030;
            border: 1px solid #fc8181;
        }
        
        .alert-success {
            background: #c6f6d5;
            color: #2f855a;
            border: 1px solid #9ae6b4;
        }
        
        .install-footer {
            background: #f7fafc;
            padding: 20px 30px;
            text-align: center;
            color: #718096;
            font-size: 13px;
        }
    </style>
</head>
<body>
    <div class="install-container">
        <div class="install-header">
            <h1>🚀 Database Installation</h1>
            <p>Welcome to MAFIA MAILER - Professional Email Marketing System</p>
        </div>
        
        <div class="install-body">
            <?php
            // Handle installation
            if (isset($_POST['do_install'])) {
                $db_host = trim($_POST['db_host'] ?? '');
                $db_name = trim($_POST['db_name'] ?? '');
                $db_user = trim($_POST['db_user'] ?? '');
                $db_pass = $_POST['db_pass'] ?? '';
                $admin_username = trim($_POST['admin_username'] ?? '');
                $admin_password = $_POST['admin_password'] ?? '';
                $admin_password_confirm = $_POST['admin_password_confirm'] ?? '';
                
                $errors = [];
                
                // Validate inputs
                if (empty($db_host)) $errors[] = "Database host is required";
                if (empty($db_name)) $errors[] = "Database name is required";
                if (empty($db_user)) $errors[] = "Database username is required";
                if (empty($admin_username)) $errors[] = "Admin username is required";
                if (empty($admin_password)) $errors[] = "Admin password is required";
                if ($admin_password !== $admin_password_confirm) $errors[] = "Admin passwords do not match";
                if (strlen($admin_password) < 6) $errors[] = "Admin password must be at least 6 characters";
                
                if (empty($errors)) {
                    // Test database connection
                    try {
                        $testPdo = new PDO(
                            "mysql:host={$db_host};dbname={$db_name};charset=utf8mb4",
                            $db_user,
                            $db_pass,
                            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                        );
                        
                        // Create necessary tables
                        $testPdo->exec("
                            CREATE TABLE IF NOT EXISTS sending_profiles (
                                id INT AUTO_INCREMENT PRIMARY KEY,
                                profile_name VARCHAR(255) NOT NULL,
                                from_email VARCHAR(255) NOT NULL,
                                sender_name VARCHAR(255) DEFAULT '',
                                type ENUM('smtp','api') DEFAULT 'smtp',
                                host VARCHAR(255) DEFAULT '',
                                port INT DEFAULT 587,
                                username VARCHAR(255) DEFAULT '',
                                password VARCHAR(255) DEFAULT '',
                                api_url VARCHAR(500) DEFAULT '',
                                api_key VARCHAR(500) DEFAULT '',
                                headers_json TEXT,
                                active TINYINT(1) DEFAULT 1,
                                connection_numbers INT DEFAULT 5,
                                batch_size INT DEFAULT 50,
                                send_rate INT DEFAULT 0,
                                sends_used INT DEFAULT 0,
                                workers INT DEFAULT 4,
                                messages_per_worker INT DEFAULT 100,
                                bounce_imap_server VARCHAR(255) DEFAULT '',
                                bounce_imap_user VARCHAR(255) DEFAULT '',
                                bounce_imap_pass VARCHAR(255) DEFAULT '',
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                        ");
                        
                        $testPdo->exec("
                            CREATE TABLE IF NOT EXISTS campaigns (
                                id INT AUTO_INCREMENT PRIMARY KEY,
                                name VARCHAR(255) NOT NULL,
                                subject VARCHAR(500) DEFAULT '',
                                preheader VARCHAR(255) DEFAULT '',
                                from_email VARCHAR(255) DEFAULT '',
                                sender_name VARCHAR(255) DEFAULT '',
                                html LONGTEXT,
                                status VARCHAR(50) DEFAULT 'draft',
                                total_recipients INT DEFAULT 0,
                                unsubscribe_enabled TINYINT(1) DEFAULT 0,
                                progress_sent INT DEFAULT 0,
                                progress_total INT DEFAULT 0,
                                progress_status VARCHAR(50) DEFAULT 'draft',
                                sent_at TIMESTAMP NULL,
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                        ");
                        
                        $testPdo->exec("
                            CREATE TABLE IF NOT EXISTS events (
                                id INT AUTO_INCREMENT PRIMARY KEY,
                                campaign_id INT NOT NULL,
                                event_type VARCHAR(50) NOT NULL,
                                details TEXT,
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                INDEX(campaign_id),
                                INDEX(event_type)
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                        ");
                        
                        $testPdo->exec("
                            CREATE TABLE IF NOT EXISTS rotation_settings (
                                id INT PRIMARY KEY DEFAULT 1,
                                rotation_enabled TINYINT(1) DEFAULT 0,
                                target_per_minute INT DEFAULT 1000,
                                batch_size INT DEFAULT 1,
                                workers INT DEFAULT 4,
                                messages_per_worker INT DEFAULT 100
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                        ");
                        
                        $testPdo->exec("INSERT IGNORE INTO rotation_settings (id) VALUES (1)");
                        
                        $testPdo->exec("
                            CREATE TABLE IF NOT EXISTS contact_lists (
                                id INT AUTO_INCREMENT PRIMARY KEY,
                                name VARCHAR(255) NOT NULL,
                                type ENUM('global','list') NOT NULL DEFAULT 'list',
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                        ");
                        
                        $testPdo->exec("
                            CREATE TABLE IF NOT EXISTS contacts (
                                id INT AUTO_INCREMENT PRIMARY KEY,
                                list_id INT NOT NULL,
                                email VARCHAR(255) NOT NULL,
                                first_name VARCHAR(100) DEFAULT NULL,
                                last_name VARCHAR(100) DEFAULT NULL,
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                INDEX(list_id),
                                INDEX(email)
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                        ");
                        
                        $testPdo->exec("
                            CREATE TABLE IF NOT EXISTS unsubscribes (
                                email VARCHAR(255) PRIMARY KEY,
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                        ");
                        
                        // Create config.php file
                        $admin_password_hash = password_hash($admin_password, PASSWORD_DEFAULT);
                        $configContent = "<?php\n";
                        $configContent .= "/**\n";
                        $configContent .= " * Configuration file for MAFIA MAILER\n";
                        $configContent .= " * Generated on " . date('Y-m-d H:i:s') . "\n";
                        $configContent .= " */\n\n";
                        $configContent .= "// Database configuration\n";
                        $configContent .= "define('DB_HOST', " . var_export($db_host, true) . ");\n";
                        $configContent .= "define('DB_NAME', " . var_export($db_name, true) . ");\n";
                        $configContent .= "define('DB_USER', " . var_export($db_user, true) . ");\n";
                        $configContent .= "define('DB_PASS', " . var_export($db_pass, true) . ");\n\n";
                        $configContent .= "// Installation status\n";
                        $configContent .= "define('INSTALLED', true);\n\n";
                        $configContent .= "// Admin credentials\n";
                        $configContent .= "define('ADMIN_USERNAME', " . var_export($admin_username, true) . ");\n";
                        $configContent .= "define('ADMIN_PASSWORD_HASH', " . var_export($admin_password_hash, true) . ");\n";
                        
                        $configFile = __DIR__ . '/config.php';
                        if (file_put_contents($configFile, $configContent) === false) {
                            $errors[] = "Failed to create config.php file. Please check write permissions.";
                        } else {
                            // Installation successful
                            echo '<div class="alert alert-success">';
                            echo '<strong>✅ Installation Successful!</strong><br>';
                            echo 'Your database has been configured and all tables have been created.<br>';
                            echo 'Redirecting to login page...';
                            echo '</div>';
                            echo '<script>setTimeout(function(){ window.location.href = "' . $_SERVER['SCRIPT_NAME'] . '?action=login"; }, 2000);</script>';
                            exit;
                        }
                    } catch (PDOException $e) {
                        $errors[] = "Database connection failed: " . $e->getMessage();
                    } catch (Exception $e) {
                        $errors[] = "Installation error: " . $e->getMessage();
                    }
                }
                
                if (!empty($errors)) {
                    echo '<div class="alert alert-error">';
                    echo '<strong>⚠️ Installation Errors:</strong><ul style="margin-top:10px; padding-left:20px;">';
                    foreach ($errors as $error) {
                        echo '<li>' . htmlspecialchars($error) . '</li>';
                    }
                    echo '</ul></div>';
                }
            }
            ?>
            
            <form method="POST" action="">
                <div class="form-section">
                    <h2>📊 Database Configuration</h2>
                    <p style="color: #718096; font-size: 14px; margin-bottom: 15px;">
                        Please provide your MySQL database credentials. Make sure the database already exists.
                    </p>
                    
                    <div class="form-group">
                        <label for="db_host">Database Host</label>
                        <input type="text" id="db_host" name="db_host" value="<?php echo isset($_POST['db_host']) ? htmlspecialchars($_POST['db_host']) : 'localhost'; ?>" required>
                        <div class="form-help">Usually "localhost" or your server's IP address</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="db_name">Database Name</label>
                        <input type="text" id="db_name" name="db_name" value="<?php echo isset($_POST['db_name']) ? htmlspecialchars($_POST['db_name']) : ''; ?>" required>
                        <div class="form-help">The name of your MySQL database</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="db_user">Database Username</label>
                        <input type="text" id="db_user" name="db_user" value="<?php echo isset($_POST['db_user']) ? htmlspecialchars($_POST['db_user']) : ''; ?>" required>
                        <div class="form-help">MySQL username with full privileges</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="db_pass">Database Password</label>
                        <input type="password" id="db_pass" name="db_pass" value="<?php echo isset($_POST['db_pass']) ? htmlspecialchars($_POST['db_pass']) : ''; ?>">
                        <div class="form-help">MySQL password (leave blank if none)</div>
                    </div>
                </div>
                
                <div class="form-section">
                    <h2>🔐 Admin Account</h2>
                    <p style="color: #718096; font-size: 14px; margin-bottom: 15px;">
                        Create your admin account to access the system.
                    </p>
                    
                    <div class="form-group">
                        <label for="admin_username">Admin Username</label>
                        <input type="text" id="admin_username" name="admin_username" value="<?php echo isset($_POST['admin_username']) ? htmlspecialchars($_POST['admin_username']) : 'admin'; ?>" required>
                        <div class="form-help">Choose a username for admin access</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="admin_password">Admin Password</label>
                        <input type="password" id="admin_password" name="admin_password" required>
                        <div class="form-help">Minimum 6 characters</div>
                    </div>
                    
                    <div class="form-group">
                        <label for="admin_password_confirm">Confirm Password</label>
                        <input type="password" id="admin_password_confirm" name="admin_password_confirm" required>
                        <div class="form-help">Re-enter your password</div>
                    </div>
                </div>
                
                <button type="submit" name="do_install" class="btn-install">
                    🚀 Install MAFIA MAILER
                </button>
            </form>
        </div>
        
        <div class="install-footer">
            MAFIA MAILER - Professional Email Marketing System<br>
            © <?php echo date('Y'); ?> All rights reserved
        </div>
    </div>
</body>
</html>
