<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

require_once __DIR__ . '/../includes/supabase.php';

$input = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $input['action'] ?? '';

$db = supabaseService();

switch ($action) {
    case 'get':
        $slot = $input['slot'] ?? 'banner_top';
        $game = $input['game'] ?? '';

        $params = [
            'select' => 'id,name,image_url,click_url,target_slots',
            'status' => 'eq.active',
            'order' => 'priority.desc,created_at.desc',
            'limit' => '5'
        ];

        $campaigns = $db->get('ad_campaigns', $params);

        if (empty($campaigns) || isset($campaigns['error'])) {
            echo json_encode(['error' => 'no_ads']);
            exit;
        }

        // Filter by slot and game targeting
        $matched = null;
        foreach ($campaigns as $c) {
            $slots = $c['target_slots'] ?? [];
            if (is_string($slots)) {
                $slots = array_filter(explode(',', trim($slots, '{}')));
            }
            if (!empty($slots) && !in_array($slot, $slots)) continue;

            $games = $c['target_games'] ?? [];
            if (is_string($games)) {
                $games = array_filter(explode(',', trim($games, '{}')));
            }
            if (!empty($games) && $game && !in_array($game, $games)) continue;

            $matched = $c;
            break;
        }

        if (!$matched) {
            echo json_encode(['error' => 'no_ads']);
            exit;
        }

        echo json_encode([
            'id' => $matched['id'],
            'image_url' => $matched['image_url'] ?? '',
            'click_url' => $matched['click_url'] ?? '',
        ], JSON_UNESCAPED_UNICODE);
        break;

    case 'impression':
        $campaignId = $input['campaign_id'] ?? null;
        if ($campaignId) {
            $campaign = $db->get('ad_campaigns', ['id' => "eq.{$campaignId}", 'select' => 'id,impressions']);
            if (!empty($campaign) && !isset($campaign['error']) && isset($campaign[0])) {
                $current = (int)($campaign[0]['impressions'] ?? 0);
                $db->update('ad_campaigns', ['impressions' => $current + 1], ['id' => "eq.{$campaignId}"]);
            }
        }
        echo json_encode(['ok' => true]);
        break;

    default:
        echo json_encode(['error' => 'Invalid action']);
}
