<?php
// GET ?action=giftcard_list&api_key=KEY&country=US
// Returns available gift cards

$country = trim($_GET['country'] ?? '');
$api_markup = $GLOBALS['api_markup'];

try {
    $sql = "SELECT id, product_name, country, denomination, price, currency, brand
              FROM giftcard_products
             WHERE status = 1";
    $params = [];

    if (!empty($country)) {
        $sql .= " AND UPPER(country) = :country";
        $params[':country'] = strtoupper($country);
    }

    $sql .= " ORDER BY brand ASC, product_name ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $cards = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Database error.'], 500);
}

$result = [];
foreach ($cards as $c) {
    $price = (float)$c['price'];
    if ($api_markup > 0) $price = round($price * (1 + $api_markup / 100), 2);
    $result[] = [
        'id'           => (int)$c['id'],
        'name'         => $c['product_name'],
        'brand'        => $c['brand'],
        'country'      => $c['country'],
        'denomination' => $c['denomination'],
        'price'        => number_format($price, 2, '.', ''),
        'currency'     => $c['currency'],
    ];
}

api_response([
    'status' => 'success',
    'count'  => count($result),
    'cards'  => $result,
]);
