<?php
/**
 * Fouad AI Photo Editor - Installation Wizard
 * Run this once to set up the application
 */

$steps = [];
$errors = [];
$success = false;

// ─── Step 1: Check Requirements ───
$phpVersion = phpversion();
$phpOk = version_compare($phpVersion, '8.0', '>=');
$pdoOk = extension_loaded('pdo_sqlite');
$curlOk = extension_loaded('curl');
$jsonOk = extension_loaded('json');
$gdOk = extension_loaded('gd');
$mbstringOk = extension_loaded('mbstring');

$steps[] = [
    'title' => 'فحص المتطلبات',
    'items' => [
        ['PHP ≥ 8.0', $phpOk, "الإصدار الحالي: $phpVersion"],
        ['PDO SQLite', $pdoOk, 'لازم لقاعدة البيانات'],
        ['cURL', $curlOk, 'لازم للاتصال بـ AI API'],
        ['JSON', $jsonOk, 'لازم لمعالجة البيانات'],
        ['GD', $gdOk, 'لازم لضغط الصور (اختياري)'],
        ['MBString', $mbstringOk, 'لازم للنصوص العربية'],
    ]
];

$allRequirementsOk = $phpOk && $pdoOk && $curlOk && $jsonOk;

// ─── Step 2: Handle Form Submission ───
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $zaiBaseUrl = trim($_POST['zai_base_url'] ?? '');
    $zaiApiKey = trim($_POST['zai_api_key'] ?? '');
    $adminPassword = trim($_POST['admin_password'] ?? '');
    $adminPassword2 = trim($_POST['admin_password2'] ?? '');
    $appUrl = trim($_POST['app_url'] ?? '');

    if (empty($zaiBaseUrl)) $errors[] = 'رابط Z-AI API مطلوب';
    if (empty($zaiApiKey)) $errors[] = 'مفتاح Z-AI API مطلوب';
    if (strlen($adminPassword) < 6) $errors[] = 'كلمة مرور المدير يجب أن تكون 6 أحرف على الأقل';
    if ($adminPassword !== $adminPassword2) $errors[] = 'كلمتا المرور غير متطابقتين';
    if (empty($appUrl)) $appUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];

    if (empty($errors)) {
        // Generate secret
        $secret = bin2hex(random_bytes(32));

        // Write config.php
        $configContent = "<?php\n";
        $configContent .= "/**\n * Fouad AI Photo Editor - Configuration\n * Generated by install.php on " . date('Y-m-d H:i:s') . "\n */\n\n";
        $configContent .= "define('DB_PATH', __DIR__ . '/data/database.sqlite');\n";
        $configContent .= "define('ZAI_BASE_URL', " . var_export($zaiBaseUrl, true) . ");\n";
        $configContent .= "define('ZAI_API_KEY', " . var_export($zaiApiKey, true) . ");\n";
        $configContent .= "define('APP_SECRET', " . var_export($secret, true) . ");\n";
        $configContent .= "define('APP_URL', " . var_export($appUrl, true) . ");\n";
        $configContent .= "define('MAX_UPLOAD_SIZE', 10 * 1024 * 1024);\n";
        $configContent .= "define('MAX_BANNER_SIZE', 2 * 1024 * 1024);\n";
        $configContent .= "define('ALLOWED_IMAGE_TYPES', ['image/png', 'image/jpeg', 'image/webp']);\n";
        $configContent .= "define('SESSION_LIFETIME', 24 * 60 * 60);\n";

        if (file_put_contents(__DIR__ . '/config.php', $configContent) === false) {
            $errors[] = 'فشل في كتابة ملف config.php. تحقق من صلاحيات الكتابة.';
        } else {
            // Initialize database
            require_once __DIR__ . '/includes/Database.php';
            require_once __DIR__ . '/includes/Auth.php';
            Database::initSchema();
            Auth::createDefaultAdmin($adminPassword);

            // Create upload directories
            $dirs = ['public/uploads', 'public/banners', 'public/generated', 'public/edited', 'data/jobs'];
            foreach ($dirs as $dir) {
                $fullPath = __DIR__ . '/' . $dir;
                if (!is_dir($fullPath)) {
                    mkdir($fullPath, 0755, true);
                }
            }

            // Protect data directory
            $htaccess = "Deny from all\n";
            file_put_contents(__DIR__ . '/data/.htaccess', $htaccess);

            $success = true;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تثبيت محرر الصور Fouad AI</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Tajawal', system-ui, sans-serif; }
        .glass { background: rgba(255,255,255,0.03); backdrop-filter: blur(20px); border: 1px solid rgba(255,255,255,0.1); }
        .gradient-text { background: linear-gradient(to right, #34d399, #22d3ee); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
    </style>
</head>
<body class="bg-gray-950 text-white min-h-screen flex items-center justify-center p-4">

<?php if ($success): ?>
    <div class="max-w-md w-full">
        <div class="glass rounded-2xl p-8 text-center">
            <div class="text-6xl mb-4">✅</div>
            <h1 class="text-2xl font-bold gradient-text mb-4">تم التثبيت بنجاح!</h1>
            <div class="text-sm text-gray-400 space-y-2 mb-6 text-right">
                <p>✓ تم إنشاء قاعدة البيانات</p>
                <p>✓ تم إنشاء حساب المدير (admin)</p>
                <p>✓ تم حفظ الإعدادات</p>
            </div>
            <div class="glass rounded-xl p-4 mb-6 text-right">
                <p class="text-sm text-yellow-400 mb-2">⚠️ احذف ملف install.php بعد الانتهاء</p>
                <p class="text-xs text-gray-500">rm install.php</p>
            </div>
            <a href="index.php" class="block w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-3 rounded-xl transition-colors">
                فتح التطبيق ←
            </a>
        </div>
    </div>
<?php else: ?>
    <div class="max-w-lg w-full">
        <div class="text-center mb-8">
            <h1 class="text-3xl font-bold gradient-text mb-2">محرر الصور Fouad AI</h1>
            <p class="text-gray-400">معالج التثبيت</p>
        </div>

        <!-- Requirements Check -->
        <div class="glass rounded-2xl p-6 mb-6">
            <h2 class="text-lg font-bold mb-4">📋 فحص المتطلبات</h2>
            <div class="space-y-2">
                <?php foreach ($steps[0]['items'] as $item): ?>
                    <div class="flex items-center justify-between p-2 rounded-lg <?= $item[1] ? 'bg-emerald-500/10' : 'bg-red-500/10' ?>">
                        <div class="flex items-center gap-2">
                            <span class="text-lg"><?= $item[1] ? '✅' : '❌' ?></span>
                            <span class="font-medium"><?= $item[0] ?></span>
                        </div>
                        <span class="text-xs text-gray-400"><?= $item[2] ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php if (!$allRequirementsOk): ?>
                <div class="mt-4 p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm text-center">
                    بعض المتطلبات غير متوفرة. يرجى تثبيتها أولاً.
                </div>
            <?php endif; ?>
        </div>

        <?php if ($allRequirementsOk): ?>
        <!-- Configuration Form -->
        <form method="POST" class="glass rounded-2xl p-6 space-y-4">
            <h2 class="text-lg font-bold mb-2">⚙️ إعداد التطبيق</h2>

            <?php if (!empty($errors)): ?>
                <div class="p-3 bg-red-500/10 border border-red-500/20 rounded-lg">
                    <?php foreach ($errors as $error): ?>
                        <p class="text-red-400 text-sm">• <?= htmlspecialchars($error) ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <div>
                <label class="block text-sm font-medium mb-1">رابط Z-AI API Base URL</label>
                <input type="url" name="zai_base_url" required placeholder="https://api.example.com"
                    value="<?= htmlspecialchars($_POST['zai_base_url'] ?? '') ?>"
                    dir="ltr" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-emerald-500 focus:outline-none">
            </div>

            <div>
                <label class="block text-sm font-medium mb-1">مفتاح Z-AI API Key</label>
                <input type="text" name="zai_api_key" required placeholder="sk-xxxxxxxxxxxxxxxx"
                    value="<?= htmlspecialchars($_POST['zai_api_key'] ?? '') ?>"
                    dir="ltr" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-emerald-500 focus:outline-none">
            </div>

            <div>
                <label class="block text-sm font-medium mb-1">رابط التطبيق (اختياري)</label>
                <input type="url" name="app_url" placeholder="https://your-domain.com"
                    value="<?= htmlspecialchars($_POST['app_url'] ?? '') ?>"
                    dir="ltr" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-emerald-500 focus:outline-none">
            </div>

            <hr class="border-white/10">

            <div>
                <label class="block text-sm font-medium mb-1">كلمة مرور المدير</label>
                <input type="password" name="admin_password" required minlength="6" placeholder="6 أحرف على الأقل"
                    class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-emerald-500 focus:outline-none">
            </div>

            <div>
                <label class="block text-sm font-medium mb-1">تأكيد كلمة المرور</label>
                <input type="password" name="admin_password2" required minlength="6" placeholder="أعد كتابة كلمة المرور"
                    class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-gray-500 focus:border-emerald-500 focus:outline-none">
            </div>

            <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-3 rounded-xl transition-colors flex items-center justify-center gap-2">
                <span>تثبيت وإنشاء قاعدة البيانات</span>
                <span>←</span>
            </button>
        </form>
        <?php endif; ?>
    </div>
<?php endif; ?>

</body>
</html>