<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Payment;
use Carbon\Carbon;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function index()
    {
        return view('home');
    }

    private function groupAndSumPaymentsByYear($payments)
    {
        return $payments->groupBy(function($payment){
            /** @var Payment $payment */
            return $payment->created_at->month;
        })->map(function($payments){
            return $payments->sum('amount');
        });
    }

    public function reports(Request $request)
    {
        $clients = Client::all();
        $clientId = $request->get('client_id');
        $today = Carbon::today();
        $paymentQuery = Payment::whereBetween(
            'created_at',
            [$today->startOfYear()->toDateTimeString(), $today->endOfYear()->toDateTimeString()]
        );

        $client = null;
        if($clientId) {
            $paymentQuery->whereHas('project', function($query) use ($clientId) {
                return $query->where('client_id', '=', $clientId);
            });
            $client = Client::find($clientId);
        }
        $paymentsInThisYear = $paymentQuery->get();
        $thisYearPaymentGroup = $this->groupAndSumPaymentsByYear($paymentsInThisYear);

        $lastYearToday = $today->clone()->modify('-1 year');
        $paymentsInLastYear = Payment::whereBetween(
            'created_at',
            [$lastYearToday->startOfYear()->toDateTimeString(), $lastYearToday->endOfYear()->toDateTimeString()]
        )->get();
        $lastYearPaymentGroup = $this->groupAndSumPaymentsByYear($paymentsInLastYear);

        $data = [
            'thisYearPaymentGroup' => [
                'values' => $thisYearPaymentGroup->toArray(),
                'year' => $today->year,
                'sum' => $thisYearPaymentGroup->sum(),
            ],
            'lastYearPaymentGroup' => [
                'values' => $lastYearPaymentGroup->toArray(),
                'year' => $lastYearToday->year,
                'sum' => $lastYearPaymentGroup->sum(),
            ],
        ];
        return view('reports', ['data' => $data, 'client' => $client, 'clients' => $clients]);
    }
}
