<?php
/**
 * إصلاح ملف database.sql
 * يصلح مشاكل line breaks (/n و \n)
 */

echo "<!DOCTYPE html>";
echo "<html lang='ar' dir='rtl'>";
echo "<head>";
echo "<meta charset='UTF-8'>";
echo "<title>إصلاح database.sql</title>";
echo "<style>";
echo "body { font-family: Arial; padding: 20px; background: #f5f5f5; }";
echo ".card { background: white; padding: 20px; margin: 10px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }";
echo ".success { color: #10b981; font-weight: bold; }";
echo ".error { color: #ef4444; font-weight: bold; }";
echo ".info { color: #3b82f6; }";
echo ".warning { color: #f59e0b; }";
echo "pre { background: #1e293b; color: #e2e8f0; padding: 15px; border-radius: 8px; overflow-x: auto; font-size: 13px; }";
echo ".btn { display: inline-block; padding: 12px 24px; background: #E57393; color: white; text-decoration: none; border-radius: 8px; margin: 10px 5px; }";
echo ".btn:hover { background: #D1537A; }";
echo "</style>";
echo "</head>";
echo "<body>";

echo "<h1>🔧 إصلاح ملف database.sql</h1>";

$sqlFile = 'backend/database.sql';
$backupFile = 'backend/database.sql.backup';

if (!file_exists($sqlFile)) {
    echo "<div class='card'>";
    echo "<p class='error'>❌ ملف database.sql غير موجود!</p>";
    echo "</div>";
    echo "</body></html>";
    exit;
}

// Read original file
$originalContent = file_get_contents($sqlFile);
$originalSize = strlen($originalContent);

echo "<div class='card'>";
echo "<h2>📊 معلومات الملف الأصلي</h2>";
echo "<p><strong>المسار:</strong> <code>{$sqlFile}</code></p>";
echo "<p><strong>الحجم:</strong> " . number_format($originalSize) . " بايت</p>";

// Check for problems
$hasSlashN = strpos($originalContent, '/n') !== false;
$hasBackslashN = strpos($originalContent, '\n') !== false;
$slashNCount = substr_count($originalContent, '/n');
$backslashNCount = substr_count($originalContent, '\n');

echo "<p><strong>مشاكل محتملة:</strong></p>";
echo "<ul>";
if ($hasSlashN) {
    echo "<li class='warning'>⚠️ يحتوي على <code>/n</code> ({$slashNCount} مرة)</li>";
}
if ($hasBackslashN) {
    echo "<li class='warning'>⚠️ يحتوي على <code>\\n</code> ({$backslashNCount} مرة)</li>";
}
if (!$hasSlashN && !$hasBackslashN) {
    echo "<li class='success'>✅ لا توجد مشاكل واضحة</li>";
}
echo "</ul>";
echo "</div>";

if (isset($_POST['fix_file'])) {
    echo "<div class='card'>";
    echo "<h2>🔨 جاري الإصلاح...</h2>";
    
    // Create backup
    if (copy($sqlFile, $backupFile)) {
        echo "<p class='success'>✅ تم إنشاء نسخة احتياطية: {$backupFile}</p>";
    } else {
        echo "<p class='error'>❌ فشل إنشاء النسخة الاحتياطية!</p>";
        echo "</div></body></html>";
        exit;
    }
    
    // Fix the content
    $fixedContent = $originalContent;
    
    // Replace /n with actual newlines
    $fixedContent = str_replace('/n', "\n", $fixedContent);
    
    // Replace \n with actual newlines (but be careful with escaped characters)
    $fixedContent = str_replace('\\n', "\n", $fixedContent);
    
    // Normalize line endings (convert all to \n)
    $fixedContent = str_replace("\r\n", "\n", $fixedContent);
    $fixedContent = str_replace("\r", "\n", $fixedContent);
    
    // Remove multiple consecutive blank lines
    $fixedContent = preg_replace("/\n{3,}/", "\n\n", $fixedContent);
    
    // Save fixed file
    if (file_put_contents($sqlFile, $fixedContent)) {
        $newSize = strlen($fixedContent);
        echo "<p class='success'>✅ تم إصلاح الملف بنجاح!</p>";
        echo "<p><strong>الحجم الجديد:</strong> " . number_format($newSize) . " بايت</p>";
        echo "<p><strong>الفرق:</strong> " . number_format($newSize - $originalSize) . " بايت</p>";
        
        // Show changes
        echo "<h3>التغييرات:</h3>";
        echo "<ul>";
        $newSlashNCount = substr_count($fixedContent, '/n');
        $newBackslashNCount = substr_count($fixedContent, '\n');
        
        if ($slashNCount > 0) {
            echo "<li>تم إصلاح <code>/n</code>: {$slashNCount} → {$newSlashNCount}</li>";
        }
        if ($backslashNCount > 0) {
            echo "<li>تم إصلاح <code>\\n</code>: {$backslashNCount} → {$newBackslashNCount}</li>";
        }
        echo "</ul>";
        
        echo "<div style='margin-top: 20px; padding: 15px; background: #d1fae5; border-radius: 8px; border-right: 4px solid #10b981;'>";
        echo "<p class='success'>✅ الملف جاهز الآن!</p>";
        echo "<p>يمكنك الآن العودة لـ <a href='install.php?step=3' style='color: #E57393; font-weight: bold;'>معالج التنصيب</a> وإعادة المحاولة.</p>";
        echo "</div>";
        
    } else {
        echo "<p class='error'>❌ فشل حفظ الملف المُصلح!</p>";
    }
    
    echo "</div>";
    
} elseif (isset($_POST['restore_backup'])) {
    echo "<div class='card'>";
    echo "<h2>♻️ استعادة النسخة الاحتياطية...</h2>";
    
    if (!file_exists($backupFile)) {
        echo "<p class='error'>❌ النسخة الاحتياطية غير موجودة!</p>";
    } elseif (copy($backupFile, $sqlFile)) {
        echo "<p class='success'>✅ تم استعادة النسخة الاحتياطية بنجاح!</p>";
    } else {
        echo "<p class='error'>❌ فشلت عملية الاستعادة!</p>";
    }
    
    echo "</div>";
}

// Show sample of problematic lines
if ($hasSlashN || $hasBackslashN) {
    echo "<div class='card'>";
    echo "<h2>🔍 عينة من المشاكل</h2>";
    
    $lines = explode("\n", $originalContent);
    $problemLines = [];
    
    foreach ($lines as $idx => $line) {
        if (strpos($line, '/n') !== false || strpos($line, '\n') !== false) {
            $problemLines[] = [
                'number' => $idx + 1,
                'content' => substr($line, 0, 100)
            ];
            
            if (count($problemLines) >= 5) break;
        }
    }
    
    if (!empty($problemLines)) {
        echo "<p>أول 5 أسطر تحتوي على مشاكل:</p>";
        echo "<pre>";
        foreach ($problemLines as $pl) {
            echo "السطر {$pl['number']}: " . htmlspecialchars($pl['content']) . "\n";
        }
        echo "</pre>";
    }
    
    echo "</div>";
}

// Action buttons
echo "<div class='card'>";
echo "<h2>⚡ الإجراءات</h2>";

if ($hasSlashN || $hasBackslashN) {
    echo "<form method='POST' style='display: inline;'>";
    echo "<button type='submit' name='fix_file' class='btn' onclick='return confirm(\"هل أنت متأكد من إصلاح الملف؟ سيتم إنشاء نسخة احتياطية.\")'>🔧 إصلاح الملف</button>";
    echo "</form>";
} else {
    echo "<p class='info'>ℹ️ الملف يبدو سليماً، لا حاجة للإصلاح.</p>";
}

if (file_exists($backupFile)) {
    echo "<form method='POST' style='display: inline;'>";
    echo "<button type='submit' name='restore_backup' class='btn' style='background: #6c757d;' onclick='return confirm(\"هل تريد استعادة النسخة الاحتياطية؟\")'>♻️ استعادة النسخة الاحتياطية</button>";
    echo "</form>";
}

echo "<a href='install.php?step=3' class='btn' style='background: #10b981;'>↩️ العودة للتنصيب</a>";
echo "</div>";

// Show file info
echo "<div class='card'>";
echo "<h2>📝 معلومات إضافية</h2>";
echo "<p><strong>عدد الأسطر:</strong> " . count(explode("\n", $originalContent)) . "</p>";

// Count CREATE TABLE statements
preg_match_all('/CREATE TABLE/i', $originalContent, $matches);
echo "<p><strong>عدد جمل CREATE TABLE:</strong> " . count($matches[0]) . "</p>";

// Count INSERT statements
preg_match_all('/INSERT INTO/i', $originalContent, $matches);
echo "<p><strong>عدد جمل INSERT:</strong> " . count($matches[0]) . "</p>";

echo "</div>";

echo "</body>";
echo "</html>";
?>
