<?php

namespace App\Http\Controllers\Provider;

use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Payment;
use App\Models\Expense;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $provider = Auth::user()->provider;
        $today = Carbon::now()->startOfDay();
        $startOfWeek = Carbon::now()->startOfWeek();
        $endOfWeek = Carbon::now()->endOfWeek();
        $startOfMonth = Carbon::now()->startOfMonth();
        $endOfMonth = Carbon::now()->endOfMonth();

        // Today's data
        $appointmentsToday = Appointment::where('provider_id', $provider->id)
            ->whereBetween('start_time', [$today, $today->copy()->endOfDay()])
            ->get();

        $nextAppointment = Appointment::where('provider_id', $provider->id)
            ->where('start_time', '>=', now())
            ->with(['client', 'service'])
            ->orderBy('start_time')
            ->first();

        // Week's data
        $appointmentsWeek = Appointment::where('provider_id', $provider->id)
            ->whereBetween('start_time', [$startOfWeek, $endOfWeek])
            ->get();

        // Month's financial data
        $totalPayments = Payment::where('provider_id', $provider->id)
            ->whereBetween('payment_date', [$startOfMonth, $endOfMonth])
            ->sum('amount');

        $totalExpenses = Expense::where('provider_id', $provider->id)
            ->whereBetween('expense_date', [$startOfMonth, $endOfMonth])
            ->sum('amount');

        $balanceNet = $totalPayments - $totalExpenses;

        return view('provider.dashboard', [
            'appointmentsToday' => $appointmentsToday,
            'nextAppointment' => $nextAppointment,
            'appointmentsWeek' => $appointmentsWeek,
            'totalPayments' => $totalPayments,
            'totalExpenses' => $totalExpenses,
            'balanceNet' => $balanceNet,
        ]);
    }
}
