<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Transaction;
use Illuminate\Http\Request;

class RevenueController extends Controller
{
    public function index(Request $request)
    {
        $query = Transaction::where('type', 'INCOME')
            ->when($request->search, function ($q, $search) {
                $q->where('description', 'like', "%{$search}%");
            })->when($request->filled('period'), function ($q) use ($request) {
                if ($request->period === 'today') {
                    $q->whereDate('created_at', today());
                } elseif ($request->period === 'week') {
                    $q->where('created_at', '>=', now()->startOfWeek());
                } elseif ($request->period === 'month') {
                    $q->whereMonth('created_at', now()->month);
                } elseif ($request->period === 'year') {
                    $q->whereYear('created_at', now()->year);
                }
            });

        $revenue = $query->latest()->paginate(15);

        $stats = [
            'total_revenue' => Transaction::where('type', 'INCOME')->sum('amount'),
            'this_month' => Transaction::where('type', 'INCOME')->whereMonth('created_at', now()->month)->sum('amount'),
            'last_month' => Transaction::where('type', 'INCOME')->whereMonth('created_at', now()->subMonth()->month)->sum('amount'),
            'total_invoiced' => Invoice::sum('total_amount'),
            'total_collected' => Invoice::sum('paid_amount'),
        ];

        return view('admin.revenue.index', compact('revenue', 'stats'));
    }
}
