<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Patient;
use App\Models\Appointment;
use App\Models\Invoice;
use App\Models\Payment;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        $today = Carbon::today();
        $monthStart = $today->copy()->startOfMonth();
        $monthEnd = $today->copy()->endOfMonth();

        return response()->json([
            'stats' => [
                'total_patients' => Patient::count(),
                'active_patients' => Patient::where('status', 'active')->count(),
                'today_appointments' => Appointment::whereDate('appointment_date', $today)->count(),
                'pending_appointments' => Appointment::whereIn('status', ['scheduled', 'confirmed'])
                    ->whereDate('appointment_date', '>=', $today)
                    ->count(),
                'month_invoices' => Invoice::whereBetween('invoice_date', [$monthStart, $monthEnd])->count(),
                'month_revenue' => Payment::whereBetween('payment_date', [$monthStart, $monthEnd])->sum('amount'),
                'outstanding_balance' => Invoice::sum('balance'),
            ],
            'recent_appointments' => Appointment::with(['patient', 'user'])
                ->whereDate('appointment_date', '>=', $today)
                ->orderBy('appointment_date')
                ->limit(5)
                ->get()
                ->map(fn($a) => [
                    'id' => $a->id,
                    'patient_name' => $a->patient->fullName(),
                    'therapist_name' => $a->user->name,
                    'date' => $a->appointment_date->format('Y-m-d'),
                    'time' => $a->appointment_date->format('H:i'),
                    'status' => $a->status,
                ]),
            'appointments_by_status' => Appointment::selectRaw('status, count(*) as count')
                ->whereDate('appointment_date', '>=', $today->copy()->subDays(30))
                ->groupBy('status')
                ->get(),
            'invoices_by_status' => Invoice::selectRaw('status, count(*) as count, sum(total_amount) as total')
                ->groupBy('status')
                ->get(),
        ]);
    }
}
