<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\CustomerTransaction;
use App\Models\SupplierTransaction;
use App\Models\Expense;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ReportController extends Controller
{
    public function profitLoss(Request $request)
    {
        $query = CustomerTransaction::whereHas('customer', function($q){
            $q->where('user_id', Auth::id());
        });

        $supplierQuery = SupplierTransaction::whereHas('supplier', function($q){
            $q->where('user_id', Auth::id());
        });

        $expenseQuery = Expense::where('user_id', Auth::id());

        if($request->month){
            $query->whereMonth('created_at', $request->month);
            $supplierQuery->whereMonth('created_at', $request->month);
            $expenseQuery->whereMonth('created_at', $request->month);
        }

        if($request->year){
            $query->whereYear('created_at', $request->year);
            $supplierQuery->whereYear('created_at', $request->year);
            $expenseQuery->whereYear('created_at', $request->year);
        }

        $totalIncome = $query->where('type','bill')->sum('amount');
        $totalSupplierCost = $supplierQuery->where('type','purchase')->sum('amount');
        $totalExpenses = $expenseQuery->sum('amount');

        $profitLoss = $totalIncome - ($totalSupplierCost + $totalExpenses);

        return view('user.reports.profit_loss', compact('totalIncome','totalSupplierCost','totalExpenses','profitLoss'));
    }
}