<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Ga4TrafficSnapshot;
use App\Models\GoogleCampaignSnapshot;
use App\Models\GoogleKeywordSnapshot;
use App\Models\GoogleSearchTermSnapshot;
use App\Models\MetaAdSnapshot;
use App\Models\MetaAdsetSnapshot;
use App\Models\MetaCampaignSnapshot;
use App\Models\SearchConsolePageSnapshot;
use App\Models\SearchConsoleQuerySnapshot;
use Illuminate\View\View;

class PerformanceController extends Controller
{
    public function index(string $platform = 'overview'): View
    {
        $page_title = 'Performans';
        $page_description = 'Snapshot veriler üzerinden ilk analiz ekranları';

        $summary = [
            'google_cost' => (float) GoogleCampaignSnapshot::sum('cost'),
            'google_clicks' => (int) GoogleCampaignSnapshot::sum('clicks'),
            'google_conversions' => (float) GoogleCampaignSnapshot::sum('conversions'),
            'meta_spend' => (float) MetaCampaignSnapshot::sum('spend'),
            'meta_clicks' => (int) MetaCampaignSnapshot::sum('clicks'),
            'meta_leads' => (float) MetaCampaignSnapshot::sum('leads'),
            'gsc_clicks' => (int) SearchConsoleQuerySnapshot::sum('clicks'),
            'gsc_impressions' => (int) SearchConsoleQuerySnapshot::sum('impressions'),
            'ga4_sessions' => (int) Ga4TrafficSnapshot::sum('sessions'),
            'ga4_conversions' => (float) Ga4TrafficSnapshot::sum('conversions'),
        ];

        $latestGoogleCampaigns = GoogleCampaignSnapshot::latest('date')->orderByDesc('cost')->limit(10)->get();
        $latestGoogleKeywords = GoogleKeywordSnapshot::latest('date')->orderByDesc('cost')->limit(10)->get();
        $latestGoogleSearchTerms = GoogleSearchTermSnapshot::latest('date')->orderByDesc('cost')->limit(10)->get();
        $latestMetaCampaigns = MetaCampaignSnapshot::latest('date')->orderByDesc('spend')->limit(10)->get();
        $latestMetaAdsets = MetaAdsetSnapshot::latest('date')->orderByDesc('spend')->limit(10)->get();
        $latestMetaAds = MetaAdSnapshot::latest('date')->orderByDesc('spend')->limit(10)->get();
        $topQueries = SearchConsoleQuerySnapshot::latest('date')->orderByDesc('clicks')->limit(10)->get();
        $topPages = SearchConsolePageSnapshot::latest('date')->orderByDesc('clicks')->limit(10)->get();
        $ga4Rows = Ga4TrafficSnapshot::latest('date')->orderByDesc('sessions')->limit(10)->get();

        return view('admin.performance.index', compact(
            'page_title',
            'page_description',
            'platform',
            'summary',
            'latestGoogleCampaigns',
            'latestGoogleKeywords',
            'latestGoogleSearchTerms',
            'latestMetaCampaigns',
            'latestMetaAdsets',
            'latestMetaAds',
            'topQueries',
            'topPages',
            'ga4Rows'
        ));
    }
}
