<?php
/**
 * Roz Skin Installation Wizard
 * معالج تنصيب روز سكين
 * 
 * هذا الملف يساعدك على تنصيب المشروع بسهولة
 */

session_start();

// Check if already installed
$isInstalled = file_exists('backend/config/.installed');
$forceMode = isset($_GET['force']) || isset($_GET['step']);

// If installed and not in force mode, show warning page
if ($isInstalled && !$forceMode) {
    $step = 0; // Warning page
} else {
    $step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
}
$error = '';
$success = '';
$info = '';

// Database helper functions
function getDbConnection() {
    if (!file_exists('backend/config/database.php')) {
        return null;
    }
    require_once 'backend/config/database.php';
    $database = new Database();
    return $database->getConnection();
}

function getCurrentTables() {
    try {
        $conn = getDbConnection();
        if (!$conn) return [];
        
        $stmt = $conn->query("SHOW TABLES");
        $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
        return $tables;
    } catch (Exception $e) {
        return [];
    }
}

function getExpectedTables() {
    $sqlFile = 'backend/database.sql';
    if (!file_exists($sqlFile)) return [];
    
    $sql = file_get_contents($sqlFile);
    preg_match_all('/CREATE TABLE IF NOT EXISTS `([^`]+)`/i', $sql, $matches);
    return $matches[1] ?? [];
}

function executeQuery($query) {
    try {
        $conn = getDbConnection();
        if (!$conn) {
            return ['success' => false, 'message' => 'فشل الاتصال بقاعدة البيانات'];
        }
        
        // Check if it's a SELECT query
        if (stripos(trim($query), 'SELECT') === 0) {
            $stmt = $conn->query($query);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            return ['success' => true, 'data' => $results, 'type' => 'select'];
        } else {
            $affected = $conn->exec($query);
            return ['success' => true, 'affected' => $affected, 'type' => 'exec'];
        }
    } catch (PDOException $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Execute SQL Query
    if (isset($_POST['execute_query'])) {
        $query = trim($_POST['sql_query']);
        if (!empty($query)) {
            $result = executeQuery($query);
            if ($result['success']) {
                if ($result['type'] === 'select') {
                    $_SESSION['query_result'] = $result['data'];
                    $success = 'تم تنفيذ الاستعلام بنجاح! عدد النتائج: ' . count($result['data']);
                } else {
                    $success = 'تم تنفيذ الاستعلام بنجاح! عدد الصفوف المتأثرة: ' . $result['affected'];
                }
            } else {
                $error = 'خطأ في الاستعلام: ' . $result['message'];
            }
        }
    }
    
    // Reset Database
    if (isset($_POST['reset_database'])) {
        try {
            $conn = getDbConnection();
            if ($conn) {
                $tables = getCurrentTables();
                foreach ($tables as $table) {
                    $conn->exec("DROP TABLE IF EXISTS `$table`");
                }
                $success = 'تم حذف جميع الجداول (' . count($tables) . ' جدول) بنجاح!';
                $_SESSION['db_imported'] = false;
            }
        } catch (Exception $e) {
            $error = 'خطأ في إعادة الضبط: ' . $e->getMessage();
        }
    }
    
    // Step 2: Test Database Connection
    if ($step === 2 && isset($_POST['test_connection'])) {
        $host = $_POST['db_host'];
        $name = $_POST['db_name'];
        $user = $_POST['db_user'];
        $pass = $_POST['db_pass'];
        $port = $_POST['db_port'];
        
        try {
            $dsn = "mysql:host=$host;port=$port;dbname=$name;charset=utf8mb4";
            $conn = new PDO($dsn, $user, $pass);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            $_SESSION['db_config'] = [
                'host' => $host,
                'name' => $name,
                'user' => $user,
                'pass' => $pass,
                'port' => $port
            ];
            
            $success = 'تم الاتصال بنجاح! ✅';
        } catch (PDOException $e) {
            $error = 'فشل الاتصال: ' . $e->getMessage();
        }
    }
    
    // Step 2: Save Configuration
    if ($step === 2 && isset($_POST['save_config'])) {
        $config = $_SESSION['db_config'];
        
        $config_content = "<?php\n";
        $config_content .= "class Database {\n";
        $config_content .= "    private \$host = '{$config['host']}';\n";
        $config_content .= "    private \$db_name = '{$config['name']}';\n";
        $config_content .= "    private \$username = '{$config['user']}';\n";
        $config_content .= "    private \$password = '{$config['pass']}';\n";
        $config_content .= "    private \$port = {$config['port']};\n";
        $config_content .= "    private \$conn;\n\n";
        $config_content .= "    public function getConnection() {\n";
        $config_content .= "        \$this->conn = null;\n";
        $config_content .= "        try {\n";
        $config_content .= "            \$dsn = \"mysql:host=\" . \$this->host . \";port=\" . \$this->port . \";dbname=\" . \$this->db_name . \";charset=utf8mb4\";\n";
        $config_content .= "            \$this->conn = new PDO(\$dsn, \$this->username, \$this->password);\n";
        $config_content .= "            \$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n";
        $config_content .= "            \$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);\n";
        $config_content .= "        } catch(PDOException \$exception) {\n";
        $config_content .= "            error_log(\"Connection error: \" . \$exception->getMessage());\n";
        $config_content .= "            return null;\n";
        $config_content .= "        }\n";
        $config_content .= "        return \$this->conn;\n";
        $config_content .= "    }\n";
        $config_content .= "}\n";
        $config_content .= "?>";
        
        file_put_contents('backend/config/database.php', $config_content);
        
        // Redirect to step 3
        header('Location: install.php?step=3');
        exit;
    }
    
    // Step 3: Import Database
    if ($step === 3 && isset($_POST['import_database'])) {
        require_once 'backend/config/database.php';
        
        try {
            $database = new Database();
            $conn = $database->getConnection();
            
            if (!$conn) {
                throw new Exception('فشل الاتصال بقاعدة البيانات');
            }
            
            // Get MySQL/MariaDB version
            $versionStmt = $conn->query("SELECT VERSION() as version");
            $versionInfo = $versionStmt->fetch();
            $dbVersion = $versionInfo['version'];
            
            // Set SQL mode for MariaDB compatibility
            $conn->exec("SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO'");
            $conn->exec("SET time_zone = '+00:00'");
            
            // Read SQL file
            if (!file_exists('backend/database.sql')) {
                throw new Exception('ملف database.sql غير موجود');
            }
            
            $sql = file_get_contents('backend/database.sql');
            
            // Fix line breaks: replace /n with actual newlines
            $sql = str_replace('/n', "\n", $sql);
            $sql = str_replace('\n', "\n", $sql);
            
            // Remove comments
            $sql = preg_replace('/^--.*$/m', '', $sql);
            $sql = preg_replace('/\/\*.*?\*\//s', '', $sql);
            
            // Split by semicolon and execute each statement
            $statements = array_filter(
                array_map('trim', explode(';', $sql)),
                function($stmt) {
                    // Remove empty statements and comments
                    $stmt = trim($stmt);
                    if (empty($stmt)) return false;
                    if (preg_match('/^(--|\/\*|USE\s+)/i', $stmt)) return false;
                    return true;
                }
            );
            
            $executed = 0;
            $failed = 0;
            $errors = [];
            $createdTables = [];
            $skipped = 0;
            
            foreach ($statements as $statement) {
                try {
                    $statement = trim($statement);
                    if (empty($statement)) continue;
                    
                    // Skip USE database statements
                    if (preg_match('/^USE\s+/i', $statement)) {
                        $skipped++;
                        continue;
                    }
                    
                    $conn->exec($statement);
                    $executed++;
                    
                    // Extract table name if it's a CREATE TABLE statement
                    if (preg_match('/CREATE TABLE (?:IF NOT EXISTS )?`?([a-zA-Z0-9_]+)`?/i', $statement, $matches)) {
                        $createdTables[] = $matches[1];
                    }
                    
                } catch (PDOException $e) {
                    $errorMsg = $e->getMessage();
                    
                    // Ignore "table already exists" errors
                    if (strpos($errorMsg, 'already exists') !== false) {
                        $executed++;
                        if (preg_match('/CREATE TABLE (?:IF NOT EXISTS )?`?([a-zA-Z0-9_]+)`?/i', $statement, $matches)) {
                            $createdTables[] = $matches[1];
                        }
                        continue;
                    }
                    
                    $failed++;
                    
                    // Extract table name from statement
                    $tableName = 'unknown';
                    if (preg_match('/CREATE TABLE (?:IF NOT EXISTS )?`?([a-zA-Z0-9_]+)`?/i', $statement, $matches)) {
                        $tableName = $matches[1];
                    } elseif (preg_match('/INSERT INTO\s+`?([a-zA-Z0-9_]+)`?/i', $statement, $matches)) {
                        $tableName = $matches[1];
                    } elseif (preg_match('/ALTER TABLE\s+`?([a-zA-Z0-9_]+)`?/i', $statement, $matches)) {
                        $tableName = $matches[1];
                    }
                    
                    // Clean up statement for display
                    $displayStmt = str_replace(["\r\n", "\r", "\n"], ' ', $statement);
                    $displayStmt = preg_replace('/\s+/', ' ', $displayStmt);
                    $displayStmt = substr($displayStmt, 0, 300);
                    
                    $errors[] = [
                        'table' => $tableName,
                        'error' => $errorMsg,
                        'statement' => $displayStmt . (strlen($statement) > 300 ? '...' : '')
                    ];
                    
                    error_log("SQL Error in table '$tableName': " . $errorMsg);
                }
            }
            
            $_SESSION['db_imported'] = true;
            $_SESSION['tables_created'] = $executed;
            $_SESSION['tables_failed'] = $failed;
            $_SESSION['db_version'] = $dbVersion;
            $_SESSION['created_tables'] = $createdTables;
            
            if ($failed > 0) {
                $_SESSION['import_errors'] = $errors;
                $error = "تم إنشاء {$executed} جدول بنجاح، لكن فشل إنشاء {$failed} جدول. راجع التفاصيل أدناه.";
            } else {
                $success = "تم إنشاء {$executed} جدول بنجاح! ✅ (إصدار قاعدة البيانات: {$dbVersion})";
                
                // Redirect to step 4 only if no errors
                header('Location: install.php?step=4');
                exit;
            }
            
        } catch (Exception $e) {
            $error = 'خطأ في الاستيراد: ' . $e->getMessage();
        }
    }
    
    // Step 4: Create Admin
    if ($step === 4 && isset($_POST['create_admin'])) {
        require_once 'backend/config/database.php';
        
        $name = $_POST['admin_name'];
        $phone = $_POST['admin_phone'];
        $password = password_hash($_POST['admin_password'], PASSWORD_DEFAULT);
        
        try {
            $database = new Database();
            $conn = $database->getConnection();
            
            // Check if user already exists
            $checkStmt = $conn->prepare("SELECT id FROM users WHERE phone = ?");
            $checkStmt->execute([$phone]);
            $existingUser = $checkStmt->fetch();
            
            if ($existingUser) {
                // Update existing user
                $stmt = $conn->prepare("UPDATE users SET name = ?, password = ?, role = 'admin' WHERE phone = ?");
                $stmt->execute([$name, $password, $phone]);
                $success = 'تم تحديث حساب المدير بنجاح! ✅';
            } else {
                // Create new user
                $stmt = $conn->prepare("INSERT INTO users (name, phone, password, role) VALUES (?, ?, ?, 'admin')");
                $stmt->execute([$name, $phone, $password]);
                $success = 'تم إنشاء حساب المدير بنجاح! ✅';
            }
            
            // Mark as installed
            file_put_contents('backend/config/.installed', date('Y-m-d H:i:s'));
            
            // Redirect to step 5
            header('Location: install.php?step=5');
            exit;
        } catch (Exception $e) {
            $error = 'خطأ في إنشاء الحساب: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تنصيب Roz Skin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        body { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh; 
            padding: 20px;
            position: relative;
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: fixed;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px);
            background-size: 50px 50px;
            animation: moveBackground 20s linear infinite;
            pointer-events: none;
        }
        @keyframes moveBackground {
            0% { transform: translate(0, 0); }
            100% { transform: translate(50px, 50px); }
        }
        .container { 
            max-width: 900px; 
            margin: 0 auto; 
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 24px; 
            box-shadow: 0 25px 80px rgba(0,0,0,0.3);
            overflow: hidden;
            position: relative;
            animation: slideUp 0.6s ease;
        }
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .header { 
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); 
            color: white; 
            padding: 50px 40px; 
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        .header::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            animation: pulse 4s ease-in-out infinite;
        }
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 0.5; }
            50% { transform: scale(1.1); opacity: 0.8; }
        }
        .header h1 { 
            font-size: 36px; 
            margin-bottom: 12px;
            position: relative;
            z-index: 1;
            text-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        .header p { 
            opacity: 0.95;
            position: relative;
            z-index: 1;
            font-size: 16px;
        }
        .progress { 
            display: flex; 
            justify-content: space-between; 
            padding: 35px 40px; 
            background: linear-gradient(to bottom, #f8f9fa 0%, #ffffff 100%);
            border-bottom: 1px solid #e0e0e0;
        }
        .progress-step { 
            flex: 1; 
            text-align: center; 
            position: relative;
            transition: all 0.3s ease;
        }
        .progress-step::before { 
            content: ''; 
            position: absolute; 
            top: 22px; 
            right: 50%; 
            width: 100%; 
            height: 3px; 
            background: #e0e0e0; 
            z-index: 0;
            transition: all 0.5s ease;
        }
        .progress-step:first-child::before { display: none; }
        .progress-step.active .step-number { 
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(229, 115, 147, 0.4);
            transform: scale(1.1);
        }
        .progress-step.completed .step-number { 
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4);
        }
        .progress-step.completed::before { 
            background: linear-gradient(90deg, #10b981 0%, #059669 100%);
        }
        .step-number { 
            width: 45px; 
            height: 45px; 
            border-radius: 50%; 
            background: #e0e0e0; 
            color: #999; 
            display: inline-flex; 
            align-items: center; 
            justify-content: center; 
            font-weight: bold; 
            position: relative; 
            z-index: 1; 
            margin-bottom: 12px;
            transition: all 0.3s ease;
            font-size: 16px;
        }
        .step-label { 
            font-size: 13px; 
            color: #666;
            font-weight: 500;
        }
        .progress-step.active .step-label {
            color: #E57393;
            font-weight: 600;
        }
        .content { padding: 40px; }
        .form-group { margin-bottom: 25px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #333; }
        .form-group input, .form-group select { width: 100%; padding: 12px 15px; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 14px; transition: border-color 0.3s; }
        .form-group input:focus, .form-group select:focus { outline: none; border-color: #E57393; }
        .btn { 
            padding: 14px 32px; 
            border: none; 
            border-radius: 12px; 
            font-size: 16px; 
            font-weight: 600; 
            cursor: pointer; 
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: inline-flex; 
            align-items: center; 
            gap: 10px;
            position: relative;
            overflow: hidden;
        }
        .btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.3);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }
        .btn:hover::before {
            width: 300px;
            height: 300px;
        }
        .btn-primary { 
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); 
            color: white;
            box-shadow: 0 4px 15px rgba(229, 115, 147, 0.3);
        }
        .btn-primary:hover { 
            transform: translateY(-3px); 
            box-shadow: 0 8px 25px rgba(229, 115, 147, 0.5);
        }
        .btn-secondary { 
            background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
        }
        .btn-secondary:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(108, 117, 125, 0.5);
        }
        .btn-success { 
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }
        .btn-success:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(16, 185, 129, 0.5);
        }
        .alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; }
        .alert-success { background: #d1fae5; color: #065f46; border-right: 4px solid #10b981; }
        .alert-error { background: #fee2e2; color: #991b1b; border-right: 4px solid #ef4444; }
        .alert-info { background: #dbeafe; color: #1e40af; border-right: 4px solid #3b82f6; }
        .card { background: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px; }
        .card h3 { margin-bottom: 15px; color: #E57393; }
        .hosting-option { 
            padding: 24px; 
            border: 2px solid #e0e0e0; 
            border-radius: 16px; 
            margin-bottom: 16px; 
            cursor: pointer; 
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            background: white;
            position: relative;
            overflow: hidden;
        }
        .hosting-option::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: linear-gradient(135deg, #E57393 0%, #D1537A 100%);
            transform: scaleY(0);
            transition: transform 0.3s ease;
        }
        .hosting-option:hover { 
            border-color: #E57393; 
            background: linear-gradient(135deg, #fdf2f8 0%, #fce7f3 100%);
            transform: translateX(-5px);
            box-shadow: 0 4px 20px rgba(229, 115, 147, 0.2);
        }
        .hosting-option:hover::before {
            transform: scaleY(1);
        }
        .hosting-option.selected { 
            border-color: #E57393; 
            background: linear-gradient(135deg, #fdf2f8 0%, #fce7f3 100%);
            box-shadow: 0 4px 20px rgba(229, 115, 147, 0.3);
        }
        .hosting-option.selected::before {
            transform: scaleY(1);
        }
        .hosting-option h4 { 
            margin-bottom: 8px; 
            color: #333;
            font-size: 18px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .hosting-option p { 
            color: #666; 
            font-size: 14px;
            margin-right: 34px;
        }
        .actions { display: flex; gap: 15px; justify-content: space-between; margin-top: 30px; padding-top: 30px; border-top: 1px solid #e0e0e0; }
        .code-box { background: #1e293b; color: #e2e8f0; padding: 20px; border-radius: 8px; font-family: 'Courier New', monospace; font-size: 13px; overflow-x: auto; margin: 15px 0; }
        .success-icon { font-size: 80px; color: #10b981; text-align: center; margin: 30px 0; }
        table { width: 100%; border-collapse: collapse; margin: 15px 0; }
        th, td { padding: 10px; text-align: right; border: 1px solid #e0e0e0; }
        th { background: #f3f4f6; font-weight: 600; }
        textarea { resize: vertical; }
        .info-badge { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; margin: 0 5px; }
        .badge-success { background: #d1fae5; color: #065f46; }
        .badge-warning { background: #fef3c7; color: #92400e; }
        .badge-error { background: #fee2e2; color: #991b1b; }
        .badge-info { background: #dbeafe; color: #1e40af; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-spa"></i> Roz Skin</h1>
            <p>معالج التنصيب السريع</p>
            <?php if ($isInstalled && $step !== 0): ?>
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.3);">
                <div style="display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;">
                    <a href="backend/public/index.php" style="color: white; text-decoration: none; padding: 8px 16px; background: rgba(255,255,255,0.2); border-radius: 20px; font-size: 13px; transition: all 0.3s;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                        <i class="fas fa-home"></i> الموقع
                    </a>
                    <a href="backend/admin/" style="color: white; text-decoration: none; padding: 8px 16px; background: rgba(255,255,255,0.2); border-radius: 20px; font-size: 13px; transition: all 0.3s;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                        <i class="fas fa-lock"></i> لوحة التحكم
                    </a>
                    <a href="?step=3" style="color: white; text-decoration: none; padding: 8px 16px; background: rgba(255,255,255,0.2); border-radius: 20px; font-size: 13px; transition: all 0.3s;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                        <i class="fas fa-database"></i> قاعدة البيانات
                    </a>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="progress">
            <div class="progress-step <?php echo $step >= 1 ? 'active' : ''; ?> <?php echo $step > 1 ? 'completed' : ''; ?>">
                <div class="step-number">1</div>
                <div class="step-label">البداية</div>
            </div>
            <div class="progress-step <?php echo $step >= 2 ? 'active' : ''; ?> <?php echo $step > 2 ? 'completed' : ''; ?>">
                <div class="step-number">2</div>
                <div class="step-label">قاعدة البيانات</div>
            </div>
            <div class="progress-step <?php echo $step >= 3 ? 'active' : ''; ?> <?php echo $step > 3 ? 'completed' : ''; ?>">
                <div class="step-number">3</div>
                <div class="step-label">الجداول</div>
            </div>
            <div class="progress-step <?php echo $step >= 4 ? 'active' : ''; ?> <?php echo $step > 4 ? 'completed' : ''; ?>">
                <div class="step-number">4</div>
                <div class="step-label">المدير</div>
            </div>
            <div class="progress-step <?php echo $step >= 5 ? 'active' : ''; ?>">
                <div class="step-number">5</div>
                <div class="step-label">اكتمل</div>
            </div>
        </div>
        
        <div class="content">
            <?php if ($error): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($step === 0): ?>
                <!-- Warning Page: Already Installed -->
                <div style="text-align: center; padding: 40px 20px;">
                    <div style="font-size: 80px; color: #f59e0b; margin-bottom: 20px;">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    
                    <h2 style="color: #92400e; margin-bottom: 15px;">
                        ⚠️ الموقع مُنصّب بالفعل!
                    </h2>
                    
                    <p style="color: #666; font-size: 16px; margin-bottom: 30px; line-height: 1.8;">
                        يبدو أن عملية التنصيب قد تمت بالفعل.<br>
                        هل تريد الوصول لأدوات إدارة قاعدة البيانات أم الذهاب للموقع؟
                    </p>
                </div>
                
                <div class="card" style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 2px solid #f59e0b;">
                    <h3 style="color: #92400e;"><i class="fas fa-info-circle"></i> الخيارات المتاحة</h3>
                    
                    <div style="display: grid; gap: 15px; margin-top: 20px;">
                        <a href="backend/public/index.php" class="hosting-option" style="text-decoration: none; display: block;">
                            <h4 style="color: #10b981;"><i class="fas fa-home"></i> الذهاب للصفحة الرئيسية</h4>
                            <p>زيارة الموقع والتصفح</p>
                        </a>
                        
                        <a href="backend/admin/" class="hosting-option" style="text-decoration: none; display: block;">
                            <h4 style="color: #E57393;"><i class="fas fa-lock"></i> لوحة التحكم</h4>
                            <p>إدارة المنتجات والطلبات والإعدادات</p>
                        </a>
                        
                        <a href="?step=3" class="hosting-option" style="text-decoration: none; display: block;">
                            <h4 style="color: #3b82f6;"><i class="fas fa-database"></i> أدوات قاعدة البيانات</h4>
                            <p>تنفيذ استعلامات SQL، عرض الجداول، إعادة الضبط</p>
                        </a>
                        
                        <a href="?step=1" class="hosting-option" style="text-decoration: none; display: block;">
                            <h4 style="color: #6c757d;"><i class="fas fa-redo"></i> إعادة التنصيب</h4>
                            <p>البدء من جديد (سيتم حذف البيانات الحالية)</p>
                        </a>
                    </div>
                </div>
                
                <div class="alert alert-info" style="margin-top: 20px;">
                    <i class="fas fa-lightbulb"></i> 
                    <strong>نصيحة:</strong> يمكنك الوصول لأدوات قاعدة البيانات مباشرة عبر: 
                    <code style="background: white; padding: 2px 8px; border-radius: 4px; margin: 0 5px;">install.php?step=3</code>
                </div>
                
            <?php elseif ($step === 1): ?>
                <h2>مرحباً بك في معالج تنصيب Roz Skin! 🎉</h2>
                <p style="margin: 20px 0; color: #666; line-height: 1.8;">
                    هذا المعالج سيساعدك على تنصيب المشروع خطوة بخطوة بكل سهولة.
                </p>
                
                <div class="card">
                    <h3><i class="fas fa-check-circle"></i> المتطلبات</h3>
                    <table>
                        <tr>
                            <th>المتطلب</th>
                            <th>الحالة</th>
                        </tr>
                        <tr>
                            <td>PHP 7.4+</td>
                            <td style="color: <?php echo version_compare(PHP_VERSION, '7.4.0', '>=') ? '#10b981' : '#ef4444'; ?>">
                                <?php echo version_compare(PHP_VERSION, '7.4.0', '>=') ? '✅ ' . PHP_VERSION : '❌ ' . PHP_VERSION; ?>
                            </td>
                        </tr>
                        <tr>
                            <td>PDO Extension</td>
                            <td style="color: <?php echo extension_loaded('pdo') ? '#10b981' : '#ef4444'; ?>">
                                <?php echo extension_loaded('pdo') ? '✅ موجود' : '❌ مفقود'; ?>
                            </td>
                        </tr>
                        <tr>
                            <td>MySQL Extension</td>
                            <td style="color: <?php echo extension_loaded('pdo_mysql') ? '#10b981' : '#ef4444'; ?>">
                                <?php echo extension_loaded('pdo_mysql') ? '✅ موجود' : '❌ مفقود'; ?>
                            </td>
                        </tr>
                    </table>
                </div>
                
                <?php if ($isInstalled): ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> 
                    الموقع مُنصّب بالفعل. يمكنك الانتقال مباشرة لأدوات قاعدة البيانات أو إعادة التنصيب.
                </div>
                <?php endif; ?>
                
                <div class="actions">
                    <?php if ($isInstalled): ?>
                        <a href="?step=3" class="btn btn-secondary">
                            <i class="fas fa-database"></i> أدوات قاعدة البيانات
                        </a>
                    <?php else: ?>
                        <div></div>
                    <?php endif; ?>
                    <a href="?step=2" class="btn btn-primary">
                        التالي <i class="fas fa-arrow-left"></i>
                    </a>
                </div>
                
            <?php elseif ($step === 2): ?>
                <h2>إعداد قاعدة البيانات 🗄️</h2>
                
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> اختر نوع الاستضافة لتعبئة البيانات تلقائياً
                </div>
                
                <form method="POST" id="dbForm">
                    <div class="hosting-option" onclick="selectHosting('local')">
                        <h4><i class="fas fa-laptop"></i> استضافة محلية (Localhost)</h4>
                        <p>XAMPP, WAMP, Laragon</p>
                    </div>
                    
                    <div class="hosting-option" onclick="selectHosting('hostinger')">
                        <h4><i class="fas fa-server"></i> Hostinger</h4>
                        <p>استضافة Hostinger</p>
                    </div>
                    
                    <div class="hosting-option" onclick="selectHosting('custom')">
                        <h4><i class="fas fa-cog"></i> مخصص</h4>
                        <p>أدخل البيانات يدوياً</p>
                    </div>
                    
                    <div class="form-group">
                        <label>Host</label>
                        <input type="text" name="db_host" id="db_host" value="<?php echo $_SESSION['db_config']['host'] ?? 'localhost'; ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Database Name</label>
                        <input type="text" name="db_name" id="db_name" value="<?php echo $_SESSION['db_config']['name'] ?? 'u884608576_rozskin'; ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Username</label>
                        <input type="text" name="db_user" id="db_user" value="<?php echo $_SESSION['db_config']['user'] ?? 'u884608576_rozskin'; ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Password <small style="color: #999;">(اتركه فارغاً إذا لم يكن هناك باسورد)</small></label>
                        <input type="password" name="db_pass" id="db_pass" value="<?php echo $_SESSION['db_config']['pass'] ?? 'Rozskin@ahmad123'; ?>" placeholder="اتركه فارغاً للـ localhost">
                    </div>
                    
                    <div class="form-group">
                        <label>Port</label>
                        <input type="number" name="db_port" id="db_port" value="<?php echo $_SESSION['db_config']['port'] ?? '3306'; ?>" required>
                    </div>
                    
                    <div class="actions">
                        <a href="?step=1" class="btn btn-secondary">
                            <i class="fas fa-arrow-right"></i> السابق
                        </a>
                        <div style="display: flex; gap: 10px;">
                            <button type="submit" name="test_connection" class="btn btn-secondary">
                                <i class="fas fa-plug"></i> اختبار الاتصال
                            </button>
                            <?php if (isset($_SESSION['db_config'])): ?>
                                <button type="submit" name="save_config" class="btn btn-primary">
                                    حفظ والمتابعة <i class="fas fa-arrow-left"></i>
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
                
                <script>
                    function selectHosting(type) {
                        if (type === 'local') {
                            document.getElementById('db_host').value = 'localhost';
                            document.getElementById('db_name').value = 'ecommerce';
                            document.getElementById('db_user').value = 'root';
                            document.getElementById('db_pass').value = '';
                            document.getElementById('db_port').value = '3306';
                        } else if (type === 'hostinger') {
                            document.getElementById('db_host').value = 'localhost';
                            document.getElementById('db_name').value = 'u884608576_rozskin';
                            document.getElementById('db_user').value = 'u884608576_rozskin';
                            document.getElementById('db_pass').value = 'Rozskin@ahmad123';
                            document.getElementById('db_port').value = '3306';
                        }
                    }
                </script>
                
            <?php elseif ($step === 3): ?>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h2 style="margin: 0;">إدارة قاعدة البيانات 📋</h2>
                    <?php if ($isInstalled): ?>
                        <span class="info-badge badge-success">
                            <i class="fas fa-check-circle"></i> مُنصّب
                        </span>
                    <?php endif; ?>
                </div>
                
                <?php
                $currentTables = getCurrentTables();
                $expectedTables = getExpectedTables();
                $missingTables = array_diff($expectedTables, $currentTables);
                $extraTables = array_diff($currentTables, $expectedTables);
                ?>
                
                <div class="card" style="background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%); border: 2px solid #0ea5e9;">
                    <h3 style="color: #0369a1;"><i class="fas fa-info-circle"></i> حالة قاعدة البيانات</h3>
                    <table style="margin-top: 15px;">
                        <?php
                        // Get database version
                        try {
                            $conn = getDbConnection();
                            if ($conn) {
                                $versionStmt = $conn->query("SELECT VERSION() as version");
                                $versionInfo = $versionStmt->fetch();
                                $dbVersion = $versionInfo['version'];
                            }
                        } catch (Exception $e) {
                            $dbVersion = 'غير معروف';
                        }
                        ?>
                        <tr>
                            <td><strong>إصدار قاعدة البيانات:</strong></td>
                            <td style="color: #0369a1; font-weight: bold;">
                                <span class="info-badge badge-info">
                                    <i class="fas fa-database"></i> <?php echo htmlspecialchars($dbVersion); ?>
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <td><strong>الجداول الحالية:</strong></td>
                            <td style="color: #0ea5e9; font-weight: bold; font-size: 18px;"><?php echo count($currentTables); ?> جدول</td>
                        </tr>
                        <tr>
                            <td><strong>الجداول المطلوبة:</strong></td>
                            <td style="color: #10b981; font-weight: bold; font-size: 18px;"><?php echo count($expectedTables); ?> جدول</td>
                        </tr>
                        <tr>
                            <td><strong>الجداول الناقصة:</strong></td>
                            <td style="color: <?php echo count($missingTables) > 0 ? '#ef4444' : '#10b981'; ?>; font-weight: bold; font-size: 18px;">
                                <?php echo count($missingTables); ?> جدول
                            </td>
                        </tr>
                        <?php if (count($extraTables) > 0): ?>
                        <tr>
                            <td><strong>جداول إضافية:</strong></td>
                            <td style="color: #f59e0b; font-weight: bold; font-size: 18px;"><?php echo count($extraTables); ?> جدول</td>
                        </tr>
                        <?php endif; ?>
                    </table>
                </div>
                
                <?php if (count($missingTables) > 0): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-triangle"></i> 
                    <strong>تنبيه:</strong> يوجد <?php echo count($missingTables); ?> جدول ناقص في قاعدة البيانات
                </div>
                
                <div class="card">
                    <h3 style="color: #ef4444;"><i class="fas fa-times-circle"></i> الجداول الناقصة (<?php echo count($missingTables); ?>):</h3>
                    <div style="columns: 3; column-gap: 15px; padding-right: 20px; line-height: 2; font-size: 14px;">
                        <?php foreach ($missingTables as $table): ?>
                            <div style="color: #dc2626;">• <?php echo $table; ?></div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php else: ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> 
                    <strong>ممتاز!</strong> جميع الجداول المطلوبة موجودة في قاعدة البيانات
                </div>
                <?php endif; ?>
                
                <?php if (isset($_SESSION['import_errors']) && !empty($_SESSION['import_errors'])): ?>
                <div class="card" style="background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); border: 2px solid #ef4444;">
                    <h3 style="color: #991b1b;"><i class="fas fa-bug"></i> تفاصيل الأخطاء (<?php echo count($_SESSION['import_errors']); ?>):</h3>
                    <?php foreach ($_SESSION['import_errors'] as $idx => $err): ?>
                    <details style="margin: 15px 0; background: white; padding: 15px; border-radius: 8px; border-right: 4px solid #ef4444;">
                        <summary style="cursor: pointer; font-weight: 600; color: #dc2626;">
                            <i class="fas fa-exclamation-circle"></i> خطأ #<?php echo $idx + 1; ?>: جدول <?php echo htmlspecialchars($err['table']); ?>
                        </summary>
                        <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #fee2e2;">
                            <p style="margin-bottom: 10px;"><strong>رسالة الخطأ:</strong></p>
                            <div style="background: #fef2f2; padding: 12px; border-radius: 6px; font-family: 'Courier New', monospace; font-size: 13px; color: #991b1b; margin-bottom: 15px; word-break: break-word;">
                                <?php echo htmlspecialchars($err['error']); ?>
                            </div>
                            <p style="margin-bottom: 10px;"><strong>جزء من الاستعلام:</strong></p>
                            <div style="background: #1e293b; color: #e2e8f0; padding: 12px; border-radius: 6px; font-family: 'Courier New', monospace; font-size: 12px; overflow-x: auto;">
                                <?php echo htmlspecialchars($err['statement']); ?>
                            </div>
                        </div>
                    </details>
                    <?php endforeach; ?>
                    
                    <div style="margin-top: 20px; padding: 15px; background: #fffbeb; border-radius: 8px; border-right: 4px solid #f59e0b;">
                        <h4 style="color: #92400e; margin-bottom: 10px;"><i class="fas fa-lightbulb"></i> حلول مقترحة:</h4>
                        <ul style="padding-right: 20px; line-height: 2; color: #78350f;">
                            <li><strong>مشكلة شائعة:</strong> إذا كانت الأخطاء تحتوي على <code>/n</code> أو <code>\n</code>، فهذا يعني أن ملف database.sql يحتوي على line breaks غير صحيحة</li>
                            <li>جرب فتح ملف database.sql في محرر نصوص وتأكد من أن السطور منفصلة بشكل صحيح</li>
                            <li>تأكد من توافق ملف database.sql مع إصدار MariaDB <?php echo isset($_SESSION['db_version']) ? $_SESSION['db_version'] : '11.8.3'; ?></li>
                            <li>جرب حذف الجداول الموجودة وإعادة الإنشاء باستخدام زر "إعادة ضبط"</li>
                            <li>تحقق من صلاحيات المستخدم في قاعدة البيانات (CREATE, ALTER, DROP)</li>
                        </ul>
                    </div>
                </div>
                <?php unset($_SESSION['import_errors']); ?>
                <?php endif; ?>
                
                <?php if (isset($_SESSION['created_tables']) && !empty($_SESSION['created_tables'])): ?>
                <details style="margin: 20px 0;">
                    <summary style="cursor: pointer; padding: 15px; background: #d1fae5; border-radius: 8px; font-weight: 600; color: #065f46; border-right: 4px solid #10b981;">
                        <i class="fas fa-check-circle"></i> الجداول التي تم إنشاؤها بنجاح (<?php echo count($_SESSION['created_tables']); ?> جدول)
                    </summary>
                    <div style="margin-top: 15px; padding: 15px; background: white; border: 1px solid #d1fae5; border-radius: 8px;">
                        <div style="columns: 4; column-gap: 15px; line-height: 2; font-size: 13px;">
                            <?php foreach ($_SESSION['created_tables'] as $table): ?>
                                <div style="color: #059669;">✓ <?php echo htmlspecialchars($table); ?></div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </details>
                <?php unset($_SESSION['created_tables']); ?>
                <?php endif; ?>
                
                <?php if (count($currentTables) > 0): ?>
                <details style="margin: 20px 0;">
                    <summary style="cursor: pointer; padding: 15px; background: #f3f4f6; border-radius: 8px; font-weight: 600; color: #374151;">
                        <i class="fas fa-table"></i> عرض جميع الجداول الموجودة (<?php echo count($currentTables); ?> جدول)
                    </summary>
                    <div style="margin-top: 15px; padding: 15px; background: white; border: 1px solid #e5e7eb; border-radius: 8px;">
                        <div style="columns: 4; column-gap: 15px; line-height: 2; font-size: 13px;">
                            <?php foreach ($currentTables as $table): ?>
                                <div style="color: #059669;">✓ <?php echo $table; ?></div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </details>
                <?php endif; ?>
                
                <!-- SQL Query Executor -->
                <div class="card" style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 2px solid #f59e0b;">
                    <h3 style="color: #92400e;"><i class="fas fa-terminal"></i> تنفيذ استعلام SQL</h3>
                    <form method="POST">
                        <div class="form-group">
                            <label>أدخل استعلام SQL:</label>
                            <textarea name="sql_query" rows="4" style="width: 100%; padding: 12px; border: 2px solid #f59e0b; border-radius: 8px; font-family: 'Courier New', monospace; font-size: 13px;" placeholder="مثال: SELECT COUNT(*) as total FROM users"><?php echo isset($_POST['sql_query']) ? htmlspecialchars($_POST['sql_query']) : ''; ?></textarea>
                        </div>
                        <button type="submit" name="execute_query" class="btn btn-secondary">
                            <i class="fas fa-play"></i> تنفيذ الاستعلام
                        </button>
                    </form>
                    
                    <?php if (isset($_SESSION['query_result']) && !empty($_SESSION['query_result'])): ?>
                    <div style="margin-top: 20px; max-height: 300px; overflow: auto;">
                        <h4 style="color: #92400e; margin-bottom: 10px;">النتائج:</h4>
                        <table style="font-size: 13px;">
                            <thead>
                                <tr>
                                    <?php foreach (array_keys($_SESSION['query_result'][0]) as $column): ?>
                                        <th><?php echo htmlspecialchars($column); ?></th>
                                    <?php endforeach; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($_SESSION['query_result'] as $row): ?>
                                    <tr>
                                        <?php foreach ($row as $value): ?>
                                            <td><?php echo htmlspecialchars($value); ?></td>
                                        <?php endforeach; ?>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php unset($_SESSION['query_result']); ?>
                    <?php endif; ?>
                </div>
                
                <!-- Quick Queries -->
                <div class="card">
                    <h3><i class="fas fa-bolt"></i> استعلامات سريعة</h3>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px;">
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="sql_query" value="SHOW TABLES">
                            <button type="submit" name="execute_query" class="btn btn-secondary" style="width: 100%; padding: 10px; font-size: 13px;">
                                <i class="fas fa-list"></i> عرض الجداول
                            </button>
                        </form>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="sql_query" value="SELECT COUNT(*) as total FROM users">
                            <button type="submit" name="execute_query" class="btn btn-secondary" style="width: 100%; padding: 10px; font-size: 13px;">
                                <i class="fas fa-users"></i> المستخدمين
                            </button>
                        </form>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="sql_query" value="SELECT COUNT(*) as total FROM products">
                            <button type="submit" name="execute_query" class="btn btn-secondary" style="width: 100%; padding: 10px; font-size: 13px;">
                                <i class="fas fa-box"></i> المنتجات
                            </button>
                        </form>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="sql_query" value="SELECT COUNT(*) as total FROM orders">
                            <button type="submit" name="execute_query" class="btn btn-secondary" style="width: 100%; padding: 10px; font-size: 13px;">
                                <i class="fas fa-shopping-cart"></i> الطلبات
                            </button>
                        </form>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="sql_query" value="SELECT COUNT(*) as total FROM categories">
                            <button type="submit" name="execute_query" class="btn btn-secondary" style="width: 100%; padding: 10px; font-size: 13px;">
                                <i class="fas fa-tags"></i> الفئات
                            </button>
                        </form>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="sql_query" value="SELECT name, role FROM users LIMIT 10">
                            <button type="submit" name="execute_query" class="btn btn-secondary" style="width: 100%; padding: 10px; font-size: 13px;">
                                <i class="fas fa-user-shield"></i> المستخدمين
                            </button>
                        </form>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="sql_query" value="SELECT TABLE_NAME, TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()">
                            <button type="submit" name="execute_query" class="btn btn-secondary" style="width: 100%; padding: 10px; font-size: 13px;">
                                <i class="fas fa-chart-bar"></i> إحصائيات
                            </button>
                        </form>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="sql_query" value="SELECT VERSION() as mysql_version">
                            <button type="submit" name="execute_query" class="btn btn-secondary" style="width: 100%; padding: 10px; font-size: 13px;">
                                <i class="fas fa-info"></i> إصدار MySQL
                            </button>
                        </form>
                    </div>
                </div>
                
                <!-- Database Actions -->
                <form method="POST">
                    <div class="actions" style="flex-wrap: wrap;">
                        <a href="?step=2" class="btn btn-secondary">
                            <i class="fas fa-arrow-right"></i> السابق
                        </a>
                        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                            <?php if (count($currentTables) > 0): ?>
                            <button type="submit" name="reset_database" class="btn" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color: white;" onclick="return confirm('هل أنت متأكد من حذف جميع الجداول؟')">
                                <i class="fas fa-trash"></i> إعادة ضبط
                            </button>
                            <?php endif; ?>
                            
                            <?php if (count($missingTables) > 0 || count($currentTables) === 0): ?>
                            <button type="submit" name="import_database" class="btn btn-primary">
                                <i class="fas fa-database"></i> إنشاء الجداول
                            </button>
                            <?php else: ?>
                            <a href="?step=4" class="btn btn-primary">
                                التالي <i class="fas fa-arrow-left"></i>
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
                
            <?php elseif ($step === 4): ?>
                <h2>إنشاء حساب المدير 👤</h2>
                
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> تم إنشاء الجداول بنجاح!
                </div>
                
                <?php
                // Check existing admins
                try {
                    $conn = getDbConnection();
                    if ($conn) {
                        $stmt = $conn->query("SELECT id, name, phone, role, created_at FROM users WHERE role = 'admin' ORDER BY created_at DESC LIMIT 5");
                        $existingAdmins = $stmt->fetchAll();
                        
                        if (!empty($existingAdmins)) {
                            echo '<div class="alert alert-info">';
                            echo '<i class="fas fa-info-circle"></i> ';
                            echo '<strong>ملاحظة:</strong> يوجد ' . count($existingAdmins) . ' حساب مدير بالفعل. ';
                            echo 'إذا أدخلت رقم هاتف موجود، سيتم تحديث الحساب بدلاً من إنشاء واحد جديد.';
                            echo '</div>';
                            
                            echo '<details style="margin: 20px 0;">';
                            echo '<summary style="cursor: pointer; padding: 15px; background: #f3f4f6; border-radius: 8px; font-weight: 600; color: #374151;">';
                            echo '<i class="fas fa-users"></i> عرض حسابات المدير الموجودة (' . count($existingAdmins) . ')';
                            echo '</summary>';
                            echo '<div style="margin-top: 15px;">';
                            echo '<table style="font-size: 13px;">';
                            echo '<thead><tr><th>الاسم</th><th>رقم الهاتف</th><th>الدور</th><th>تاريخ الإنشاء</th></tr></thead>';
                            echo '<tbody>';
                            foreach ($existingAdmins as $admin) {
                                echo '<tr>';
                                echo '<td>' . htmlspecialchars($admin['name']) . '</td>';
                                echo '<td><code>' . htmlspecialchars($admin['phone']) . '</code></td>';
                                echo '<td><span class="info-badge badge-success">' . htmlspecialchars($admin['role']) . '</span></td>';
                                echo '<td>' . date('Y-m-d H:i', strtotime($admin['created_at'])) . '</td>';
                                echo '</tr>';
                            }
                            echo '</tbody></table>';
                            echo '</div>';
                            echo '</details>';
                        }
                    }
                } catch (Exception $e) {
                    // Ignore errors
                }
                ?>
                
                <form method="POST" id="adminForm">
                    <div class="form-group">
                        <label>الاسم</label>
                        <input type="text" name="admin_name" value="Admin" required>
                    </div>
                    
                    <div class="form-group">
                        <label>رقم الهاتف <small style="color: #999;">(إذا كان موجوداً، سيتم تحديث الحساب)</small></label>
                        <input type="text" name="admin_phone" id="admin_phone" value="01234567890" required pattern="[0-9]{11}" title="أدخل رقم هاتف صحيح (11 رقم)">
                    </div>
                    
                    <div class="form-group">
                        <label>كلمة المرور</label>
                        <input type="password" name="admin_password" id="admin_password" required minlength="6">
                        <small style="color: #666; font-size: 12px;">
                            <i class="fas fa-info-circle"></i> يجب أن تكون 6 أحرف على الأقل
                        </small>
                    </div>
                    
                    <div class="actions">
                        <a href="?step=3" class="btn btn-secondary">
                            <i class="fas fa-arrow-right"></i> السابق
                        </a>
                        <button type="submit" name="create_admin" class="btn btn-primary">
                            <i class="fas fa-user-plus"></i> حفظ وإنهاء
                        </button>
                    </div>
                </form>
                
                <script>
                // Check if phone exists
                document.getElementById('admin_phone').addEventListener('blur', function() {
                    const phone = this.value;
                    const existingPhones = [<?php 
                        if (!empty($existingAdmins)) {
                            echo '"' . implode('","', array_column($existingAdmins, 'phone')) . '"';
                        }
                    ?>];
                    
                    if (existingPhones.includes(phone)) {
                        const btn = document.querySelector('button[name="create_admin"]');
                        btn.innerHTML = '<i class="fas fa-sync"></i> تحديث الحساب';
                        btn.style.background = 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)';
                        
                        // Show warning
                        let warning = document.getElementById('phone-warning');
                        if (!warning) {
                            warning = document.createElement('div');
                            warning.id = 'phone-warning';
                            warning.className = 'alert alert-info';
                            warning.style.marginTop = '10px';
                            warning.innerHTML = '<i class="fas fa-info-circle"></i> هذا الرقم موجود بالفعل. سيتم تحديث الحساب الموجود.';
                            this.parentElement.appendChild(warning);
                        }
                    } else {
                        const btn = document.querySelector('button[name="create_admin"]');
                        btn.innerHTML = '<i class="fas fa-user-plus"></i> حفظ وإنهاء';
                        btn.style.background = 'linear-gradient(135deg, #E57393 0%, #D1537A 100%)';
                        
                        const warning = document.getElementById('phone-warning');
                        if (warning) warning.remove();
                    }
                });
                </script>
                
            <?php elseif ($step === 5): ?>
                <div class="success-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                
                <h2 style="text-align: center; color: #10b981; margin-bottom: 20px;">
                    تم التنصيب بنجاح! 🎉
                </h2>
                
                <p style="text-align: center; color: #666; margin-bottom: 30px;">
                    موقعك الآن جاهز للاستخدام
                </p>
                
                <?php
                $currentTables = getCurrentTables();
                $expectedTables = getExpectedTables();
                ?>
                
                <div class="card" style="background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%); border: 2px solid #10b981;">
                    <h3 style="color: #065f46;"><i class="fas fa-check-double"></i> ملخص التنصيب</h3>
                    <table>
                        <tr>
                            <td><strong>الجداول المنشأة:</strong></td>
                            <td style="color: #10b981; font-weight: bold; font-size: 18px;">
                                <?php echo count($currentTables); ?> / <?php echo count($expectedTables); ?> جدول
                            </td>
                        </tr>
                        <tr>
                            <td><strong>حالة قاعدة البيانات:</strong></td>
                            <td>
                                <?php if (count($currentTables) === count($expectedTables)): ?>
                                    <span class="info-badge badge-success">✅ مكتملة</span>
                                <?php else: ?>
                                    <span class="info-badge badge-warning">⚠️ ناقصة</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <td><strong>إصدار PHP:</strong></td>
                            <td><span class="info-badge badge-info"><?php echo PHP_VERSION; ?></span></td>
                        </tr>
                    </table>
                </div>
                
                <div class="card">
                    <h3><i class="fas fa-list-check"></i> الخطوات التالية:</h3>
                    <ol style="padding-right: 20px; line-height: 2.2; font-size: 15px;">
                        <li>سجل دخول للوحة التحكم باستخدام البيانات التي أدخلتها</li>
                        <li>أضف المنتجات والفئات من لوحة التحكم</li>
                        <li>اضبط إعدادات الموقع (الشعار، الألوان، معلومات الاتصال)</li>
                        <li>قم بتفعيل طرق الدفع المناسبة</li>
                        <li><strong style="color: #ef4444;">مهم:</strong> احذف ملف <code style="background: #fee2e2; padding: 2px 8px; border-radius: 4px;">install.php</code> من السيرفر لأسباب أمنية</li>
                    </ol>
                </div>
                
                <div class="card" style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 2px solid #f59e0b;">
                    <h3 style="color: #92400e;"><i class="fas fa-tools"></i> أدوات إضافية</h3>
                    <p style="color: #78350f; margin-bottom: 15px;">
                        يمكنك الوصول لأدوات إدارة قاعدة البيانات في أي وقت عبر:
                    </p>
                    <div class="code-box" style="background: #78350f;">
                        install.php?step=3
                    </div>
                    <p style="color: #78350f; font-size: 13px; margin-top: 10px;">
                        <i class="fas fa-info-circle"></i> يمكنك تنفيذ استعلامات SQL، عرض الجداول، وإعادة ضبط قاعدة البيانات
                    </p>
                </div>
                
                <div class="actions" style="justify-content: center; flex-wrap: wrap;">
                    <a href="backend/public/index.php" class="btn btn-success">
                        <i class="fas fa-home"></i> الصفحة الرئيسية
                    </a>
                    <a href="backend/admin/" class="btn btn-primary">
                        <i class="fas fa-lock"></i> لوحة التحكم
                    </a>
                    <a href="?step=3" class="btn btn-secondary">
                        <i class="fas fa-database"></i> إدارة قاعدة البيانات
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
