<?php
/**
 * Auto Fix Pages - Add Discount & Cart Functions
 * تحديث تلقائي للصفحات
 */

echo "🚀 بدء التحديث التلقائي.../n/n";

$files_to_update = [
    '../public/index.php',
    '../public/products.php'
];

foreach ($files_to_update as $file) {
    if (!file_exists($file)) {
        echo "⚠️  الملف غير موجود: $file/n";
        continue;
    }
    
    echo "📝 تحديث: $file/n";
    
    $content = file_get_contents($file);
    $updated = false;
    
    // 1. Add CSS if not exists
    if (strpos($content, 'product-cards.css') === false) {
        $content = str_replace(
            '</head>',
            '    <link rel="stylesheet" href="assets/css/product-cards.css">' . "/n</head>",
            $content
        );
        echo "   ✅ أضيف CSS/n";
        $updated = true;
    }
    
    // 2. Add JS if not exists
    if (strpos($content, 'store.js') === false) {
        $content = str_replace(
            '</body>',
            '    <script src="assets/js/store.js"></script>' . "/n</body>",
            $content
        );
        echo "   ✅ أضيف JavaScript/n";
        $updated = true;
    }
    
    // 3. Add product-card include if not exists
    if (strpos($content, 'product-card.php') === false) {
        // Add after session_start or first require
        if (preg_match('/(session_start/(/);|require_once.*database/.php.*/n)/', $content, $matches, PREG_OFFSET_CAPTURE)) {
            $pos = $matches[0][1] + strlen($matches[0][0]);
            $content = substr_replace($content, "\nrequire_once '../includes/product-card.php';\n", $pos, 0);
            echo "   ✅ أضيف product-card include/n";
            $updated = true;
        }
    }
    
    if ($updated) {
        file_put_contents($file, $content);
        echo "   💾 تم الحفظ/n/n";
    } else {
        echo "   ℹ️  الملف محدث بالفعل/n/n";
    }
}

echo "✨ تم التحديث!/n/n";
echo "📋 الخطوة التالية:/n";
echo "   افتح index.php أو products.php/n";
echo "   واستبدل كود عرض المنتج بـ:/n";
echo "   <?php renderProductCard(/$product, /$currency_symbol); ?>/n/n";
