<?php

namespace App\Http\Controllers\Partner;

use App\Http\Controllers\Controller;
use App\Models\Event;
use App\Models\Transaction;
use App\Models\Review;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AnalyticsController extends Controller
{
    public function index()
    {
        $partner = Auth::guard('partner')->user();
        $partnerId = $partner->id;

        // --- 1. Pendapatan Bulanan (12 bulan terakhir) ---
        $monthlyRevenue = Transaction::select(
            DB::raw('YEAR(created_at) as year'),
            DB::raw('MONTH(created_at) as month'),
            DB::raw('SUM(total_price) as total')
        )
            ->whereHas('event', function ($q) use ($partnerId) {
                $q->where('partner_id', $partnerId);
            })
            ->whereIn('status', ['settlement', 'success'])
            ->where('created_at', '>=', now()->subMonths(12))
            ->groupBy('year', 'month')
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

        // Isi bulan yang kosong dengan 0
        $revenueChart = [];
        $revenueLabels = [];
        for ($i = 11; $i >= 0; $i--) {
            $date = now()->subMonths($i);
            $month = $date->month;
            $year = $date->year;
            $label = $date->format('M Y');

            $found = $monthlyRevenue->firstWhere(function ($item) use ($month, $year) {
                return $item->year == $year && $item->month == $month;
            });

            $revenueLabels[] = $label;
            $revenueChart[] = $found ? (int)$found->total : 0;
        }

        // --- 2. Tiket Terjual Bulanan ---
        $monthlyTickets = Transaction::select(
            DB::raw('YEAR(created_at) as year'),
            DB::raw('MONTH(created_at) as month'),
            DB::raw('COUNT(*) as total')
        )
            ->whereHas('event', function ($q) use ($partnerId) {
                $q->where('partner_id', $partnerId);
            })
            ->whereIn('status', ['settlement', 'success'])
            ->where('created_at', '>=', now()->subMonths(12))
            ->groupBy('year', 'month')
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

        $ticketsChart = [];
        for ($i = 11; $i >= 0; $i--) {
            $date = now()->subMonths($i);
            $month = $date->month;
            $year = $date->year;

            $found = $monthlyTickets->firstWhere(function ($item) use ($month, $year) {
                return $item->year == $year && $item->month == $month;
            });

            $ticketsChart[] = $found ? (int)$found->total : 0;
        }

        // --- 3. Top 5 Events by Revenue ---
        $topEvents = Event::where('partner_id', $partnerId)
            ->withCount(['transactions' => function ($q) {
                $q->whereIn('status', ['settlement', 'success']);
            }])
            ->withSum(['transactions' => function ($q) {
                $q->whereIn('status', ['settlement', 'success']);
            }], 'total_price')
            ->orderByDesc('transactions_sum_total_price')
            ->take(5)
            ->get();

        // --- 4. Semua Review untuk Partner ini ---
        $reviews = Review::whereHas('event', function ($q) use ($partnerId) {
            $q->where('partner_id', $partnerId);
        })
            ->with('event')
            ->latest()
            ->get();

        // --- 5. Total keseluruhan ---
        $totalRevenue = Transaction::whereHas('event', function ($q) use ($partnerId) {
            $q->where('partner_id', $partnerId);
        })->whereIn('status', ['settlement', 'success'])->sum('total_price');

        $totalTicketsSold = Transaction::whereHas('event', function ($q) use ($partnerId) {
            $q->where('partner_id', $partnerId);
        })->whereIn('status', ['settlement', 'success'])->count();

        $totalEvents = Event::where('partner_id', $partnerId)->count();

        $avgRating = Review::whereHas('event', function ($q) use ($partnerId) {
            $q->where('partner_id', $partnerId);
        })->avg('rating');

        return view('partner.analytics', compact(
            'revenueLabels',
            'revenueChart',
            'ticketsChart',
            'topEvents',
            'reviews',
            'totalRevenue',
            'totalTicketsSold',
            'totalEvents',
            'avgRating'
        ));
    }
}

