<?php
/**
 * API للحصول على العروض النشطة
 */
header('Content-Type: application/json');
require_once '../../config/database.php';

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

try {
    $now = date('Y-m-d H:i:s');
    
    // جلب العروض النشطة فقط
    $stmt = $db->prepare("SELECT id, title, description, discount_type, discount_value, 
                          image, start_date, end_date, min_purchase, max_discount
                          FROM offers 
                          WHERE is_active = 1 
                          AND start_date <= ? 
                          AND end_date >= ?
                          ORDER BY priority ASC, created_at DESC");
    $stmt->execute([$now, $now]);
    $offers = $stmt->fetchAll();
    
    // حساب الأيام المتبقية لكل عرض
    foreach ($offers as &$offer) {
        $days_left = ceil((strtotime($offer['end_date']) - time()) / 86400);
        $offer['days_left'] = max(0, $days_left);
        $offer['is_ending_soon'] = $days_left <= 7;
    }
    
    echo json_encode([
        'success' => true,
        'count' => count($offers),
        'offers' => $offers
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ في جلب العروض'
    ]);
}
?>
