<?php
require_once 'db.php';

try {
    $products = $pdo->query("SELECT * FROM products")->fetchAll();
    
    // Process JSON fields
    foreach ($products as &$p) {
        $p['price'] = (float)$p['price'];
        if ($p['old_price']) $p['old_price'] = (float)$p['old_price'];
        if ($p['images']) $p['images'] = json_decode($p['images'], true);
        if ($p['colors']) $p['colors'] = json_decode($p['colors'], true);
        if ($p['sizes']) $p['sizes'] = json_decode($p['sizes'], true);
        $p['is_flash'] = (bool)$p['is_flash'];
        $p['is_top'] = (bool)$p['is_top'];
        $p['is_featured'] = (bool)($p['is_featured'] ?? false);
    }
    unset($p);

    $topBanners = $pdo->query("SELECT * FROM top_banners")->fetchAll();
    $heroBanners = $pdo->query("SELECT * FROM hero_banners")->fetchAll();
    $vendors = $pdo->query("SELECT * FROM vendors")->fetchAll();

    foreach ($vendors as &$v) {
        $v['wallet_balance'] = (float)($v['wallet_balance'] ?? 0);
        $v['loyalty_coins'] = (int)($v['loyalty_coins'] ?? 0);
    }
    unset($v);

    echo json_encode([
        'products' => $products,
        'topBanners' => $topBanners,
        'heroBanners' => $heroBanners,
        'vendors' => $vendors
    ]);

} catch (\PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
