<?php
/**
 * discount_functions.php
 * دوال التخفيضات المحسنة - أداء عالي، Caching
 */

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

/**
 * جلب التخفيضات النشطة مع Caching
 */
function getActiveDiscounts($pdo) {
    $cache_key = 'active_discounts';
    
    return getCachedData($cache_key, function() use ($pdo) {
        $now = date('Y-m-d H:i:s');
        
        $sql = "
            SELECT * FROM direct_discounts 
            WHERE is_active = 1 
            AND start_date <= :now 
            AND (end_date >= :now OR end_date IS NULL)
            ORDER BY discount_value DESC
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':now', $now);
        $stmt->execute();
        
        return $stmt->fetchAll();
    }, 600); // Cache 10 دقائق
}

/**
 * حساب التخفيضات المطبقة
 */
function calculateApplicableDiscounts($pdo, $customer_id, $cart_total, $cart_items) {
    $discounts = getActiveDiscounts($pdo);
    $applicable_discounts = [];
    
    foreach ($discounts as $discount) {
        if (isDiscountApplicable($discount, $customer_id, $cart_total, $cart_items)) {
            $discount_amount = calculateDiscountAmount($discount, $cart_total);
            
            if ($discount_amount > 0) {
                $discount['calculated_amount'] = $discount_amount;
                $applicable_discounts[] = $discount;
            }
        }
    }
    
    if (!empty($applicable_discounts)) {
        // ترتيب تنازلي حسب قيمة الخصم
        usort($applicable_discounts, function($a, $b) {
            return $b['calculated_amount'] <=> $a['calculated_amount'];
        });
        
        return $applicable_discounts[0];
    }
    
    return null;
}

/**
 * التحقق من صلاحية التخفيض
 */
function isDiscountApplicable($discount, $customer_id, $cart_total, $cart_items) {
    // التحقق من الحد الأدنى للطلب
    if ($discount['min_order_amount'] > 0 && $cart_total < $discount['min_order_amount']) {
        return false;
    }
    
    // التحقق من التاريخ
    $now = date('Y-m-d H:i:s');
    if ($discount['start_date'] > $now) {
        return false;
    }
    
    if ($discount['end_date'] && $discount['end_date'] < $now) {
        return false;
    }
    
    // التحقق من نوع الهدف
    switch ($discount['target_type']) {
        case 'order':
            return true;
            
        case 'category':
            if ($discount['target_id']) {
                foreach ($cart_items as $item) {
                    if (isset($item['category_id']) && $item['category_id'] == $discount['target_id']) {
                        return true;
                    }
                }
            }
            return false;
            
        case 'meal':
            if ($discount['target_id']) {
                foreach ($cart_items as $item) {
                    if ($item['id'] == $discount['target_id']) {
                        return true;
                    }
                }
            }
            return false;
            
        case 'customer':
            return ($customer_id == $discount['target_id']);
            
        default:
            return false;
    }
}

/**
 * حساب قيمة التخفيض
 */
function calculateDiscountAmount($discount, $cart_total) {
    if ($discount['discount_type'] == 'percentage') {
        $amount = ($cart_total * $discount['discount_value']) / 100;
        
        if (isset($discount['max_discount']) && $discount['max_discount'] > 0 && $amount > $discount['max_discount']) {
            return (float)$discount['max_discount'];
        }
        
        return $amount;
    } else {
        // خصم ثابت
        return min((float)$discount['discount_value'], $cart_total);
    }
}

/**
 * التحقق من كود خصم
 */
function validateCouponCode($pdo, $code, $customer_id, $cart_total) {
    $cache_key = 'coupon_' . md5($code);
    
    $coupon = getCachedData($cache_key, function() use ($pdo, $code) {
        $sql = "
            SELECT * FROM coupons 
            WHERE code = :code 
            AND is_active = 1
            AND (start_date IS NULL OR start_date <= NOW())
            AND (end_date IS NULL OR end_date >= NOW())
            AND (usage_limit IS NULL OR usage_limit > used_count)
        ";
        
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':code', $code);
        $stmt->execute();
        
        return $stmt->fetch();
    }, 300); // Cache 5 دقائق
    
    if (!$coupon) {
        return ['valid' => false, 'message' => 'كود الخصم غير صالح'];
    }
    
    // التحقق من الحد الأدنى للطلب
    if ($coupon['min_order_amount'] > 0 && $cart_total < $coupon['min_order_amount']) {
        return ['valid' => false, 'message' => 'الحد الأدنى للطلب هو ' . $coupon['min_order_amount'] . ' ريال'];
    }
    
    // التحقق من المستخدم (إذا كان مخصصاً)
    if ($coupon['customer_id'] && $coupon['customer_id'] != $customer_id) {
        return ['valid' => false, 'message' => 'كود الخصم غير صالح لهذا الحساب'];
    }
    
    return [
        'valid' => true,
        'coupon' => $coupon,
        'amount' => calculateDiscountAmount($coupon, $cart_total)
    ];
}

/**
 * استخدام كود خصم
 */
function applyCoupon($pdo, $coupon_id) {
    $sql = "UPDATE coupons SET used_count = used_count + 1 WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':id', $coupon_id, PDO::PARAM_INT);
    $stmt->execute();
    
    // مسح الكاش
    clearCache('coupon_*');
}