<?php
/**
 * TellerPro — Premium Installation Wizard
 */

// Define basic constants if not already defined (we don't load config.php yet as it might not exist or be broken)
define('INSTALL_ROOT', __DIR__);
define('DEFAULT_APP_URL', (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]" . str_replace('install.php', '', $_SERVER['SCRIPT_NAME']));

session_start();

// Security Check: If already installed, don't allow access
if (file_exists(INSTALL_ROOT . '/.env') && file_exists(INSTALL_ROOT . '/storage/install.lock')) {
    die("TellerPro is already installed. For security, please delete install.php.");
}

$step = (int)($_GET['step'] ?? 1);
$error = '';
$success = '';

// --- Logic for Steps ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step === 2) {
        // Step 2: Database Connection Check
        $host = $_POST['db_host'] ?? '';
        $name = $_POST['db_name'] ?? '';
        $user = $_POST['db_user'] ?? '';
        $pass = $_POST['db_pass'] ?? '';
        $createDb = isset($_POST['create_database']) && $_POST['create_database'] === '1';
        $dropDb = isset($_POST['drop_database']) && $_POST['drop_database'] === '1';

        try {
            // First connect without database name to check credentials
            $pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_TIMEOUT => 5
            ]);

            // If drop database option is selected, drop and recreate
            if ($dropDb) {
                $pdo->exec("DROP DATABASE IF EXISTS `$name`");
                $pdo->exec("CREATE DATABASE `$name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            } elseif ($createDb) {
                // If create database option is selected, create the database
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            }

            // Now connect to the specific database
            $pdo = new PDO("mysql:host=$host;dbname=$name;charset=utf8mb4", $user, $pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_TIMEOUT => 5
            ]);

            $_SESSION['install_db'] = $_POST;
            header("Location: install.php?step=3");
            exit;
        } catch (PDOException $e) {
            $error = "Database connection failed: " . $e->getMessage();
        }
    } elseif ($step === 3) {
        // Step 3: Site Config
        $_SESSION['install_site'] = $_POST;
        header("Location: install.php?step=4");
        exit;
    } elseif ($step === 4) {
        // Step 4: Paystack Configuration
        $_SESSION['install_paystack'] = $_POST;
        header("Location: install.php?step=5");
        exit;
    } elseif ($step === 5) {
        // Step 5: Admin Account & Final Installation
        $admin = $_POST;
        $db_config = $_SESSION['install_db'] ?? [];
        $site_config = $_SESSION['install_site'] ?? [];
        $paystack_config = $_SESSION['install_paystack'] ?? [];

        if ($admin['password'] !== $admin['password_confirm']) {
            $error = "Passwords do not match.";
        } else {
            try {
                // 1. Establish database connection
                $pdo = new PDO("mysql:host={$db_config['db_host']};dbname={$db_config['db_name']};charset=utf8mb4", $db_config['db_user'], $db_config['db_pass'], [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
                ]);

                // 2. Drop all existing tables for fresh installation
                $dropDb = isset($db_config['drop_database']) && $db_config['drop_database'] === '1';
                if ($dropDb) {
                    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
                    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
                    foreach ($tables as $table) {
                        $pdo->exec("DROP TABLE IF EXISTS `$table`");
                    }
                    $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                }

                // 3. Import Schema
                $schemaFile = INSTALL_ROOT . '/database/schema.sql';
                if (!file_exists($schemaFile)) throw new Exception("Schema file not found.");

                $sql = file_get_contents($schemaFile);
                $pdo->exec($sql);

                // 3. Optional: Import seed/initial data
                $seedFile = INSTALL_ROOT . '/database/seed.sql';
                if (file_exists($seedFile)) {
                    $pdo->exec(file_get_contents($seedFile));
                }

                // 4. Create Super Admin
                $passHash = password_hash($admin['password'], PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO superadmins (name, username, email, password, is_active, created_at) VALUES (?, ?, ?, ?, 1, NOW())");
                $stmt->execute([$admin['name'], $admin['username'], $admin['email'], $passHash]);

                // 5. Generate .env file
                $envContent = <<<EOT
APP_NAME="{$site_config['app_name']}"
APP_ENV=production
APP_DEBUG=false
APP_URL="{$site_config['app_url']}"

DB_HOST="{$db_config['db_host']}"
DB_NAME="{$db_config['db_name']}"
DB_USER="{$db_config['db_user']}"
DB_PASS="{$db_config['db_pass']}"
DB_CHARSET=utf8mb4

TIMEZONE="{$site_config['timezone']}"
TRIAL_DAYS=14

PAYSTACK_ENVIRONMENT="live"
PAYSTACK_LIVE_PUBLIC_KEY="{$paystack_config['paystack_public_key']}"
PAYSTACK_LIVE_SECRET_KEY="{$paystack_config['paystack_secret_key']}"
PAYSTACK_CURRENCY="GHS"
EOT;
                file_put_contents(INSTALL_ROOT . '/.env', $envContent);

                // 6. Create lock file
                if (!is_dir(INSTALL_ROOT . '/storage')) mkdir(INSTALL_ROOT . '/storage', 0755, true);
                file_put_contents(INSTALL_ROOT . '/storage/install.lock', date('Y-m-d H:i:s'));

                header("Location: install.php?step=6");
                exit;

            } catch (Exception $e) {
                $error = "Installation failed: " . $e->getMessage();
            }
        }
    }
}

// --- Helper: Requirements Check ---
function checkRequirements() {
    return [
        'PHP Version >= 8.0' => version_compare(PHP_VERSION, '8.0.0', '>='),
        'PDO Extension'      => extension_loaded('pdo'),
        'OpenSSL Extension'  => extension_loaded('openssl'),
        'MBString Extension' => extension_loaded('mbstring'),
        'JSON Extension'     => extension_loaded('json'),
        'cURL Extension'     => extension_loaded('curl'),
        '.env Writable'      => is_writable(INSTALL_ROOT) || !file_exists(INSTALL_ROOT . '/.env'),
        'storage/ Writable'  => is_writable(INSTALL_ROOT . '/storage') || !is_dir(INSTALL_ROOT . '/storage'),
    ];
}

$reqs = checkRequirements();
$canProceed = !in_array(false, $reqs);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Install TellerPro SaaS</title>
    <style>
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --accent: #06b6d4;
            --success: #10b981;
            --danger: #ef4444;
            --bg-base: #f8fafc;
            --text-main: #1e293b;
            --text-muted: #64748b;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, #4f46e5 0%, #06b6d4 100%);
            color: var(--text-main);
            min-height: 100vh;
            display: flex; align-items: center; justify-content: center;
            padding: 20px;
        }

        .wizard-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            max-width: 550px;
            width: 100%;
            border-radius: 24px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
            overflow: hidden;
            animation: fadeIn 0.5s ease-out;
        }

        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }

        .wizard-header {
            background: white;
            padding: 40px 40px 20px;
            text-align: center;
        }

        .wizard-logo {
            width: 64px; height: 64px;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            border-radius: 16px;
            display: inline-flex; align-items: center; justify-content: center;
            margin-bottom: 20px;
            box-shadow: 0 10px 15px -3px rgba(99, 102, 241, 0.3);
        }

        .wizard-logo svg { width: 32px; height: 32px; color: white; }

        .wizard-header h1 { font-size: 24px; font-weight: 800; color: #0f172a; margin-bottom: 8px; }
        .wizard-header p { color: var(--text-muted); font-size: 14px; }

        .progress-steps {
            display: flex; justify-content: center; gap: 8px; margin: 20px 0;
        }

        .step-dot {
            width: 8px; height: 8px; border-radius: 50%; background: #e2e8f0; transition: all 0.3s;
        }
        .step-dot.active { background: var(--primary); width: 24px; border-radius: 4px; }
        .step-dot.completed { background: var(--success); }

        .wizard-body { padding: 0 40px 40px; }

        label { display: block; font-size: 13px; font-weight: 600; color: #475569; margin-bottom: 8px; }
        
        .form-control {
            width: 100%; padding: 12px 16px; 
            border: 2px solid #e2e8f0; border-radius: 12px;
            font-size: 14px; transition: border-color 0.2s;
            outline: none; margin-bottom: 20px;
        }
        .form-control:focus { border-color: var(--primary); }

        .requirements-list { list-style: none; margin-bottom: 24px; }
        .req-item {
            display: flex; align-items: center; justify-content: space-between;
            padding: 12px 0; border-bottom: 1px solid #f1f5f9; font-size: 14px;
        }
        .status-badge {
            padding: 4px 10px; border-radius: 99px; font-size: 11px; font-weight: 700;
        }
        .status-ok { background: #d1fae5; color: #065f46; }
        .status-fail { background: #fee2e2; color: #991b1b; }

        .alert {
            padding: 16px; border-radius: 12px; margin-bottom: 24px; font-size: 14px; line-height: 1.5;
        }
        .alert-danger { background: #fee2e2; border: 1px solid #fecaca; color: #991b1b; }
        .alert-success { background: #d1fae5; border: 1px solid #a7f3d0; color: #065f46; }

        .btn {
            width: 100%; padding: 14px; border-radius: 12px; border: none;
            font-size: 15px; font-weight: 700; cursor: pointer; transition: all 0.2s;
            display: flex; align-items: center; justify-content: center; gap: 8px;
        }
        .btn-primary { 
            background: linear-gradient(135deg, var(--primary), var(--primary-dark)); 
            color: white; box-shadow: 0 4px 6px -1px rgba(99, 102, 241, 0.2);
        }
        .btn-primary:hover { transform: translateY(-1px); box-shadow: 0 10px 15px -3px rgba(99, 102, 241, 0.3); }
        .btn-primary:active { transform: translateY(0); }
        .btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none !important; }

        .btn-outline { background: white; border: 2px solid #e2e8f0; color: #64748b; margin-top: 12px; }

        .footer-text { text-align: center; margin-top: 24px; color: var(--text-muted); font-size: 12px; }
    </style>
</head>
<body>

<div class="wizard-card">
    <div class="wizard-header">
        <div class="wizard-logo">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
        </div>
        <h1>TellerPro SaaS</h1>
        <p>Software Installation Wizard</p>

        <div class="progress-steps">
            <div class="step-dot <?php echo $step >= 1 ? ($step > 1 ? 'completed' : 'active') : ''; ?>"></div>
            <div class="step-dot <?php echo $step >= 2 ? ($step > 2 ? 'completed' : 'active') : ''; ?>"></div>
            <div class="step-dot <?php echo $step >= 3 ? ($step > 3 ? 'completed' : 'active') : ''; ?>"></div>
            <div class="step-dot <?php echo $step >= 4 ? ($step > 4 ? 'completed' : 'active') : ''; ?>"></div>
            <div class="step-dot <?php echo $step >= 5 ? ($step > 5 ? 'completed' : 'active') : ''; ?>"></div>
            <div class="step-dot <?php echo $step >= 6 ? 'active' : ''; ?>"></div>
        </div>
    </div>

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

        <?php if ($step === 1): ?>
            <h2 style="font-size: 18px; margin-bottom: 20px;">System Requirements</h2>
            <div class="requirements-list">
                <?php foreach ($reqs as $name => $passed): ?>
                <div class="req-item">
                    <span><?php echo $name; ?></span>
                    <span class="status-badge <?php echo $passed ? 'status-ok' : 'status-fail'; ?>">
                        <?php echo $passed ? '✓ Passed' : '✕ Failed'; ?>
                    </span>
                </div>
                <?php endforeach; ?>
            </div>
            
            <?php if (!$canProceed): ?>
                <div class="alert alert-danger" style="margin-top: 10px;">
                    Please resolve the red issues above to continue.
                </div>
            <?php endif; ?>

            <button onclick="location.href='install.php?step=2'" class="btn btn-primary" <?php echo !$canProceed ? 'disabled' : ''; ?>>
                Get Started
                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
            </button>

        <?php elseif ($step === 2): ?>
            <h2 style="font-size: 18px; margin-bottom: 20px;">Database Connection</h2>
            <form method="POST">
                <label>Database Host</label>
                <input type="text" name="db_host" class="form-control" value="localhost" placeholder="e.g. localhost or 127.0.0.1" required>

                <label>Database Name</label>
                <input type="text" name="db_name" class="form-control" value="tellerpro" placeholder="e.g. tellerpro" required>

                <label>Username</label>
                <input type="text" name="db_user" class="form-control" value="root" placeholder="e.g. root" required>

                <label>Password</label>
                <input type="password" name="db_pass" class="form-control" placeholder="Database password">

                <div style="margin-bottom: 20px; padding: 12px; background: #fee2e2; border: 1px solid #fecaca; border-radius: 8px;">
                    <label style="display: flex; align-items: center; cursor: pointer; margin-bottom: 0;">
                        <input type="checkbox" name="drop_database" value="1" style="width: 18px; height: 18px; margin-right: 10px; cursor: pointer;">
                        <span style="font-weight: 600; color: #991b1b;">Drop existing database (FRESH INSTALL)</span>
                    </label>
                    <p style="font-size: 12px; color: #991b1b; margin-top: 8px; margin-bottom: 0;">
                        ⚠️ WARNING: This will DELETE all existing data in the database. Use this only for a fresh installation.
                    </p>
                </div>

                <div style="margin-bottom: 20px; padding: 12px; background: #f0f8ff; border: 1px solid #b3d9ff; border-radius: 8px;">
                    <label style="display: flex; align-items: center; cursor: pointer; margin-bottom: 0;">
                        <input type="checkbox" name="create_database" value="1" style="width: 18px; height: 18px; margin-right: 10px; cursor: pointer;">
                        <span style="font-weight: 600; color: #0f172a;">Create database if it doesn't exist</span>
                    </label>
                    <p style="font-size: 12px; color: #64748b; margin-top: 8px; margin-bottom: 0;">
                        Check this box to automatically create the database. Your MySQL user must have CREATE DATABASE privileges.
                    </p>
                </div>

                <button type="submit" class="btn btn-primary">
                    Test Connection & Save
                </button>
                <button type="button" onclick="history.back()" class="btn btn-outline">Back</button>
            </form>

        <?php elseif ($step === 3): ?>
            <h2 style="font-size: 18px; margin-bottom: 20px;">App Configuration</h2>
            <form method="POST">
                <label>Application Name</label>
                <input type="text" name="app_name" class="form-control" value="TellerPro" required>
                
                <label>Application URL</label>
                <input type="text" name="app_url" class="form-control" value="<?php echo DEFAULT_APP_URL; ?>" required>

                <label>Timezone</label>
                <select name="timezone" class="form-control">
                    <option value="UTC">UTC</option>
                    <option value="Africa/Lagos">Africa/Lagos (Lagos)</option>
                    <option value="America/New_York">America/New_York (New York)</option>
                    <option value="Europe/London">Europe/London (London)</option>
                    <option value="Asia/Dubai">Asia/Dubai (Dubai)</option>
                </select>

                <button type="submit" class="btn btn-primary">Continue</button>
                <button type="button" onclick="history.back()" class="btn btn-outline">Back</button>
            </form>

        <?php elseif ($step === 4): ?>
            <h2 style="font-size: 18px; margin-bottom: 20px;">Paystack Payment Configuration</h2>
            <form method="POST">
                <div class="alert alert-success" style="font-size: 12px; margin-bottom: 20px;">
                    Configure your Paystack payment gateway for processing subscription payments. Get your keys from <a href="https://dashboard.paystack.com/" target="_blank" style="color: #059669; text-decoration: underline;">Paystack Dashboard</a> > Settings > API Keys.
                </div>

                <label>Paystack Public Key (Optional)</label>
                <input type="text" name="paystack_public_key" class="form-control" placeholder="pk_live_xxxxxxxxxxxx">

                <label>Paystack Secret Key (Optional)</label>
                <input type="password" name="paystack_secret_key" class="form-control" placeholder="sk_live_xxxxxxxxxxxx">

                <button type="submit" class="btn btn-primary">Continue</button>
                <button type="button" onclick="history.back()" class="btn btn-outline">Back</button>
            </form>

        <?php elseif ($step === 5): ?>
            <h2 style="font-size: 18px; margin-bottom: 20px;">Super Admin Setup</h2>
            <form method="POST">
                <label>Your Name</label>
                <input type="text" name="name" class="form-control" placeholder="e.g. John Doe" required>

                <label>Login Username</label>
                <input type="text" name="username" class="form-control" placeholder="e.g. admin" required minlength="4">
                
                <label>Email Address</label>
                <input type="email" name="email" class="form-control" placeholder="e.g. admin@tellerpro.com" required>

                <label>Password</label>
                <input type="password" name="password" class="form-control" placeholder="Minimum 8 characters" required minlength="8">

                <label>Confirm Password</label>
                <input type="password" name="password_confirm" class="form-control" required minlength="8">

                <div class="alert alert-success" style="font-size: 12px;">
                    This account will have full access to manage plans, tenants, and billing.
                </div>

                <button type="submit" class="btn btn-primary">Finish Installation</button>
                <button type="button" onclick="history.back()" class="btn btn-outline">Back</button>
            </form>

        <?php elseif ($step === 6): ?>
            <div style="text-align: center; padding: 20px 0;">
                <div style="width: 80px; height: 80px; background: #d1fae5; color: #059669; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; margin-bottom: 24px;">
                    <svg width="40" height="40" fill="none" stroke="currentColor" stroke-width="3" viewBox="0 0 24 24"><path d="M5 13l4 4L19 7"/></svg>
                </div>
                <h2 style="font-size: 24px; font-weight: 800; margin-bottom: 12px;">Installation Successful!</h2>
                <p style="color: var(--text-muted); margin-bottom: 30px;">TellerPro has been successfully configured. For security, please delete <code style="background: #f1f5f9; padding: 2px 4px; border-radius: 4px;">install.php</code> before proceeding.</p>
                
                <button onclick="location.href='index.php'" class="btn btn-primary">Launch Application</button>
            </div>
        <?php endif; ?>
        
        <p class="footer-text">TellerPro v2.0 • Secured Enterprise Deployment</p>
    </div>
</div>

</body>
</html>
