<?php
// Quick Database Setup
require_once 'backend/config/database.php';

$database = new Database();
$conn = $database->getConnection();

if (!$conn) {
    die("❌ فشل الاتصال بقاعدة البيانات");
}

echo "<h1>🔧 إعداد قاعدة البيانات</h1>";

// Read SQL file
$sql = file_get_contents('backend/database.sql');

// Remove comments
$sql = preg_replace('/--.*$/m', '', $sql);
$sql = preg_replace('/\/\*.*?\*\//s', '', $sql);

// Split by semicolon
$statements = explode(';', $sql);

$success = 0;
$failed = 0;
$errors = [];

foreach ($statements as $statement) {
    $statement = trim($statement);
    if (empty($statement)) continue;
    
    try {
        $conn->exec($statement);
        $success++;
    } catch (PDOException $e) {
        // Ignore "already exists" errors
        if (strpos($e->getMessage(), 'already exists') === false) {
            $failed++;
            $errors[] = $e->getMessage();
        } else {
            $success++;
        }
    }
}

echo "<h2>✅ النتيجة:</h2>";
echo "<p>نجح: <strong style='color: green;'>$success</strong> استعلام</p>";
echo "<p>فشل: <strong style='color: red;'>$failed</strong> استعلام</p>";

if (!empty($errors)) {
    echo "<h3>الأخطاء:</h3><ul>";
    foreach (array_slice($errors, 0, 5) as $error) {
        echo "<li>" . htmlspecialchars($error) . "</li>";
    }
    echo "</ul>";
}

// Check tables
$stmt = $conn->query("SHOW TABLES");
$tables = $stmt->fetchAll(PDO::FETCH_COLUMN);

echo "<h2>📊 الجداول الموجودة (" . count($tables) . "):</h2>";
echo "<ul>";
foreach ($tables as $table) {
    echo "<li>✓ $table</li>";
}
echo "</ul>";

echo "<hr>";
echo "<p><a href='install.php?step=4' style='padding: 10px 20px; background: #E57393; color: white; text-decoration: none; border-radius: 8px;'>المتابعة لإنشاء حساب المدير</a></p>";
?>
