<?php

namespace App\Http\Controllers\Owner;

use App\Http\Controllers\Controller;
use App\Models\Serenata;
use App\Support\OwnerWorkspace;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        abort_if($organizationId <= 0, 403);
        $activeGroupId = OwnerWorkspace::activeGroupId($request, $organizationId);

        $today = Carbon::today();
        $tomorrow = Carbon::tomorrow();
        $weekEnd = Carbon::today()->addDays(6);
        $monthStart = Carbon::today()->startOfMonth();

        $baseQuery = OwnerWorkspace::applyScope(
            Serenata::query()->where('organization_id', $organizationId),
            $request
        );

        $stats = [
            'today_services' => (clone $baseQuery)->whereDate('event_date', $today)->count(),
            'tomorrow_services' => (clone $baseQuery)->whereDate('event_date', $tomorrow)->count(),
            'week_services' => (clone $baseQuery)->whereBetween('event_date', [$today, $weekEnd])->count(),
            'pending_services' => (clone $baseQuery)->where('service_status', 'Pendiente')->count(),
            'month_total_charged' => (float) (clone $baseQuery)->whereBetween('event_date', [$monthStart, $today])->sum('total_charged'),
            'month_commission' => (float) (clone $baseQuery)
                ->whereBetween('event_date', [$monthStart, $today])
                ->sum(DB::raw('CASE WHEN commission_amount > 0 THEN commission_amount ELSE profit_amount END')),
        ];

        $statusRows = (clone $baseQuery)
            ->select('service_status', DB::raw('COUNT(*) as total'))
            ->groupBy('service_status')
            ->pluck('total', 'service_status');

        $statusLabels = ['Pendiente', 'Confirmado', 'Completada', 'Cedida', 'Cancelado'];
        $statusSeries = collect($statusLabels)
            ->map(fn ($label) => (int) ($statusRows[$label] ?? 0))
            ->values()
            ->all();

        $months = collect(range(5, 0))->map(fn ($i) => Carbon::today()->startOfMonth()->subMonths($i));
        $months = $months->push(Carbon::today()->startOfMonth())->values();

        $monthlyRows = (clone $baseQuery)
            ->whereDate('event_date', '>=', $months->first()->toDateString())
            ->selectRaw("DATE_FORMAT(event_date, '%Y-%m') as ym")
            ->selectRaw('SUM(total_charged) as total_charged')
            ->selectRaw('SUM(CASE WHEN commission_amount > 0 THEN commission_amount ELSE profit_amount END) as commission_total')
            ->groupBy('ym')
            ->pluck('total_charged', 'ym');

        $monthlyCommissionRows = (clone $baseQuery)
            ->whereDate('event_date', '>=', $months->first()->toDateString())
            ->selectRaw("DATE_FORMAT(event_date, '%Y-%m') as ym")
            ->selectRaw('SUM(CASE WHEN commission_amount > 0 THEN commission_amount ELSE profit_amount END) as commission_total')
            ->groupBy('ym')
            ->pluck('commission_total', 'ym');

        $gainLabels = $months->map(fn (Carbon $date) => $date->translatedFormat('M'))->values()->all();
        $gainTotalSeries = $months->map(fn (Carbon $date) => (float) ($monthlyRows[$date->format('Y-m')] ?? 0))->values()->all();
        $gainCommissionSeries = $months->map(fn (Carbon $date) => (float) ($monthlyCommissionRows[$date->format('Y-m')] ?? 0))->values()->all();

        return view('content.owner.dashboard', [
            'stats' => $stats,
            'statusLabels' => $statusLabels,
            'statusSeries' => $statusSeries,
            'gainLabels' => $gainLabels,
            'gainTotalSeries' => $gainTotalSeries,
            'gainCommissionSeries' => $gainCommissionSeries,
        ]);
    }
}
