<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MetaAdsData;
use App\Models\Tenant;
use App\Services\FacebookAdsService;
use App\Services\OpenRouterService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdsAnalyticsController extends Controller
{
    /**
     * GET /api/admin/ads/summary
     * Fetch or return cached Meta Ads summary
     */
    public function summary(Request $request): JsonResponse
    {
        /** @var Tenant $tenant */
        $tenant      = app('tenant');
        $token       = $request->query('token');
        $accountId   = $request->query('account');
        $datePreset  = $request->query('date_preset', 'this_month');

        if (!$token || !$accountId) {
            return response()->json(['error' => 'token and account required'], 422);
        }

        try {
            $fbService = new FacebookAdsService($token, $accountId);
            $data      = $fbService->fetchSummary();

            // Persist latest metrics for the selected preset
            $row = $data[$datePreset] ?? null;
            if ($row) {
                MetaAdsData::updateOrCreate(
                    ['tenant_id' => $tenant->id, 'date_preset' => $datePreset],
                    [
                        'spend'         => $row['spend'],
                        'impressions'   => $row['impressions'],
                        'clicks'        => $row['clicks'],
                        'purchases'     => $row['purchases'],
                        'roas'          => $row['roas'],
                        'ctr'           => $row['ctr'],
                        'cpc'           => $row['cpc'],
                        'raw_data_json' => json_encode($data),
                        'analyzed_at'   => now(),
                    ]
                );
            }

            return response()->json(['success' => true, 'data' => $data]);

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * GET /api/admin/ads/campaigns
     */
    public function campaigns(Request $request): JsonResponse
    {
        $token      = $request->query('token');
        $accountId  = $request->query('account');
        $datePreset = $request->query('date_preset', 'this_month');

        try {
            $fbService = new FacebookAdsService($token, $accountId);
            $data      = $fbService->fetchCampaigns($datePreset);

            return response()->json(['success' => true, 'data' => $data]);

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * GET /api/admin/ads/top-ads
     */
    public function topAds(Request $request): JsonResponse
    {
        $token      = $request->query('token');
        $accountId  = $request->query('account');
        $datePreset = $request->query('date_preset', 'this_month');

        try {
            $fbService = new FacebookAdsService($token, $accountId);
            $data      = $fbService->fetchTopAds($datePreset);

            return response()->json(['success' => true, 'data' => $data]);

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * POST /api/admin/ads/analyze
     * Send all ads data to Ollama (Ubaidi AI) and return analysis report
     */
    public function analyze(Request $request): JsonResponse
    {
        /** @var Tenant $tenant */
        $tenant = app('tenant');
        $data   = $request->json()->all();

        if (empty($data)) {
            return response()->json(['error' => 'Ads data প্রয়োজন'], 422);
        }

        try {
            $aiService = new OpenRouterService();
            $report        = $aiService->analyzeAds($data);

            // Save AI report alongside metrics
            MetaAdsData::where('tenant_id', $tenant->id)
                       ->where('date_preset', $data['date_preset'] ?? 'this_month')
                       ->update(['ai_analysis_report' => $report]);

            return response()->json(['success' => true, 'report' => $report]);

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * GET /api/admin/ads/history
     * Return saved metrics history for this tenant
     */
    public function history(Request $request): JsonResponse
    {
        $tenant = app('tenant');

        $history = MetaAdsData::where('tenant_id', $tenant->id)
                              ->orderBy('analyzed_at', 'desc')
                              ->limit(20)
                              ->get();

        return response()->json(['success' => true, 'data' => $history]);
    }
}
