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

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

// =============================================
// دالة تهيئة السلة
// =============================================
if (!function_exists('initializeCart')) {
    function initializeCart() {
        if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) {
            $_SESSION['cart'] = [];
        }
        
        $_SESSION['cart'] = array_values(array_filter($_SESSION['cart'], function($item) {
            return is_array($item) && 
                   isset($item['meal_id'], $item['quantity']) && 
                   $item['quantity'] > 0;
        }));
        
        return $_SESSION['cart'];
    }
}

// =============================================
// دالة إضافة إلى السلة - نسخة MySQLi
// =============================================
if (!function_exists('addToCart')) {
    function addToCart($conn, $meal_id, $quantity = 1, $portion_id = null, $portion_name = 'كامل', $portion_price = 0) {
        $response = ['success' => false, 'message' => ''];
        
        try {
            $meal_id = (int)$meal_id;
            $quantity = (int)$quantity;
            
            if ($meal_id <= 0 || $quantity <= 0 || $quantity > 99) {
                $response['message'] = 'بيانات غير صالحة';
                return $response;
            }
            
            // جلب بيانات الوجبة
            $sql = "SELECT * FROM meals WHERE id = $meal_id AND is_active = 1";
            $result = $conn->query($sql);
            
            if (!$result || $result->num_rows == 0) {
                $response['message'] = 'الوجبة غير موجودة';
                return $response;
            }
            
            $meal = $result->fetch_assoc();
            
            // حساب السعر النهائي
            $final_price = (float)$meal['price'];
            if ($portion_id && $meal['has_portions']) {
                $portion_id = (int)$portion_id;
                $portion_sql = "SELECT * FROM meal_portions WHERE id = $portion_id AND meal_id = $meal_id AND is_active = 1";
                $portion_result = $conn->query($portion_sql);
                
                if ($portion_result && $portion_result->num_rows > 0) {
                    $portion = $portion_result->fetch_assoc();
                    $final_price = (float)$portion['price'];
                    $portion_name = $portion['name'];
                }
            }
            
            // التحقق من وجود العنصر في السلة
            $item_exists = false;
            foreach ($_SESSION['cart'] as $key => $item) {
                if ($item['meal_id'] == $meal_id && $item['portion_id'] == $portion_id) {
                    $_SESSION['cart'][$key]['quantity'] += $quantity;
                    $item_exists = true;
                    $response['success'] = true;
                    $response['message'] = "✅ تم تحديث الكمية في السلة";
                    break;
                }
            }
            
            // إضافة عنصر جديد
            if (!$item_exists) {
                $new_item = [
                    'meal_id' => $meal_id,
                    'meal_name' => $meal['name'],
                    'quantity' => $quantity,
                    'base_price' => (float)$meal['price'],
                    'final_price' => $final_price,
                    'portion_id' => $portion_id ? (int)$portion_id : null,
                    'portion_name' => $portion_name,
                    'portion_price' => $final_price,
                    'image' => $meal['image'] ?? '',
                    'has_portions' => (bool)($meal['has_portions'] ?? false)
                ];
                
                $_SESSION['cart'][] = $new_item;
                $response['success'] = true;
                $response['message'] = "✅ تم إضافة {$quantity} × {$meal['name']} إلى السلة";
            }
            
            // إعادة ترتيب السلة
            $_SESSION['cart'] = array_values($_SESSION['cart']);
            
        } catch (Exception $e) {
            error_log("Add to cart error: " . $e->getMessage());
            $response['message'] = 'حدث خطأ في إضافة المنتج';
        }
        
        return $response;
    }
}

// =============================================
// دالة تحديث السلة
// =============================================
if (!function_exists('updateCart')) {
    function updateCart($post_data) {
        if (!isset($_SESSION['cart'])) {
            return false;
        }
        
        if (isset($post_data['quantity']) && is_array($post_data['quantity'])) {
            foreach ($post_data['quantity'] as $index => $quantity) {
                $index = (int)$index;
                $quantity = (int)$quantity;
                
                if (isset($_SESSION['cart'][$index])) {
                    if ($quantity <= 0) {
                        unset($_SESSION['cart'][$index]);
                    } else {
                        $_SESSION['cart'][$index]['quantity'] = min(99, max(1, $quantity));
                        
                        if (isset($post_data['portion_id'][$index])) {
                            $_SESSION['cart'][$index]['portion_id'] = !empty($post_data['portion_id'][$index]) ? (int)$post_data['portion_id'][$index] : null;
                        }
                        if (isset($post_data['portion_name'][$index])) {
                            $_SESSION['cart'][$index]['portion_name'] = htmlspecialchars($post_data['portion_name'][$index], ENT_QUOTES, 'UTF-8');
                        }
                        if (isset($post_data['portion_price'][$index])) {
                            $price = (float)$post_data['portion_price'][$index];
                            $_SESSION['cart'][$index]['portion_price'] = $price;
                            $_SESSION['cart'][$index]['final_price'] = $price;
                        }
                    }
                }
            }
            
            $_SESSION['cart'] = array_values($_SESSION['cart']);
            return true;
        }
        
        return false;
    }
}

// =============================================
// دالة حذف عنصر من السلة
// =============================================
if (!function_exists('removeFromCart')) {
    function removeFromCart($item_index) {
        $item_index = (int)$item_index;
        
        if (isset($_SESSION['cart'][$item_index])) {
            unset($_SESSION['cart'][$item_index]);
            $_SESSION['cart'] = array_values($_SESSION['cart']);
            return true;
        }
        return false;
    }
}

// =============================================
// دالة تفريغ السلة
// =============================================
if (!function_exists('clearCart')) {
    function clearCart() {
        $_SESSION['cart'] = [];
        return true;
    }
}

// =============================================
// دالة حساب إجمالي السلة (القيمة المالية)
// =============================================
if (!function_exists('calculateCartTotal')) {
    function calculateCartTotal($cart_items) {
        $total = 0;
        
        if (is_array($cart_items)) {
            foreach ($cart_items as $item) {
                if (isset($item['final_price'], $item['quantity'])) {
                    $total += (float)$item['final_price'] * (int)$item['quantity'];
                }
            }
        }
        
        return $total;
    }
}

// =============================================
// دالة حساب عدد عناصر السلة (الكمية)
// =============================================
if (!function_exists('calculateCartCount')) {
    function calculateCartCount($cart = null) {
        if ($cart === null) {
            if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) {
                return 0;
            }
            $cart = $_SESSION['cart'];
        }
        
        $count = 0;
        
        if (is_array($cart)) {
            foreach ($cart as $item) {
                if (is_array($item) && isset($item['quantity'])) {
                    $count += (int)$item['quantity'];
                }
            }
        }
        
        return $count;
    }
}

// =============================================
// دالة جلب بيانات السلة كاملة - نسخة MySQLi
// =============================================
if (!function_exists('getCartData')) {
    function getCartData($conn) {
        $cart = initializeCart();
        $items = [];
        $total = 0;
        
        if (empty($cart)) {
            return ['items' => $items, 'total' => $total];
        }
        
        $meal_ids = [];
        foreach ($cart as $item) {
            if (isset($item['meal_id'])) {
                $meal_ids[] = (int)$item['meal_id'];
            }
        }
        
        if (empty($meal_ids)) {
            return ['items' => $items, 'total' => $total];
        }
        
        $ids_string = implode(',', $meal_ids);
        $sql = "SELECT id, name, price, image, has_portions FROM meals WHERE id IN ($ids_string) AND is_active = 1";
        
        $result = $conn->query($sql);
        $meals_by_id = [];
        
        if ($result) {
            while ($meal = $result->fetch_assoc()) {
                $meals_by_id[$meal['id']] = $meal;
            }
        }
        
        foreach ($cart as $index => $item) {
            $meal_id = $item['meal_id'];
            
            if (!isset($meals_by_id[$meal_id])) {
                continue;
            }
            
            $meal = $meals_by_id[$meal_id];
            $quantity = (int)($item['quantity'] ?? 1);
            $final_price = (float)($item['final_price'] ?? $meal['price']);
            $subtotal = $final_price * $quantity;
            $total += $subtotal;
            
            $items[] = [
                'index' => $index,
                'id' => $meal['id'],
                'name' => $meal['name'],
                'base_price' => (float)$meal['price'],
                'final_price' => $final_price,
                'image' => $meal['image'] ?? '',
                'quantity' => $quantity,
                'subtotal' => $subtotal,
                'portion_id' => $item['portion_id'] ?? null,
                'portion_name' => $item['portion_name'] ?? 'كامل',
                'has_portions' => (bool)($meal['has_portions'] ?? false)
            ];
        }
        
        return ['items' => $items, 'total' => $total];
    }
}

// =============================================
// دالة التحقق من وجود عنصر في السلة
// =============================================
if (!function_exists('isInCart')) {
    function isInCart($meal_id, $portion_id = null) {
        $cart = initializeCart();
        
        foreach ($cart as $index => $item) {
            if ($item['meal_id'] == $meal_id) {
                if ($portion_id === null || $item['portion_id'] == $portion_id) {
                    return ['index' => $index, 'item' => $item];
                }
            }
        }
        
        return false;
    }
}

// =============================================
// دالة الحصول على عدد عناصر السلة
// =============================================
if (!function_exists('getCartCount')) {
    function getCartCount() {
        return calculateCartCount();
    }
}
// =============================================
// دالة حساب عدد عناصر السلة - مهمة جداً
// =============================================
if (!function_exists('calculateCartCount')) {
    function calculateCartCount($cart = null) {
        if ($cart === null) {
            if (!isset($_SESSION['cart']) || !is_array($_SESSION['cart'])) {
                return 0;
            }
            $cart = $_SESSION['cart'];
        }
        
        $count = 0;
        
        if (is_array($cart)) {
            foreach ($cart as $item) {
                if (is_array($item) && isset($item['quantity'])) {
                    $count += (int)$item['quantity'];
                }
            }
        }
        
        return $count;
    }
}

?>