<?php
/**
 * RentRev AI - Web Installer
 * Creates config, sets up database, seeds roles/permissions/plans, creates admin user.
 */
session_start();
$step = $_GET['step'] ?? 1;
$errors = []; $success = '';

// If already installed, redirect
if (file_exists(__DIR__ . '/../config/config.php') && $step < 5) {
    // Allow reinstall only with ?force=1
    if (!isset($_GET['force'])) {
        echo '<!DOCTYPE html><html><head><title>Already Installed</title><script src="https://cdn.tailwindcss.com"></script><link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet"><style>body{font-family:"DM Sans",sans-serif}</style></head><body class="bg-gray-50 min-h-screen flex items-center justify-center"><div class="text-center"><h1 class="text-2xl font-bold text-gray-900">RentRev AI is already installed</h1><p class="text-gray-500 mt-2">To reinstall, add <code class="bg-gray-100 px-1 rounded">?force=1</code> to the URL.</p><a href="index.php" class="mt-4 inline-block px-5 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 text-sm font-medium">Go to App</a></div></body></html>';
        exit;
    }
}

// ============ STEP 2: Process DB + Admin form ============
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($step == 2 || $step == '2')) {
    $dbHost = trim($_POST['db_host'] ?? 'localhost');
    $dbName = trim($_POST['db_name'] ?? '');
    $dbUser = trim($_POST['db_user'] ?? '');
    $dbPass = $_POST['db_pass'] ?? '';
    $dbPort = trim($_POST['db_port'] ?? '3306');
    $adminFirst = trim($_POST['admin_first'] ?? '');
    $adminLast = trim($_POST['admin_last'] ?? '');
    $adminEmail = trim($_POST['admin_email'] ?? '');
    $adminPass = $_POST['admin_pass'] ?? '';
    $companyName = trim($_POST['company_name'] ?? 'My Property Co');
    $seedDemo = isset($_POST['seed_demo']);

    // Validate
    if (!$dbName) $errors[] = 'Database name is required.';
    if (!$dbUser) $errors[] = 'Database user is required.';
    if (!$adminEmail) $errors[] = 'Admin email is required.';
    if (!$adminPass || strlen($adminPass) < 8) $errors[] = 'Admin password must be at least 8 characters.';

    if (empty($errors)) {
        try {
            $pdo = new PDO("mysql:host=$dbHost;port=$dbPort;charset=utf8mb4", $dbUser, $dbPass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            ]);
            // Create database if not exists
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `$dbName`");

            // Run schema
            $schemaFile = __DIR__ . '/../database/schema.sql';
            if (!file_exists($schemaFile)) { $errors[] = 'schema.sql not found.'; }
            else {
                $sql = file_get_contents($schemaFile);
                $pdo->exec($sql);

                // Create company
                $stmt = $pdo->prepare("INSERT INTO companies (name, email, status, created_at, updated_at) VALUES (?, ?, 'active', NOW(), NOW())");
                $stmt->execute([$companyName, $adminEmail]);
                $companyId = $pdo->lastInsertId();

                // Seed default roles
                $roleIds = [];
                $defaultRoles = [
                    ['Super Admin', 'Full system access', 1],
                    ['Property Manager', 'Manage properties and tenants', 1],
                    ['Accountant', 'Financial operations', 1],
                    ['Maintenance Manager', 'Maintenance operations', 1],
                    ['Leasing Agent', 'Leasing operations', 1],
                    ['Viewer', 'Read-only access', 1],
                ];
                foreach ($defaultRoles as $r) {
                    $stmt = $pdo->prepare("INSERT INTO roles (company_id, name, description, is_system, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())");
                    $stmt->execute([$companyId, $r[0], $r[1], $r[2]]);
                    $roleIds[$r[0]] = $pdo->lastInsertId();
                }

                // Seed permissions
                $modules = [
                    'properties' => ['view_properties','create_properties','edit_properties','delete_properties'],
                    'units' => ['view_units','create_units','edit_units','delete_units'],
                    'tenants' => ['view_tenants','create_tenants','edit_tenants','delete_tenants'],
                    'owners' => ['view_owners','create_owners','edit_owners','delete_owners'],
                    'leases' => ['view_leases','create_leases','edit_leases','delete_leases'],
                    'payments' => ['view_payments','create_payments','edit_payments','delete_payments'],
                    'expenses' => ['view_expenses','create_expenses','edit_expenses','delete_expenses'],
                    'maintenance' => ['view_maintenance','create_maintenance','edit_maintenance','delete_maintenance'],
                    'vendors' => ['view_vendors','create_vendors','edit_vendors','delete_vendors'],
                    'documents' => ['view_documents','create_documents','edit_documents','delete_documents'],
                    'communications' => ['view_communications','create_communications'],
                    'leads' => ['view_leads','create_leads','edit_leads','delete_leads'],
                    'reports' => ['view_reports','export_reports'],
                    'settings' => ['view_settings','edit_settings'],
                    'users' => ['view_users','create_users','edit_users','delete_users'],
                    'roles' => ['view_roles','create_roles','edit_roles','delete_roles'],
                    'billing' => ['view_billing','manage_billing'],
                    'ai' => ['view_ai','configure_ai'],
                    'integrations' => ['view_integrations','configure_integrations'],
                    'api' => ['view_api','manage_api'],
                ];
                $allPermIds = [];
                foreach ($modules as $mod => $perms) {
                    foreach ($perms as $p) {
                        $label = ucwords(str_replace('_', ' ', $p));
                        $stmt = $pdo->prepare("INSERT INTO permissions (name, slug, module, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())");
                        $stmt->execute([$label, $p, $mod]);
                        $allPermIds[] = $pdo->lastInsertId();
                    }
                }

                // Give Super Admin all permissions
                foreach ($allPermIds as $pid) {
                    $pdo->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)")->execute([$roleIds['Super Admin'], $pid]);
                }

                // Create admin user
                $hash = password_hash($adminPass, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (company_id, role_id, first_name, last_name, email, password, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'active', NOW(), NOW())");
                $stmt->execute([$companyId, $roleIds['Super Admin'], $adminFirst ?: 'Admin', $adminLast ?: 'User', $adminEmail, $hash]);

                // Seed subscription plans
                $plans = [
                    ['Starter', 49.00, 50, 3, '{"basic_reports":true}'],
                    ['Professional', 149.00, 250, 10, '{"all_reports":true,"ai_basic":true,"api_access":true}'],
                    ['Enterprise', 399.00, 10000, 100, '{"all_reports":true,"ai_advanced":true,"api_access":true,"white_label":true}'],
                ];
                foreach ($plans as $pl) {
                    $pdo->prepare("INSERT INTO subscription_plans (name, price, max_units, max_users, features, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, NOW(), NOW())")->execute($pl);
                }

                // Seed default settings
                $defaults = [
                    'late_fee_amount' => '50', 'late_fee_days' => '5', 'late_fee_type' => 'flat',
                    'default_lease_term' => '12', 'email_notifications' => '1', 'sms_notifications' => '0',
                    'payment_gateway' => 'none', 'timezone' => 'America/New_York',
                    'date_format' => 'm/d/Y', 'currency' => 'USD',
                ];
                foreach ($defaults as $k => $val) {
                    $pdo->prepare("INSERT INTO settings (company_id, setting_key, setting_value, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())")->execute([$companyId, $k, $val]);
                }

                // Demo data
                if ($seedDemo) {
                    // Sample properties
                    $props = [
                        ['Sunset Apartments', 'apartment', '123 Sunset Blvd', 'Los Angeles', 'CA', '90028', 12],
                        ['Oakwood Townhomes', 'townhouse', '456 Oak Dr', 'Austin', 'TX', '78701', 8],
                        ['Pine Ridge Office', 'commercial', '789 Pine St', 'Denver', 'CO', '80202', 6],
                    ];
                    foreach ($props as $pr) {
                        $pdo->prepare("INSERT INTO properties (company_id, name, type, address, city, state, zip, total_units, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW(), NOW())")->execute([$companyId, $pr[0], $pr[1], $pr[2], $pr[3], $pr[4], $pr[5], $pr[6]]);
                        $propId = $pdo->lastInsertId();
                        // Create units
                        for ($i = 1; $i <= min($pr[6], 4); $i++) {
                            $rent = rand(95, 250) * 10;
                            $status = $i <= 3 ? 'occupied' : 'vacant';
                            $pdo->prepare("INSERT INTO units (company_id, property_id, unit_number, bedrooms, bathrooms, sqft, market_rent, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())")->execute([$companyId, $propId, $pr[1] === 'commercial' ? "Suite $i" : "Unit $i"."0".(string)($i), rand(1,3), rand(1,2), rand(600,1800), $rent, $status]);
                        }
                    }

                    // Sample vendors
                    $vendors = [
                        ['FastFix Plumbing', 'plumbing', 'Joe Fix', 'joe@fastfix.com', '555-0101'],
                        ['BrightSpark Electric', 'electrical', 'Sarah Spark', 'sarah@brightspark.com', '555-0102'],
                        ['GreenThumb Landscaping', 'landscaping', 'Tom Green', 'tom@greenthumb.com', '555-0103'],
                    ];
                    foreach ($vendors as $vn) {
                        $pdo->prepare("INSERT INTO vendors (company_id, company_name, specialty, contact_name, email, phone, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'active', NOW(), NOW())")->execute([$companyId, $vn[0], $vn[1], $vn[2], $vn[3], $vn[4]]);
                    }
                }

                // Write config file
                $configContent = "<?php\n";
                $configContent .= "// RentRev AI Configuration - Auto-generated " . date('Y-m-d H:i:s') . "\n\n";
                $configContent .= "// Database\n";
                $configContent .= "define('DB_HOST', " . var_export($dbHost, true) . ");\n";
                $configContent .= "define('DB_PORT', " . var_export($dbPort, true) . ");\n";
                $configContent .= "define('DB_NAME', " . var_export($dbName, true) . ");\n";
                $configContent .= "define('DB_USER', " . var_export($dbUser, true) . ");\n";
                $configContent .= "define('DB_PASS', " . var_export($dbPass, true) . ");\n\n";
                $configContent .= "// Application\n";
                $configContent .= "define('APP_NAME', 'RentRev AI');\n";
                $configContent .= "define('APP_URL', '" . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . "');\n";
                $configContent .= "define('APP_PATH', __DIR__ . '/../app');\n";
                $configContent .= "define('APP_DEBUG', false);\n";
                $configContent .= "define('APP_VERSION', '1.0.0');\n";
                $configContent .= "define('APP_TIMEZONE', 'America/New_York');\n\n";
                $configContent .= "// Security\n";
                $configContent .= "define('CSRF_TOKEN_NAME', 'csrf_token');\n";
                $configContent .= "define('SESSION_LIFETIME', 7200);\n";
                $configContent .= "define('MAX_LOGIN_ATTEMPTS', 5);\n";
                $configContent .= "define('LOGIN_LOCKOUT_TIME', 900);\n\n";
                $configContent .= "// Uploads\n";
                $configContent .= "define('UPLOAD_PATH', __DIR__ . '/../storage/uploads');\n";
                $configContent .= "define('MAX_UPLOAD_SIZE', 10 * 1024 * 1024);\n\n";
                $configContent .= "// Pagination\n";
                $configContent .= "define('ITEMS_PER_PAGE', 25);\n";

                $configDir = __DIR__ . '/../config';
                if (!is_dir($configDir)) mkdir($configDir, 0755, true);
                file_put_contents($configDir . '/config.php', $configContent);

                // Create storage directories
                $dirs = ['/../storage/uploads', '/../storage/logs', '/../storage/cache'];
                foreach ($dirs as $d) { $dir = __DIR__ . $d; if (!is_dir($dir)) mkdir($dir, 0755, true); }

                $step = 3;
                $success = 'Installation complete!';
            }
        } catch (PDOException $e) {
            $errors[] = 'Database error: ' . $e->getMessage();
        } catch (Exception $e) {
            $errors[] = 'Error: ' . $e->getMessage();
        }
    }
}

// ============ System Requirements Check ============
$checks = [
    'PHP 8.0+' => version_compare(PHP_VERSION, '8.0.0', '>='),
    'PDO MySQL' => extension_loaded('pdo_mysql'),
    'mbstring' => extension_loaded('mbstring'),
    'JSON' => extension_loaded('json'),
    'OpenSSL' => extension_loaded('openssl'),
    'FileInfo' => extension_loaded('fileinfo'),
    'Config dir writable' => is_writable(__DIR__ . '/../config') || is_writable(__DIR__ . '/..'),
];
$allPassed = !in_array(false, $checks);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Install - RentRev AI</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>body{font-family:'DM Sans',sans-serif}</style>
</head>
<body class="bg-gray-50 min-h-screen">
<div class="max-w-2xl mx-auto py-12 px-4">
    <!-- Header -->
    <div class="text-center mb-8">
        <div class="inline-flex items-center gap-2 mb-3">
            <div class="w-10 h-10 bg-indigo-600 rounded-xl flex items-center justify-center"><svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg></div>
            <span class="text-2xl font-bold text-gray-900">RentRev AI</span>
        </div>
        <p class="text-gray-500">Installation Wizard</p>
    </div>

    <!-- Steps -->
    <div class="flex items-center justify-center mb-8 gap-0">
        <?php for ($s = 1; $s <= 3; $s++): $active = $step == $s; $done = $step > $s; ?>
            <div class="flex items-center <?= $s < 3 ? '' : '' ?>">
                <div class="w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium <?= $done ? 'bg-green-500 text-white' : ($active ? 'bg-indigo-600 text-white' : 'bg-gray-200 text-gray-500') ?>">
                    <?= $done ? '✓' : $s ?>
                </div>
                <span class="ml-2 text-sm <?= $active ? 'font-semibold text-gray-900' : 'text-gray-500' ?>"><?= ['','Requirements','Configure','Done'][$s] ?></span>
                <?php if ($s < 3): ?><div class="w-12 h-px bg-gray-300 mx-3"></div><?php endif; ?>
            </div>
        <?php endfor; ?>
    </div>

    <?php if ($errors): ?><div class="bg-red-50 border border-red-200 text-red-700 rounded-xl p-4 mb-6 text-sm"><?php foreach ($errors as $e): ?><p>• <?= htmlspecialchars($e) ?></p><?php endforeach; ?></div><?php endif; ?>

    <?php if ($step == 1): ?>
    <!-- STEP 1: System Requirements -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
        <h2 class="text-lg font-bold text-gray-900 mb-4">System Requirements</h2>
        <div class="space-y-3">
            <?php foreach ($checks as $label => $pass): ?>
                <div class="flex items-center justify-between py-2 border-b border-gray-50">
                    <span class="text-sm text-gray-700"><?= $label ?></span>
                    <span class="text-sm font-medium <?= $pass ? 'text-green-600' : 'text-red-600' ?>"><?= $pass ? '✓ Pass' : '✗ Fail' ?></span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php if ($allPassed): ?>
        <a href="?step=2<?= isset($_GET['force']) ? '&force=1' : '' ?>" class="block w-full text-center px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 font-medium">Continue to Setup</a>
    <?php else: ?>
        <p class="text-center text-red-600 text-sm">Please fix the failing requirements before continuing.</p>
    <?php endif; ?>

    <?php elseif ($step == 2): ?>
    <!-- STEP 2: Database & Admin -->
    <form method="POST" action="?step=2<?= isset($_GET['force']) ? '&force=1' : '' ?>" class="space-y-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-900 mb-4">Database Configuration</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Host</label><input type="text" name="db_host" value="localhost" required class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Port</label><input type="text" name="db_port" value="3306" required class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Database Name <span class="text-red-500">*</span></label><input type="text" name="db_name" value="rentrev" required class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Username <span class="text-red-500">*</span></label><input type="text" name="db_user" value="" required class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
                <div class="md:col-span-2"><label class="block text-sm font-medium text-gray-700 mb-1">Password</label><input type="password" name="db_pass" value="" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-900 mb-4">Admin Account</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div><label class="block text-sm font-medium text-gray-700 mb-1">First Name</label><input type="text" name="admin_first" value="Admin" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Last Name</label><input type="text" name="admin_last" value="User" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Email <span class="text-red-500">*</span></label><input type="email" name="admin_email" value="" required class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Password <span class="text-red-500">*</span> (min 8 chars)</label><input type="password" name="admin_pass" value="" required minlength="8" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 class="text-lg font-bold text-gray-900 mb-4">Company</h2>
            <div><label class="block text-sm font-medium text-gray-700 mb-1">Company Name</label><input type="text" name="company_name" value="My Property Co" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500"></div>
            <label class="flex items-center gap-2 mt-4"><input type="checkbox" name="seed_demo" checked class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"><span class="text-sm text-gray-700">Seed demo data (sample properties, units, vendors)</span></label>
        </div>

        <button type="submit" class="w-full px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 font-medium">Install RentRev AI</button>
    </form>

    <?php elseif ($step == 3): ?>
    <!-- STEP 3: Done -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-8 text-center">
        <div class="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4"><svg class="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg></div>
        <h2 class="text-2xl font-bold text-gray-900 mb-2">Installation Complete!</h2>
        <p class="text-gray-500 mb-6">RentRev AI has been installed and configured successfully.</p>
        <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6 text-left text-sm text-amber-800">
            <p class="font-semibold mb-1">Security Reminder:</p>
            <p>Delete or rename this <code class="bg-amber-100 px-1 rounded">install.php</code> file to prevent unauthorized reinstallation.</p>
        </div>
        <a href="index.php?page=login" class="inline-flex px-8 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 font-medium">Launch RentRev AI →</a>
    </div>
    <?php endif; ?>

    <p class="text-center text-xs text-gray-400 mt-8">RentRev AI v1.0.0</p>
</div>
</body>
</html>
