<?php
require_once __DIR__ . "/../db/config.php";
header("Content-Type: application/json");

try {
    $pdo = db();
    $now = date("Y-m-d H:i:s");
    
    // Get latest active perk for each type
    $stmt = $pdo->prepare("
        SELECT perk_type, perk_value, user_name, expires_at 
        FROM shop_perks 
        WHERE expires_at > ? 
        ORDER BY created_at DESC
    ");
    $stmt->execute([$now]);
    $all_active = $stmt->fetchAll();
    
    $perks = [
        "pinned_message" => null,
        "background" => null
    ];
    
    foreach ($all_active as $p) {
        if (!$perks[$p["perk_type"]]) {
            $perks[$p["perk_type"]] = $p;
        }
    }

    echo json_encode(["success" => true, "perks" => $perks]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
