<?php
/**
 * تعيين الصور الموجودة للمنتجات تلقائياً
 */

require_once 'config/database.php';

$database = new Database();
$db = $database->getConnection();

echo "<!DOCTYPE html>
<html lang='ar' dir='rtl'>
<head>
    <meta charset='UTF-8'>
    <title>تعيين الصور تلقائياً</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
        .container { max-width: 900px; margin: 0 auto; background: white; padding: 30px; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); }
        h1 { color: #E57393; border-bottom: 3px solid #E57393; padding-bottom: 15px; margin-bottom: 25px; }
        .success { background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin: 10px 0; border-right: 4px solid #28a745; }
        .info { background: #d1ecf1; color: #0c5460; padding: 15px; border-radius: 8px; margin: 10px 0; border-right: 4px solid #17a2b8; }
        .warning { background: #fff3cd; color: #856404; padding: 15px; border-radius: 8px; margin: 10px 0; border-right: 4px solid #ffc107; }
        .product-item { background: #f8f9fa; padding: 15px; margin: 10px 0; border-radius: 8px; border-right: 3px solid #6c757d; display: flex; align-items: center; gap: 15px; }
        .product-item img { width: 80px; height: 80px; object-fit: cover; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.2); }
        .product-info { flex: 1; }
        .product-info strong { color: #E57393; font-size: 16px; }
        .btn { display: inline-block; padding: 12px 24px; background: #E57393; color: white; text-decoration: none; border-radius: 50px; margin: 10px 5px; font-weight: 600; transition: all 0.3s; }
        .btn:hover { background: #D1537A; transform: translateY(-2px); }
        .btn-secondary { background: #6c757d; }
        .btn-secondary:hover { background: #5a6268; }
    </style>
</head>
<body>
<div class='container'>";

echo "<h1>🎨 تعيين الصور تلقائياً</h1>";

try {
    // جلب جميع الصور الموجودة
    $images_dir = 'uploads/products/';
    $all_files = scandir($images_dir);
    $image_files = array_filter($all_files, function($file) use ($images_dir) {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        return in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp']) && 
               is_file($images_dir . $file) &&
               !strpos($file, 'product_add_'); // استبعاد الصور الإضافية
    });
    
    // ترتيب الصور حسب التاريخ (الأحدث أولاً)
    usort($image_files, function($a, $b) use ($images_dir) {
        return filemtime($images_dir . $b) - filemtime($images_dir . $a);
    });
    
    echo "<div class='info'>📊 تم العثور على <strong>" . count($image_files) . "</strong> صورة متاحة</div>";
    
    // جلب المنتجات بدون صور أو بصور مفقودة
    $stmt = $db->prepare("SELECT id, name, image FROM products ORDER BY id");
    $stmt->execute();
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $assigned_count = 0;
    $image_index = 0;
    
    foreach ($products as $product) {
        $product_id = $product['id'];
        $product_name = htmlspecialchars($product['name']);
        $current_image = $product['image'];
        
        // تحقق إذا كانت الصورة الحالية موجودة
        $image_exists = false;
        if (!empty($current_image)) {
            $possible_paths = [
                $current_image,
                'uploads/products/' . $current_image,
                'uploads/products/' . basename($current_image),
            ];
            
            foreach ($possible_paths as $path) {
                if (file_exists($path)) {
                    $image_exists = true;
                    break;
                }
            }
        }
        
        // إذا كانت الصورة مفقودة، عيّن صورة جديدة
        if (!$image_exists && $image_index < count($image_files)) {
            $new_image = 'uploads/products/' . $image_files[$image_index];
            
            // تحديث قاعدة البيانات
            $update_stmt = $db->prepare("UPDATE products SET image = ? WHERE id = ?");
            $update_stmt->execute([$new_image, $product_id]);
            
            echo "<div class='product-item'>";
            echo "<img src='{$new_image}' alt='Product'>";
            echo "<div class='product-info'>";
            echo "<strong>المنتج #{$product_id}:</strong> {$product_name}<br>";
            echo "<small style='color: #28a745;'>✅ تم تعيين الصورة: " . htmlspecialchars($image_files[$image_index]) . "</small>";
            echo "</div>";
            echo "</div>";
            
            $assigned_count++;
            $image_index++;
        } else if ($image_exists) {
            echo "<div class='product-item'>";
            echo "<img src='{$current_image}' alt='Product'>";
            echo "<div class='product-info'>";
            echo "<strong>المنتج #{$product_id}:</strong> {$product_name}<br>";
            echo "<small style='color: #17a2b8;'>✓ الصورة موجودة بالفعل</small>";
            echo "</div>";
            echo "</div>";
        }
    }
    
    echo "<div class='success'>";
    echo "<h3>🎉 تم بنجاح!</h3>";
    echo "<p>تم تعيين <strong>{$assigned_count}</strong> صورة للمنتجات</p>";
    echo "</div>";
    
    if ($image_index < count($image_files)) {
        $remaining = count($image_files) - $image_index;
        echo "<div class='info'>";
        echo "<p>📦 يوجد <strong>{$remaining}</strong> صورة إضافية غير مستخدمة</p>";
        echo "</div>";
    }
    
} catch (PDOException $e) {
    echo "<div class='error'>❌ خطأ: " . htmlspecialchars($e->getMessage()) . "</div>";
}

echo "<div style='margin-top: 30px; text-align: center;'>";
echo "<a href='public/products.php' class='btn'>👁️ عرض المتجر</a>";
echo "<a href='public/index.php' class='btn btn-secondary'>🏠 الصفحة الرئيسية</a>";
echo "<a href='admin/products/index.php' class='btn btn-secondary'>⚙️ لوحة التحكم</a>";
echo "</div>";

echo "</div></body></html>";
?>
