<?php

namespace PloverCRM\Common;

/**
 * Fetches and caches the Hub-managed Advocate Program payload for app clients.
 */
class AdvocateProgram
{
    private const API_NAMESPACE = '/wp-json/plovercrm-hub/v1/advocate-program';
    private const CACHE_TTL = 30 * MINUTE_IN_SECONDS;
    private const TRANSIENT_KEY = 'plover_crm_advocate_program_payload';

    public static function getPayload(): ?array
    {
        $license = LicenseChecker::getLicense();
        $token = sanitize_text_field((string) ($license['token'] ?? ''));

        if ($token === '') {
            return null;
        }

        $cached = get_transient(self::TRANSIENT_KEY);
        if (is_array($cached)) {
            return $cached;
        }

        $response = wp_remote_get(LicenseChecker::getHubUrl() . self::API_NAMESPACE, [
            'headers' => [
                'x-plovercrm-token' => $token,
            ],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            return null;
        }

        $status = (int) wp_remote_retrieve_response_code($response);
        if ($status < 200 || $status >= 300) {
            return null;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $rawPayload = is_array($body) && is_array($body['data'] ?? null)
            ? $body['data']
            : (is_array($body) ? $body : []);

        $normalized = self::normalizePayload($rawPayload);
        if ($normalized === null) {
            return null;
        }

        set_transient(self::TRANSIENT_KEY, $normalized, self::CACHE_TTL);

        return $normalized;
    }

    private static function normalizePayload(array $payload): ?array
    {
        $campaigns = [];
        foreach ((array) ($payload['campaigns'] ?? []) as $campaign) {
            if (!is_array($campaign)) {
                continue;
            }

            $normalizedCampaign = self::normalizeCampaign($campaign);
            if ($normalizedCampaign !== null) {
                $campaigns[] = $normalizedCampaign;
            }
        }

        if (empty($campaigns) && empty($payload['enabled'])) {
            return null;
        }

        return [
            'enabled' => !empty($payload['enabled']),
            'sidebarLabel' => sanitize_text_field((string) ($payload['sidebar_label'] ?? 'Advocate Program')),
            'dashboardCardTitle' => sanitize_text_field((string) ($payload['dashboard_card_title'] ?? 'Earn extra access')),
            'dashboardCardSubtitle' => sanitize_text_field((string) ($payload['dashboard_card_subtitle'] ?? '')),
            'pageTitle' => sanitize_text_field((string) ($payload['page_title'] ?? 'Advocate Program')),
            'pageDescription' => sanitize_textarea_field((string) ($payload['page_description'] ?? '')),
            'supportUrl' => esc_url_raw((string) ($payload['support_url'] ?? '')),
            'supportEmail' => sanitize_email((string) ($payload['support_email'] ?? '')),
            'supportSubjectPrefix' => sanitize_text_field((string) ($payload['support_subject_prefix'] ?? 'Advocate Program')),
            'defaultRewardDisclaimer' => sanitize_textarea_field((string) ($payload['default_reward_disclaimer'] ?? '')),
            'defaultDisclosureNote' => sanitize_textarea_field((string) ($payload['default_disclosure_note'] ?? '')),
            'maxVisibleCampaigns' => max(1, (int) ($payload['max_visible_campaigns'] ?? 4)),
            'featuredCampaignId' => sanitize_key((string) ($payload['featured_campaign_id'] ?? '')),
            'campaigns' => $campaigns,
        ];
    }

    private static function normalizeCampaign(array $campaign): ?array
    {
        $title = sanitize_text_field((string) ($campaign['title'] ?? ''));
        if ($title === '') {
            return null;
        }

        $policyMode = sanitize_key((string) ($campaign['policy_mode'] ?? 'rewarded'));
        if (!in_array($policyMode, ['rewarded', 'non_rewarded_only', 'disabled'], true)) {
            $policyMode = 'rewarded';
        }

        if ($policyMode === 'disabled') {
            return null;
        }

        return [
            'id' => sanitize_key((string) ($campaign['id'] ?? '')),
            'featured' => !empty($campaign['featured']),
            'title' => $title,
            'subtitle' => sanitize_text_field((string) ($campaign['subtitle'] ?? '')),
            'description' => sanitize_textarea_field((string) ($campaign['description'] ?? '')),
            'platform' => sanitize_key((string) ($campaign['platform'] ?? 'custom')),
            'taskType' => sanitize_key((string) ($campaign['task_type'] ?? 'review')),
            'policyMode' => $policyMode,
            'rewardLabel' => sanitize_text_field((string) ($campaign['reward_label'] ?? '')),
            'rewardValue' => max(0, (int) ($campaign['reward_value'] ?? 0)),
            'rewardUnit' => sanitize_key((string) ($campaign['reward_unit'] ?? 'none')),
            'ctaLabel' => sanitize_text_field((string) ($campaign['cta_label'] ?? 'Open task')),
            'ctaUrl' => esc_url_raw((string) ($campaign['cta_url'] ?? '')),
            'claimLabel' => sanitize_text_field((string) ($campaign['claim_label'] ?? '')),
            'claimUrl' => esc_url_raw((string) ($campaign['claim_url'] ?? '')),
            'claimMethod' => sanitize_key((string) ($campaign['claim_method'] ?? 'none')),
            'proofRequired' => sanitize_key((string) ($campaign['proof_required'] ?? 'none')),
            'proofInstructions' => sanitize_textarea_field((string) ($campaign['proof_instructions'] ?? '')),
            'supportSubject' => sanitize_text_field((string) ($campaign['support_subject'] ?? '')),
            'disclosureText' => sanitize_textarea_field((string) ($campaign['disclosure_text'] ?? '')),
            'termsNote' => sanitize_textarea_field((string) ($campaign['terms_note'] ?? '')),
            'showOnWeb' => !empty($campaign['show_on_web']),
            'showOnMobile' => !empty($campaign['show_on_mobile']),
            'sortOrder' => (int) ($campaign['sort_order'] ?? 0),
            'startDate' => sanitize_text_field((string) ($campaign['start_date'] ?? '')),
            'endDate' => sanitize_text_field((string) ($campaign['end_date'] ?? '')),
        ];
    }
}
