<?php

namespace App\Http\Controllers\Meet;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Meet\Concerns\ScopesToAccount;
use App\Models\Branch;
use App\Models\Member;
use App\Models\Recording;
use App\Models\Room;
use App\Services\Meet\ReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\View\View;

class DashboardController extends Controller
{
    use ScopesToAccount;

    public function index(Request $request): View
    {
        $this->authorizeAbility($request, 'dashboard.view');
        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);
        $reports = app(ReportService::class);

        $roomQuery = Room::owned($owner)->where('organization_id', $organization->id);
        $this->scopeToBranch($request, $roomQuery);

        $upcoming = (clone $roomQuery)
            ->where('status', 'scheduled')
            ->where('scheduled_at', '>=', now())
            ->orderBy('scheduled_at')
            ->limit(10)
            ->get();

        $active = (clone $roomQuery)
            ->where('status', 'live')
            ->orderByDesc('updated_at')
            ->get();

        $past = (clone $roomQuery)
            ->whereIn('status', ['ended', 'cancelled'])
            ->orderByDesc('scheduled_at')
            ->limit(10)
            ->get();

        $stats = [
            'branches' => Branch::owned($owner)->where('organization_id', $organization->id)->where('is_active', true)->count(),
            'team_members' => Member::owned($owner)->where('organization_id', $organization->id)->count(),
            'upcoming_count' => (clone $roomQuery)->where('status', 'scheduled')->where('scheduled_at', '>=', now())->count(),
            'live_count' => (clone $roomQuery)->where('status', 'live')->count(),
            'recordings_count' => Recording::owned($owner)
                ->whereHas('session.room', fn ($q) => $q->where('organization_id', $organization->id))
                ->count(),
        ];

        $recentRecordings = Recording::owned($owner)
            ->whereHas('session.room', fn ($q) => $q->where('organization_id', $organization->id))
            ->with(['session.room'])
            ->orderByDesc('created_at')
            ->limit(5)
            ->get();

        $analytics = $reports->orgSummary(
            $owner,
            $organization->id,
            Carbon::now()->subDays(30)->startOfDay(),
            Carbon::now()->endOfDay(),
        );

        return view('meet.dashboard', compact('organization', 'stats', 'upcoming', 'active', 'past', 'recentRecordings', 'analytics'));
    }
}
