<?php

namespace App\Http\Controllers;

use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class ProfitController extends Controller
{
    public function index(Request $request)
    {
        $data = $request->validate([
            'date' => ['nullable', 'date'],
        ]);

        $day = Carbon::parse($data['date'] ?? now()->toDateString());

        $transactions = Transaction::with(['currency', 'account'])
            ->whereDate('created_at', $day->toDateString())
            ->latest()
            ->get();

        return view('profits.index', [
            'date' => $day->toDateString(),
            'transactions' => $transactions,
            'dailyExchangeProfit' => $transactions->sum(fn ($transaction) => (float) $transaction->exchange_profit),
            'dailyTotalProfit' => $transactions->sum(fn ($transaction) => (float) $transaction->total_profit),
            'totalProfit' => Transaction::sum('total_profit'),
        ]);
    }
}
