<?php
require_once '../../includes/functions.php';
setCORSHeaders();

// Verify API Hash
verifyAPIHash();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Method not allowed', 405);
}

try {
    // Get all active coin packages
    $stmt = $pdo->query("
        SELECT id, name, coins, price, original_price, discount, priority, is_popular, 
               is_special_offer, special_offer_end_time, special_offer_bg_color, product_id
        FROM coin_packages 
        WHERE is_active = 1 
        ORDER BY priority ASC, coins ASC
    ");
    $packages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Process packages to add calculated fields
    foreach ($packages as &$package) {
        // Check if special offer is expired
        $package['is_special_offer_expired'] = false;
        if ($package['is_special_offer'] && $package['special_offer_end_time']) {
            $endTime = strtotime($package['special_offer_end_time']);
            $package['is_special_offer_expired'] = $endTime < time();
        }
        
        // Calculate savings
        $package['savings'] = $package['original_price'] - $package['price'];
        $package['savings_percentage'] = $package['original_price'] > 0 ? 
            round(($package['savings'] / $package['original_price']) * 100) : 0;
    }
    
    sendResponse([
        'success' => true,
        'message' => 'Coin packages retrieved successfully',
        'data' => $packages
    ]);
    
} catch (Exception $e) {
    sendResponse([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
        'data' => null
    ], 500);
}
?>