<?php
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../models/Deal.php';

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

try {
    $limit = $_GET['limit'] ?? 20;
    $deals = $deal->getActiveDeals($limit);
    
    // Add image URLs
    foreach ($deals as &$dealItem) {
        if ($dealItem['product_image']) {
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
            $host = $_SERVER['HTTP_HOST'];
            $dealItem['product_image'] = $protocol . $host . '/api/uploads/products/' . $dealItem['product_image'];
        }
    }
    
    echo json_encode([
        'deals' => $deals,
        'count' => count($deals)
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'deals' => [],
        'count' => 0,
        'error' => 'Failed to fetch deals: ' . $e->getMessage()
    ]);
}
?>