<?php

namespace App\Services\Reports;

use App\Models\Client;
use App\Models\ReportTemplate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ReportTemplateDefaults
{
    public function __construct(private readonly BrandKitResolver $brandKitResolver)
    {
    }

    /** @return array<string, string> */
    public function channels(): array
    {
        return [
            'google_ads' => 'Google Ads',
            'meta_ads' => 'Meta Ads',
            'search_console' => 'Search Console',
            'ga4' => 'GA4',
        ];
    }

    /** @return array<string, array<string, string>> */
    public function sectionGroups(): array
    {
        return [
            'Genel' => [
                'cover' => 'Kapak alanı',
                'overview_cards' => 'Ana metrik kartları',
                'executive_summary' => 'Yönetici özeti / notlar',
                'ai_summary' => 'AI yorumları',
                'channel_comparison' => 'Kanal karşılaştırması',
            ],
            'Google Ads' => [
                'google_campaigns' => 'Kampanya tablosu',
                'google_keywords' => 'Anahtar kelime tablosu',
                'google_search_terms' => 'Arama terimi tablosu',
            ],
            'Meta Ads' => [
                'meta_campaigns' => 'Kampanya tablosu',
                'meta_adsets' => 'Reklam seti tablosu',
                'meta_ads' => 'Reklam tablosu',
            ],
            'SEO / Analytics' => [
                'gsc_queries' => 'Search Console sorgular',
                'gsc_pages' => 'Search Console sayfalar',
                'ga4_channels' => 'GA4 kanal/kaynak tablosu',
            ],
            'Kapanış' => [
                'footer' => 'Alt bilgi / veri zamanı',
            ],
        ];
    }

    /** @return array<int, string> */
    public function sectionKeys(): array
    {
        return collect($this->sectionGroups())->flatMap(fn (array $items) => array_keys($items))->values()->all();
    }

    /** @return array<string, bool> */
    public function defaultSections(?string $type = null): array
    {
        $type = $type ?: 'monthly';
        $sections = array_fill_keys($this->sectionKeys(), true);

        if ($type === 'daily') {
            $sections['google_keywords'] = false;
            $sections['google_search_terms'] = false;
            $sections['meta_adsets'] = false;
            $sections['meta_ads'] = false;
            $sections['gsc_pages'] = false;
            $sections['ga4_channels'] = true;
        }

        if ($type === 'weekly') {
            $sections['google_search_terms'] = false;
            $sections['meta_ads'] = false;
        }

        return $sections;
    }

    /** @return array<string, mixed> */
    public function defaultSettings(): array
    {
        return [
            'agency_name' => 'DW Ads Reporter',
            'agency_logo_url' => '',
            'client_logo_url' => '',
            'primary_color' => '#111827',
            'accent_color' => '#ef5f86',
            'secondary_color' => '#f8fafc',
            'text_color' => '#111827',
            'muted_color' => '#6b7280',
            'cover_style' => 'gradient',
            'cover_background_url' => '',
            'cover_title' => 'Dijital Performans Raporu',
            'cover_subtitle' => 'Google Ads, Meta Ads, Search Console ve GA4 performans özeti',
            'intro_text' => 'Bu rapor seçilen tarih aralığında toplanan reklam, SEO ve analitik verileri üzerinden otomatik hazırlanmıştır.',
            'footer_note' => 'Bu rapor DW Ads Reporter tarafından otomatik oluşturulmuştur.',
            'contact_email' => '',
            'contact_phone' => '',
            'website_url' => '',
            'table_limit' => 20,
            'show_client_logo' => true,
            'show_agency_logo' => true,
            'show_data_timestamp' => true,
            'compact_mode' => false,
            'include_pdf_cover' => true,
            'include_excel_summary' => true,
        ];
    }

    /** @return array<int, array<string, mixed>> */
    public function defaultTemplates(): array
    {
        return [
            [
                'name' => 'Günlük Hızlı Özet',
                'description' => 'Her sabah gönderilecek kısa reklam/SEO özeti.',
                'type' => 'daily',
                'channels' => ['google_ads', 'meta_ads', 'search_console', 'ga4'],
                'sections' => $this->defaultSections('daily'),
                'settings' => array_merge($this->defaultSettings(), [
                    'cover_title' => 'Günlük Dijital Performans Özeti',
                    'cover_subtitle' => 'Dünkü harcama, tıklama, dönüşüm ve organik görünürlük özeti',
                    'compact_mode' => true,
                    'table_limit' => 10,
                ]),
                'is_default' => true,
                'sort_order' => 10,
            ],
            [
                'name' => 'Haftalık Performans Raporu',
                'description' => 'Son 7 gün ve önceki dönem karşılaştırması için standart şablon.',
                'type' => 'weekly',
                'channels' => ['google_ads', 'meta_ads', 'search_console', 'ga4'],
                'sections' => $this->defaultSections('weekly'),
                'settings' => array_merge($this->defaultSettings(), [
                    'cover_title' => 'Haftalık Dijital Performans Raporu',
                    'cover_subtitle' => 'Haftalık kanal performansı, riskler, fırsatlar ve aksiyon önerileri',
                    'table_limit' => 15,
                ]),
                'is_default' => true,
                'sort_order' => 20,
            ],
            [
                'name' => 'Aylık Yönetici Raporu',
                'description' => 'Müşteri ve yönetici sunumu için detaylı aylık rapor.',
                'type' => 'monthly',
                'channels' => ['google_ads', 'meta_ads', 'search_console', 'ga4'],
                'sections' => $this->defaultSections('monthly'),
                'settings' => array_merge($this->defaultSettings(), [
                    'cover_title' => 'Aylık Dijital Pazarlama Raporu',
                    'cover_subtitle' => 'Reklam, SEO, Analytics ve öneri odaklı yönetici raporu',
                    'table_limit' => 25,
                ]),
                'is_default' => true,
                'sort_order' => 30,
            ],
        ];
    }

    /** @param array<int, string>|null $channels @return array<int, string> */
    public function normalizeChannels(?array $channels): array
    {
        $allowed = array_keys($this->channels());
        $selected = array_values(array_intersect($allowed, $channels ?: []));

        return $selected ?: $allowed;
    }

    /** @param array<string, mixed>|null $sections @return array<string, bool> */
    public function normalizeSections(?array $sections, ?string $type = null): array
    {
        $defaults = $this->defaultSections($type);
        foreach ($defaults as $key => $value) {
            if (array_key_exists($key, $sections ?: [])) {
                $defaults[$key] = filter_var($sections[$key], FILTER_VALIDATE_BOOL);
            }
        }

        return $defaults;
    }

    /** @param array<string, mixed>|null $settings @return array<string, mixed> */
    public function normalizeSettings(?array $settings): array
    {
        $defaults = $this->defaultSettings();
        $settings = $settings ?: [];

        foreach ($defaults as $key => $value) {
            if (array_key_exists($key, $settings)) {
                $defaults[$key] = $settings[$key];
            }
        }

        foreach (['show_client_logo', 'show_agency_logo', 'show_data_timestamp', 'compact_mode', 'include_pdf_cover', 'include_excel_summary'] as $key) {
            $defaults[$key] = filter_var($defaults[$key], FILTER_VALIDATE_BOOL);
        }

        foreach (['primary_color', 'accent_color', 'secondary_color', 'text_color', 'muted_color'] as $key) {
            $defaults[$key] = $this->normalizeColor((string) $defaults[$key], (string) $this->defaultSettings()[$key]);
        }

        $defaults['cover_style'] = in_array($defaults['cover_style'], ['gradient', 'minimal', 'image', 'dark'], true) ? $defaults['cover_style'] : 'gradient';
        $defaults['table_limit'] = max(5, min(100, (int) ($defaults['table_limit'] ?: 20)));

        return $defaults;
    }

    public function settingsFor(?ReportTemplate $template = null, ?Client $client = null): array
    {
        $base = $this->defaultSettings();
        $brandSettings = $this->brandKitResolver->settings($template, $client);
        $templateSettings = $template?->settings ?: [];

        $settings = $this->normalizeSettings(array_merge($base, $brandSettings, $templateSettings));

        if ($client) {
            if (empty($settings['client_logo_url']) && ! empty($client->logo_path)) {
                $settings['client_logo_url'] = $client->logo_path;
            }

            if (! empty($client->primary_color) && empty($templateSettings['primary_color']) && empty($brandSettings['primary_color'])) {
                $settings['primary_color'] = $this->normalizeColor($client->primary_color, $settings['primary_color']);
            }
        }

        return $settings;
    }

    public function sectionsFor(?ReportTemplate $template = null): array
    {
        return $this->normalizeSections($template?->sections ?: [], $template?->type ?: 'monthly');
    }

    public function seedDefaults(): int
    {
        $count = 0;
        foreach ($this->defaultTemplates() as $template) {
            DB::table('report_templates')->updateOrInsert(
                ['name' => $template['name'], 'client_id' => null],
                [
                    'description' => $template['description'],
                    'type' => $template['type'],
                    'channels' => json_encode($template['channels'], JSON_UNESCAPED_UNICODE),
                    'sections' => json_encode($template['sections'], JSON_UNESCAPED_UNICODE),
                    'settings' => json_encode($template['settings'], JSON_UNESCAPED_UNICODE),
                    'is_default' => $template['is_default'],
                    'is_active' => true,
                    'sort_order' => $template['sort_order'],
                    'updated_at' => now(),
                    'created_at' => now(),
                ]
            );
            $count++;
        }

        return $count;
    }

    private function normalizeColor(string $value, string $fallback): string
    {
        $value = trim($value);
        if (preg_match('/^#[0-9a-fA-F]{6}$/', $value)) {
            return Str::lower($value);
        }

        return $fallback;
    }
}
