<?php

namespace App\Http\Controllers;

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

class ExpenseReportController extends Controller
{
    public function index()
    {
        $from = Carbon::parse(sprintf(
            '%s 00:00:00',
            request()->query('from', Carbon::now()->toDateString())
        ));
        $to = Carbon::parse(sprintf(
            '%s 23:59:59',
            request()->query('to', Carbon::now()->toDateString())
        ));

        $expenses = Transaction::where('type',"=",Transaction::TYPE_EXPENSE)->whereBetween('paid_at', [$from, $to]);

        $incomes = Transaction::where('type',"=",Transaction::TYPE_INCOME)->whereBetween('paid_at', [$from, $to]);

        $expensesTotal   = $expenses->sum('amount');
        $incomesTotal    = $incomes->sum('amount');
        $groupedExpenses = $expenses->whereNotNull('category')->orderBy('amount', 'desc')->get()->groupBy('category');
        $groupedIncomes  = $incomes->whereNotNull('category')->orderBy('amount', 'desc')->get()->groupBy('category');
        $profit          = $incomesTotal + $expensesTotal;

        $expensesSummary = [];
        foreach ($groupedExpenses as $key=>$exp) {
            foreach ($exp as $line) {
                if (!isset($expensesSummary[$key])) {
                    $expensesSummary[$key] = [
                        'name'   => $key,
                        'amount' => 0,
                    ];
                }

                $expensesSummary[$key]['amount'] += $line->amount;
            }
        }

        $incomesSummary = [];

        foreach ($groupedIncomes as $key=>$inc) {
            foreach ($inc as $line) {
                if (!isset($incomesSummary[$key])) {
                    $incomesSummary[$key] = [
                        'name'   => $key,
                        'amount' => 0,
                    ];
                }

                $incomesSummary[$key]['amount'] += $line->amount;
            }
        }

        return view('expenseReports.index', compact(
            'expensesSummary',
            'incomesSummary',
            'expensesTotal',
            'incomesTotal',
            'profit'
        ));
    }
}
