<?php

namespace App\Http\Controllers\Tenant;

use App\Enums\AppointmentStatus;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Patient;
use App\Support\ClinicTime;
use App\Support\Tenancy;
use App\Domain\Billing\InstallmentService;
use Carbon\CarbonImmutable;

class DashboardController extends Controller
{
    public function index(Tenancy $tenancy)
    {
        $tenant = $tenancy->get();
        $tz = ClinicTime::timezone();
        $todayStart = CarbonImmutable::today($tz)->utc();
        $todayEnd = CarbonImmutable::today($tz)->addDay()->utc();
        $weekStart = CarbonImmutable::now($tz)->startOfWeek()->utc();

        $todays = Appointment::with(['patient:id,full_name,phone', 'dentist:id,name,color'])
            ->between($todayStart, $todayEnd)
            ->orderBy('starts_at')
            ->get();

        // 14-day appointment volume for the mini chart.
        $series = collect(range(13, 0))->map(function ($daysAgo) use ($tz) {
            $day = CarbonImmutable::today($tz)->subDays($daysAgo);

            return [
                'label' => $day->format('d M'),
                'count' => Appointment::between($day->utc(), $day->addDay()->utc())->count(),
            ];
        });

        return view('tenant.dashboard', [
            'tenant' => $tenant,
            'subscription' => $tenant->subscription?->load('plan'),
            'todays' => $todays,
            'kpis' => [
                'today_total' => $todays->count(),
                'today_completed' => $todays->where('status', AppointmentStatus::Completed)->count(),
                'week_total' => Appointment::between($weekStart, $todayEnd)->count(),
                'no_shows_week' => Appointment::between($weekStart, $todayEnd)
                    ->where('status', AppointmentStatus::NoShow)->count(),
                'new_patients_week' => Patient::where('created_at', '>=', $weekStart)->count(),
                'patients_total' => Patient::count(),
            ],
            'chart' => $series,
            'money' => auth()->user()->can('invoices.view')
                ? app(InstallmentService::class)->dashboardWidgets()
                : null,
        ]);
    }
}
