<?php
/**
 * API للتحقق من العروض المتاحة للمنتج أو السلة
 */
header('Content-Type: application/json');
require_once '../../config/database.php';

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

$product_id = $_GET['product_id'] ?? null;
$cart_total = $_GET['cart_total'] ?? 0;

try {
    $now = date('Y-m-d H:i:s');
    
    // جلب العروض النشطة
    $stmt = $db->prepare("SELECT * FROM offers 
                          WHERE is_active = 1 
                          AND start_date <= ? 
                          AND end_date >= ?
                          AND (usage_limit = 0 OR used_count < usage_limit)
                          ORDER BY priority ASC");
    $stmt->execute([$now, $now]);
    $offers = $stmt->fetchAll();
    
    $applicable_offers = [];
    
    foreach ($offers as $offer) {
        // التحقق من الحد الأدنى للشراء
        if ($offer['min_purchase'] > 0 && $cart_total < $offer['min_purchase']) {
            continue;
        }
        
        // حساب قيمة الخصم
        if ($offer['discount_type'] === 'percentage') {
            $discount = ($cart_total * $offer['discount_value']) / 100;
            if ($offer['max_discount'] && $discount > $offer['max_discount']) {
                $discount = $offer['max_discount'];
            }
        } else {
            $discount = $offer['discount_value'];
        }
        
        $applicable_offers[] = [
            'id' => $offer['id'],
            'title' => $offer['title'],
            'description' => $offer['description'],
            'discount_type' => $offer['discount_type'],
            'discount_value' => $offer['discount_value'],
            'calculated_discount' => $discount,
            'min_purchase' => $offer['min_purchase']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'offers' => $applicable_offers,
        'best_offer' => !empty($applicable_offers) ? $applicable_offers[0] : null
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ في التحقق من العروض'
    ]);
}
?>
