<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Wallet;
use App\Models\DetailPayment;

class HomeController extends Controller
{
    public function index()
    {
        $now = Carbon::now();
        $month = $now->month;
        $year = $now->year;

        $monthlyIncome = DetailPayment::where('status', 'paid')
            ->where('payment_month', $month)
            ->where('payment_year', $year)
            ->whereHas('payments', fn($q) => $q->where('payment_status', 'success'))
            ->sum(DB::raw('IFNULL(amount,0) + IFNULL(penalty,0)'));


        $studentCount = User::where('level', 2)
            ->where('status_santri', 'aktif')
            ->count();

        $totalBalance = Wallet::sum('saldo');

        $paymentTrend = DetailPayment::select('payment_month', 'payment_year')
            ->selectRaw('SUM(IFNULL(amount,0) + IFNULL(penalty,0)) as total')
            ->where('status', 'paid')
            ->whereHas('payments', fn($q) => $q->where('payment_status', 'success'))
            ->whereBetween(DB::raw("STR_TO_DATE(CONCAT(payment_year,'-',payment_month,'-01'), '%Y-%m-%d')"), [
                now()->subMonths(11)->startOfMonth()->toDateString(),
                now()->endOfMonth()->toDateString(),
            ])
            ->groupBy('payment_year', 'payment_month')
            ->orderBy('payment_year')
            ->orderBy('payment_month')
            ->get();

        $labels = [];
        $data = [];

        foreach ($paymentTrend as $pt) {
            $labels[] = Carbon::createFromDate($pt->payment_year, $pt->payment_month, 1)->format('M Y');
            $data[] = (int)$pt->total;
        }

        return Inertia()->render('Dashboard', [
            'monthlyIncome' => $monthlyIncome,
            'studentCount' => $studentCount,
            'totalBalance' => $totalBalance,
            'paymentTrend' => [
                'labels' => $labels,
                'data' => $data,
            ],
        ]);
    }
}
