<?php
/**
 * meal_functions.php - دوال الوجبات المحسنة
 * نسخة MySQLi - متوافقة تماماً مع اتصال قاعدة البيانات الخاص بك
 */

if (!defined('SECURE_ACCESS')) {
    die('الوصول المباشر غير مسموح');
}

// =============================================
// جلب الوجبات مع Caching - نسخة MySQLi
// =============================================

if (!function_exists('getMealsWithCachingMySQLi')) {
    function getMealsWithCachingMySQLi($conn, $category_id = 'all', $search_query = '', $limit = 50) {
        $cache_key = 'meals_mysqli_' . md5($category_id . '_' . $search_query . '_' . $limit);
        
        return getCachedData($cache_key, function() use ($conn, $category_id, $search_query, $limit) {
            return getMealsMySQLi($conn, $category_id, $search_query, $limit);
        }, 600); // Cache 10 دقائق
    }
}

// =============================================
// جلب الوجبات من قاعدة البيانات - نسخة MySQLi
// =============================================

if (!function_exists('getMealsMySQLi')) {
    function getMealsMySQLi($conn, $category_id = 'all', $search_query = '', $limit = 50) {
        try {
            $params = [];
            $conditions = ["m.is_active = 1"];
            
            // فلترة حسب التصنيف
            if ($category_id != 'all' && is_numeric($category_id)) {
                $conditions[] = "m.category_id = " . (int)$category_id;
            }
            
            // فلترة حسب البحث
            if (!empty($search_query)) {
                $search_term = $conn->real_escape_string($search_query);
                $conditions[] = "(m.name LIKE '%$search_term%' OR m.description LIKE '%$search_term%')";
            }
            
            // بناء جملة WHERE
            $where_clause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";
            
            // استعلام محسن
            $sql = "
                SELECT 
                    m.*,
                    c.name as category_name,
                    c.id as category_id,
                    CASE 
                        WHEN m.has_portions = 1 AND EXISTS (
                            SELECT 1 FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1
                        ) THEN 1 ELSE 0 
                    END as has_active_portions,
                    (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                FROM meals m
                LEFT JOIN categories c ON m.category_id = c.id
                {$where_clause}
                ORDER BY 
                    m.featured DESC,
                    m.created_at DESC
                LIMIT " . (int)$limit . "
            ";
            
            $result = $conn->query($sql);
            
            if (!$result) {
                throw new Exception($conn->error);
            }
            
            $meals = [];
            while ($row = $result->fetch_assoc()) {
                $meals[] = $row;
            }
            
            return $meals;
            
        } catch (Exception $e) {
            logError("Error fetching meals (MySQLi): " . $e->getMessage());
            return [];
        }
    }
}

// =============================================
// جلب وجبة واحدة - نسخة MySQLi
// =============================================

if (!function_exists('getMealByIdMySQLi')) {
    function getMealByIdMySQLi($conn, $meal_id, $force_refresh = false) {
        $cache_key = 'meal_mysqli_' . $meal_id;
        
        if ($force_refresh) {
            clearCache($cache_key);
        }
        
        return getCachedData($cache_key, function() use ($conn, $meal_id) {
            try {
                $meal_id = (int)$meal_id;
                
                $sql = "
                    SELECT 
                        m.*,
                        c.name as category_name,
                        c.id as category_id,
                        (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                    FROM meals m
                    LEFT JOIN categories c ON m.category_id = c.id
                    WHERE m.id = $meal_id AND m.is_active = 1
                ";
                
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                return $result->fetch_assoc();
                
            } catch (Exception $e) {
                logError("Error fetching meal $meal_id (MySQLi): " . $e->getMessage());
                return null;
            }
        }, 1800); // Cache 30 دقيقة
    }
}

// =============================================
// جلب أقسام الوجبة - نسخة MySQLi
// =============================================

if (!function_exists('getMealPortionsCachedMySQLi')) {
    function getMealPortionsCachedMySQLi($conn, $meal_id, $cache_time = 3600) {
        static $portions_static_cache = [];
        
        $cache_key = 'portions_mysqli_' . $meal_id;
        
        // 1. Static Cache (أسرع)
        if (isset($portions_static_cache[$cache_key])) {
            return $portions_static_cache[$cache_key];
        }
        
        // 2. Session Cache
        if (isset($_SESSION['cache'][$cache_key]) && $_SESSION['cache'][$cache_key]['expires'] > time()) {
            $portions = $_SESSION['cache'][$cache_key]['data'];
            $portions_static_cache[$cache_key] = $portions;
            return $portions;
        }
        
        // 3. Database Query
        try {
            $meal_id = (int)$meal_id;
            
            $sql = "
                SELECT 
                    id, 
                    name, 
                    price,
                    description,
                    is_default,
                    sort_order
                FROM meal_portions 
                WHERE meal_id = $meal_id AND is_active = 1 
                ORDER BY sort_order ASC, price ASC
            ";
            
            $result = $conn->query($sql);
            
            if (!$result) {
                throw new Exception($conn->error);
            }
            
            $portions = [];
            while ($row = $result->fetch_assoc()) {
                $portions[] = $row;
            }
            
            // تخزين في الكاش
            $portions_static_cache[$cache_key] = $portions;
            
            $expires = time() + $cache_time;
            $_SESSION['cache'][$cache_key] = ['data' => $portions, 'expires' => $expires];
            
            return $portions;
            
        } catch (Exception $e) {
            logError("Error fetching portions for meal $meal_id (MySQLi): " . $e->getMessage());
            return [];
        }
    }
}

// =============================================
// جلب الوجبات المميزة - نسخة MySQLi
// =============================================

if (!function_exists('getFeaturedMealsMySQLi')) {
    function getFeaturedMealsMySQLi($conn, $limit = 10) {
        $cache_key = 'featured_meals_mysqli_' . $limit;
        
        return getCachedData($cache_key, function() use ($conn, $limit) {
            try {
                $limit = (int)$limit;
                
                $sql = "
                    SELECT 
                        m.*,
                        c.name as category_name,
                        (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                    FROM meals m
                    LEFT JOIN categories c ON m.category_id = c.id
                    WHERE m.is_active = 1 AND m.featured = 1
                    ORDER BY m.created_at DESC
                    LIMIT $limit
                ";
                
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                $meals = [];
                while ($row = $result->fetch_assoc()) {
                    $meals[] = $row;
                }
                
                return $meals;
                
            } catch (Exception $e) {
                logError("Error fetching featured meals (MySQLi): " . $e->getMessage());
                return [];
            }
        }, 1800); // Cache 30 دقيقة
    }
}

// =============================================
// جلب الوجبات الأكثر مبيعاً - نسخة MySQLi
// =============================================

if (!function_exists('getBestSellingMealsMySQLi')) {
    function getBestSellingMealsMySQLi($conn, $limit = 10) {
        $cache_key = 'best_selling_meals_mysqli_' . $limit;
        
        return getCachedData($cache_key, function() use ($conn, $limit) {
            try {
                $limit = (int)$limit;
                
                $sql = "
                    SELECT 
                        m.*,
                        c.name as category_name,
                        COUNT(oi.id) as sales_count,
                        SUM(oi.quantity) as total_quantity,
                        (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                    FROM meals m
                    LEFT JOIN categories c ON m.category_id = c.id
                    LEFT JOIN order_items oi ON m.id = oi.meal_id
                    LEFT JOIN orders o ON oi.order_id = o.id
                    WHERE m.is_active = 1 
                        AND o.status IN ('delivered', 'accepted')
                        AND o.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
                    GROUP BY m.id
                    ORDER BY total_quantity DESC
                    LIMIT $limit
                ";
                
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                $meals = [];
                while ($row = $result->fetch_assoc()) {
                    $meals[] = $row;
                }
                
                return $meals;
                
            } catch (Exception $e) {
                logError("Error fetching best selling meals (MySQLi): " . $e->getMessage());
                return getFeaturedMealsMySQLi($conn, $limit);
            }
        }, 3600); // Cache ساعة
    }
}

// =============================================
// جلب الوجبات المقترحة - نسخة MySQLi
// =============================================

if (!function_exists('getRelatedMealsMySQLi')) {
    function getRelatedMealsMySQLi($conn, $meal_id, $category_id, $limit = 6) {
        $cache_key = 'related_meals_mysqli_' . $meal_id . '_' . $limit;
        
        return getCachedData($cache_key, function() use ($conn, $meal_id, $category_id, $limit) {
            try {
                $meal_id = (int)$meal_id;
                $category_id = (int)$category_id;
                $limit = (int)$limit;
                
                $sql = "
                    SELECT 
                        m.*,
                        c.name as category_name,
                        (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                    FROM meals m
                    LEFT JOIN categories c ON m.category_id = c.id
                    WHERE m.category_id = $category_id 
                        AND m.id != $meal_id 
                        AND m.is_active = 1
                    ORDER BY RAND()
                    LIMIT $limit
                ";
                
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                $meals = [];
                while ($row = $result->fetch_assoc()) {
                    $meals[] = $row;
                }
                
                return $meals;
                
            } catch (Exception $e) {
                logError("Error fetching related meals (MySQLi): " . $e->getMessage());
                return [];
            }
        }, 3600); // Cache ساعة
    }
}

// =============================================
// البحث المتقدم في الوجبات - نسخة MySQLi
// =============================================

if (!function_exists('searchMealsMySQLi')) {
    function searchMealsMySQLi($conn, $query, $filters = []) {
        $cache_key = 'search_mysqli_' . md5($query . serialize($filters));
        
        return getCachedData($cache_key, function() use ($conn, $query, $filters) {
            try {
                $conditions = ["m.is_active = 1"];
                
                // البحث في الاسم والوصف
                if (!empty($query)) {
                    $search_term = $conn->real_escape_string($query);
                    $conditions[] = "(m.name LIKE '%$search_term%' OR m.description LIKE '%$search_term%' OR m.tags LIKE '%$search_term%')";
                }
                
                // فلترة حسب التصنيف
                if (!empty($filters['category_id'])) {
                    $conditions[] = "m.category_id = " . (int)$filters['category_id'];
                }
                
                // فلترة حسب السعر
                if (isset($filters['min_price'])) {
                    $conditions[] = "m.price >= " . (float)$filters['min_price'];
                }
                
                if (isset($filters['max_price'])) {
                    $conditions[] = "m.price <= " . (float)$filters['max_price'];
                }
                
                // فلترة حسب وجود أقسام
                if (isset($filters['has_portions'])) {
                    $conditions[] = "m.has_portions = " . (int)$filters['has_portions'];
                }
                
                // بناء ORDER BY
                $order_by = "m.created_at DESC";
                if (!empty($filters['sort'])) {
                    switch ($filters['sort']) {
                        case 'price_asc':
                            $order_by = "m.price ASC";
                            break;
                        case 'price_desc':
                            $order_by = "m.price DESC";
                            break;
                        case 'name_asc':
                            $order_by = "m.name ASC";
                            break;
                        case 'popular':
                            $order_by = "m.featured DESC, m.created_at DESC";
                            break;
                    }
                }
                
                $where_clause = implode(" AND ", $conditions);
                
                $sql = "
                    SELECT 
                        m.*,
                        c.name as category_name,
                        (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                    FROM meals m
                    LEFT JOIN categories c ON m.category_id = c.id
                    WHERE {$where_clause}
                    ORDER BY {$order_by}
                    LIMIT 50
                ";
                
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                $meals = [];
                while ($row = $result->fetch_assoc()) {
                    $meals[] = $row;
                }
                
                return $meals;
                
            } catch (Exception $e) {
                logError("Error searching meals (MySQLi): " . $e->getMessage());
                return [];
            }
        }, 300); // Cache 5 دقائق
    }
}

// =============================================
// جلب الوجبات حسب التصنيف مع Pagination - نسخة MySQLi
// =============================================

if (!function_exists('getMealsByCategoryMySQLi')) {
    function getMealsByCategoryMySQLi($conn, $category_id, $page = 1, $per_page = 20) {
        $offset = ($page - 1) * $per_page;
        $cache_key = 'category_meals_mysqli_' . $category_id . '_' . $page . '_' . $per_page;
        
        return getCachedData($cache_key, function() use ($conn, $category_id, $per_page, $offset) {
            try {
                $category_id = (int)$category_id;
                $per_page = (int)$per_page;
                $offset = (int)$offset;
                
                // جلب الوجبات
                $sql = "
                    SELECT 
                        m.*,
                        c.name as category_name,
                        (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                    FROM meals m
                    LEFT JOIN categories c ON m.category_id = c.id
                    WHERE m.category_id = $category_id AND m.is_active = 1
                    ORDER BY m.featured DESC, m.created_at DESC
                    LIMIT $per_page OFFSET $offset
                ";
                
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                $meals = [];
                while ($row = $result->fetch_assoc()) {
                    $meals[] = $row;
                }
                
                // جلب العدد الإجمالي
                $count_sql = "SELECT COUNT(*) as total FROM meals WHERE category_id = $category_id AND is_active = 1";
                $count_result = $conn->query($count_sql);
                $total = 0;
                
                if ($count_result) {
                    $row = $count_result->fetch_assoc();
                    $total = $row['total'];
                }
                
                return [
                    'meals' => $meals,
                    'total' => (int)$total,
                    'page' => $page,
                    'per_page' => $per_page,
                    'total_pages' => ceil($total / $per_page)
                ];
                
            } catch (Exception $e) {
                logError("Error fetching meals by category (MySQLi): " . $e->getMessage());
                return [
                    'meals' => [],
                    'total' => 0,
                    'page' => $page,
                    'per_page' => $per_page,
                    'total_pages' => 0
                ];
            }
        }, 600); // Cache 10 دقائق
    }
}

// =============================================
// جلب الوجبات العشوائية - نسخة MySQLi
// =============================================

if (!function_exists('getRandomMealsMySQLi')) {
    function getRandomMealsMySQLi($conn, $limit = 6, $exclude_ids = []) {
        $cache_key = 'random_meals_mysqli_' . $limit . '_' . md5(implode(',', $exclude_ids));
        
        return getCachedData($cache_key, function() use ($conn, $limit, $exclude_ids) {
            try {
                $limit = (int)$limit;
                
                $sql = "
                    SELECT 
                        m.*,
                        c.name as category_name,
                        (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                    FROM meals m
                    LEFT JOIN categories c ON m.category_id = c.id
                    WHERE m.is_active = 1
                ";
                
                if (!empty($exclude_ids)) {
                    $exclude_ids = array_map('intval', $exclude_ids);
                    $exclude_str = implode(',', $exclude_ids);
                    $sql .= " AND m.id NOT IN ($exclude_str)";
                }
                
                $sql .= " ORDER BY RAND() LIMIT $limit";
                
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                $meals = [];
                while ($row = $result->fetch_assoc()) {
                    $meals[] = $row;
                }
                
                return $meals;
                
            } catch (Exception $e) {
                logError("Error fetching random meals (MySQLi): " . $e->getMessage());
                return [];
            }
        }, 1800); // Cache 30 دقيقة
    }
}

// =============================================
// التحقق من توفر الوجبة - نسخة MySQLi
// =============================================

if (!function_exists('isMealAvailableMySQLi')) {
    function isMealAvailableMySQLi($conn, $meal_id) {
        $cache_key = 'meal_available_mysqli_' . $meal_id;
        
        return getCachedData($cache_key, function() use ($conn, $meal_id) {
            try {
                $meal_id = (int)$meal_id;
                
                $sql = "SELECT is_active FROM meals WHERE id = $meal_id AND is_active = 1";
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                return $result->num_rows > 0;
                
            } catch (Exception $e) {
                logError("Error checking meal availability (MySQLi): " . $e->getMessage());
                return false;
            }
        }, 300); // Cache 5 دقائق
    }
}

// =============================================
// تحديث كاش الوجبات - نسخة MySQLi
// =============================================

if (!function_exists('refreshMealsCacheMySQLi')) {
    function refreshMealsCacheMySQLi($meal_id = null) {
        if ($meal_id) {
            clearCache('meal_mysqli_' . $meal_id);
            clearCache('portions_mysqli_' . $meal_id);
            clearCache('meal_available_mysqli_' . $meal_id);
        } else {
            clearCache('meals_mysqli_*');
            clearCache('featured_meals_mysqli_*');
            clearCache('best_selling_meals_mysqli_*');
            clearCache('category_meals_mysqli_*');
            clearCache('related_meals_mysqli_*');
            clearCache('random_meals_mysqli_*');
            clearCache('search_mysqli_*');
        }
        
        return true;
    }
}

// =============================================
// تصدير بيانات الوجبات للتطبيق - نسخة MySQLi
// =============================================

if (!function_exists('exportMealsForAppMySQLi')) {
    function exportMealsForAppMySQLi($conn, $last_sync = null) {
        $cache_key = 'app_meals_export_mysqli_' . ($last_sync ?? 'full');
        
        return getCachedData($cache_key, function() use ($conn, $last_sync) {
            try {
                $sql = "
                    SELECT 
                        m.id,
                        m.name,
                        m.description,
                        m.price,
                        m.image,
                        m.has_portions,
                        m.featured,
                        m.created_at,
                        m.updated_at,
                        c.id as category_id,
                        c.name as category_name,
                        (SELECT COUNT(*) FROM meal_portions mp WHERE mp.meal_id = m.id AND mp.is_active = 1) as portions_count
                    FROM meals m
                    LEFT JOIN categories c ON m.category_id = c.id
                    WHERE m.is_active = 1
                ";
                
                if ($last_sync) {
                    $last_sync = $conn->real_escape_string($last_sync);
                    $sql .= " AND (m.updated_at > '$last_sync' OR m.created_at > '$last_sync')";
                }
                
                $result = $conn->query($sql);
                
                if (!$result) {
                    throw new Exception($conn->error);
                }
                
                $meals = [];
                while ($row = $result->fetch_assoc()) {
                    $meals[] = $row;
                }
                
                foreach ($meals as &$meal) {
                    if ($meal['has_portions'] && $meal['portions_count'] > 0) {
                        $meal['portions'] = getMealPortionsCachedMySQLi($conn, $meal['id']);
                    } else {
                        $meal['portions'] = [];
                    }
                    
                    if (!empty($meal['image'])) {
                        $meal['image_url'] = '../../admin/uploads/' . $meal['image'];
                        $meal['thumbnail_url'] = '../../admin/uploads/thumb_' . $meal['image'];
                    }
                }
                
                return [
                    'success' => true,
                    'timestamp' => time(),
                    'meals' => $meals,
                    'total' => count($meals)
                ];
                
            } catch (Exception $e) {
                logError("Error exporting meals for app (MySQLi): " . $e->getMessage());
                return [
                    'success' => false,
                    'message' => 'حدث خطأ في تصدير البيانات'
                ];
            }
        }, 300); // Cache 5 دقائق
    }
}

// =============================================
// الحفاظ على التوافق مع الإصدارات السابقة
// =============================================

// =============================================
// الحفاظ على التوافق مع الإصدارات السابقة
// =============================================

if (!function_exists('getMealsWithCaching')) {
    function getMealsWithCaching($conn, $category_id = 'all', $search_query = '', $limit = 50) {
        return getMealsWithCachingMySQLi($conn, $category_id, $search_query, $limit);
    }
}

if (!function_exists('getMealPortionsCached')) {
    function getMealPortionsCached($conn, $meal_id, $cache_time = 3600) {
        return getMealPortionsCachedMySQLi($conn, $meal_id, $cache_time);
    }
}

if (!function_exists('getMealById')) {
    function getMealById($conn, $meal_id, $force_refresh = false) {
        return getMealByIdMySQLi($conn, $meal_id, $force_refresh);
    }
}

if (!function_exists('getFeaturedMeals')) {
    function getFeaturedMeals($conn, $limit = 10) {
        return getFeaturedMealsMySQLi($conn, $limit);
    }
}

if (!function_exists('getBestSellingMeals')) {
    function getBestSellingMeals($conn, $limit = 10) {
        return getBestSellingMealsMySQLi($conn, $limit);
    }
}

if (!function_exists('getUnreadTicketsCount')) {
    function getUnreadTicketsCount($conn, $customer_id) {
        return getUnreadTicketsCountMySQLi($conn, $customer_id);
    }
}
// =============================================
// دوال التوافق - إضافية
// =============================================

if (!function_exists('getUnreadTicketsCount')) {
    function getUnreadTicketsCount($conn, $customer_id) {
        return getUnreadTicketsCountMySQLi($conn, $customer_id);
    }
}

// دالة بديلة للشكاوي - في حال عدم وجود جدول ticket_messages
if (!function_exists('getUnreadTicketsCountMySQLi')) {
    function getUnreadTicketsCountMySQLi($conn, $customer_id) {
        // التحقق من وجود الجدول أولاً
        $table_check = $conn->query("SHOW TABLES LIKE 'ticket_messages'");
        if ($table_check->num_rows == 0) {
            return 0; // الجدول غير موجود
        }
        
        try {
            $customer_id = (int)$customer_id;
            
            $sql = "
                SELECT COUNT(*) as count
                FROM ticket_messages m
                JOIN customer_tickets t ON m.ticket_id = t.id
                WHERE t.customer_id = $customer_id 
                AND m.sender_type = 'admin' 
                AND (m.is_read = 0 OR m.is_read IS NULL)
            ";
            
            $result = $conn->query($sql);
            
            if ($result && $result->num_rows > 0) {
                $row = $result->fetch_assoc();
                return (int)($row['count'] ?? 0);
            }
            
            return 0;
            
        } catch (Exception $e) {
            error_log("Error in getUnreadTicketsCountMySQLi: " . $e->getMessage());
            return 0;
        }
    }
}

// =============================================
// دالة جلب الوجبات مع Caching - اسم قصير
// =============================================
if (!function_exists('getMealsWithCaching')) {
    function getMealsWithCaching($conn, $category_id = 'all', $search_query = '', $limit = 50) {
        return getMealsWithCachingMySQLi($conn, $category_id, $search_query, $limit);
    }
}

// =============================================
// دالة عدد الشكاوي غير المقروءة
// =============================================
if (!function_exists('getUnreadTicketsCount')) {
    function getUnreadTicketsCount($conn, $customer_id) {
        // تأكد من وجود الدالة الأصلية
        if (function_exists('getUnreadTicketsCountMySQLi')) {
            return getUnreadTicketsCountMySQLi($conn, $customer_id);
        }
        
        // إذا الدالة غير موجودة، نرجع 0
        return 0;
    }
}

// =============================================
// دالة بديلة للشكاوي - تعريف كامل
// =============================================
if (!function_exists('getUnreadTicketsCountMySQLi')) {
    function getUnreadTicketsCountMySQLi($conn, $customer_id) {
        try {
            $customer_id = (int)$customer_id;
            
            // التحقق من وجود الجدول أولاً
            $table_check = $conn->query("SHOW TABLES LIKE 'ticket_messages'");
            if (!$table_check || $table_check->num_rows == 0) {
                return 0; // الجدول غير موجود
            }
            
            $sql = "
                SELECT COUNT(*) as count
                FROM ticket_messages m
                JOIN customer_tickets t ON m.ticket_id = t.id
                WHERE t.customer_id = $customer_id 
                AND m.sender_type = 'admin' 
                AND (m.is_read = 0 OR m.is_read IS NULL)
            ";
            
            $result = $conn->query($sql);
            
            if ($result && $result->num_rows > 0) {
                $row = $result->fetch_assoc();
                return (int)($row['count'] ?? 0);
            }
            
            return 0;
            
        } catch (Exception $e) {
            error_log("Error in getUnreadTicketsCountMySQLi: " . $e->getMessage());
            return 0;
        }
    }
}

// =============================================
// دوال التوافق - مهمة جداً للتشغيل
// =============================================

if (!function_exists('getMealsWithCaching')) {
    function getMealsWithCaching($conn, $category_id = 'all', $search_query = '', $limit = 50) {
        return getMealsWithCachingMySQLi($conn, $category_id, $search_query, $limit);
    }
}

if (!function_exists('getMealPortionsCached')) {
    function getMealPortionsCached($conn, $meal_id, $cache_time = 3600) {
        return getMealPortionsCachedMySQLi($conn, $meal_id, $cache_time);
    }
}

if (!function_exists('getMealById')) {
    function getMealById($conn, $meal_id, $force_refresh = false) {
        return getMealByIdMySQLi($conn, $meal_id, $force_refresh);
    }
}

if (!function_exists('getFeaturedMeals')) {
    function getFeaturedMeals($conn, $limit = 10) {
        return getFeaturedMealsMySQLi($conn, $limit);
    }
}

if (!function_exists('getBestSellingMeals')) {
    function getBestSellingMeals($conn, $limit = 10) {
        return getBestSellingMealsMySQLi($conn, $limit);
    }
}

if (!function_exists('getUnreadTicketsCount')) {
    function getUnreadTicketsCount($conn, $customer_id) {
        return getUnreadTicketsCountMySQLi($conn, $customer_id);
    }
}
?>