<?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'] ?? 10;
    $deals = $deal->getActiveDeals($limit);
    
    // Filter only flash deals
    $flashDeals = array_filter($deals, function($deal) {
        return $deal['is_flash_deal'] == 1;
    });
    $flashDeals = array_values($flashDeals); // Re-index array
    
    // Add image URLs
    foreach ($flashDeals 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' => $flashDeals,
        'count' => count($flashDeals)
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'deals' => [],
        'count' => 0,
        'error' => 'Failed to fetch flash deals: ' . $e->getMessage()
    ]);
}
?>