<?php

namespace App\Http\Controllers;

use App\Models\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class ProfitLossController extends Controller
{
    public function index(Request $request)
    {
        $companyId = Auth::user()->current_company_id;

        // Default dates: Jan 1st of current year to Today
        $startDate = $request->get('start_date', Carbon::now()->startOfYear()->format('Y-m-d'));
        $endDate = $request->get('end_date', Carbon::now()->format('Y-m-d'));

        // Helper to fetch sums by Category or Group
        $getSummary = function($query) use ($startDate, $endDate) {
            return $query->withSum(['journal_entries' => function ($q) use ($startDate, $endDate) {
                $q->whereBetween('transaction_date', [$startDate, $endDate]);
            }], 'debit')
            ->withSum(['journal_entries' => function ($q) use ($startDate, $endDate) {
                $q->whereBetween('transaction_date', [$startDate, $endDate]);
            }], 'credit')->get();
        };

        // 1. REVENUE
        $revAccounts = $getSummary(Account::where('company_id', $companyId)->byCategory('Revenue'));
        $revenue = $revAccounts->sum('journal_entries_sum_credit') - $revAccounts->sum('journal_entries_sum_debit');

        // 2. OTHER OPERATING INCOME
        $otherIncomeAccounts = $getSummary(Account::where('company_id', $companyId)->byCategory('Other Income'));
        $otherIncome = $otherIncomeAccounts->sum('journal_entries_sum_credit') - $otherIncomeAccounts->sum('journal_entries_sum_debit');

        // 3. COST OF SALES
        $cosAccounts = $getSummary(Account::where('company_id', $companyId)->byCategory('Cost of Sales'));
        $cos = $cosAccounts->sum('journal_entries_sum_debit') - $cosAccounts->sum('journal_entries_sum_credit');

        // 4. ADMINISTRATIVE EXPENSES (Specific Group)
        $adminAccounts = $getSummary(Account::where('company_id', $companyId)->whereHas('type.group', function($q) {
            $q->where('name', 'like', '%Administrative%');
        }));
        $adminTotal = $adminAccounts->sum('journal_entries_sum_debit') - $adminAccounts->sum('journal_entries_sum_credit');

        // 5. OTHER OPERATING EXPENSES (All other expenses excluding Admin and Finance)
        $operatingExpenses = $getSummary(Account::where('company_id', $companyId)
            ->byCategory('Expenses')
            ->whereHas('type.group', function($q) {
                $q->where('name', 'not like', '%Administrative%')
                  ->where('name', 'not like', '%Finance%');
            }));
        
        // 6. FINANCE COSTS
        $financeAccounts = $getSummary(Account::where('company_id', $companyId)->whereHas('type.group', function($q) {
            $q->where('name', 'like', '%Finance%');
        }));
        $financeCosts = $financeAccounts->sum('journal_entries_sum_debit') - $financeAccounts->sum('journal_entries_sum_credit');

        // Financial Calculations
        $grossProfit = $revenue - $cos;
        $operatingProfit = ($grossProfit + $otherIncome) - ($adminTotal + $operatingExpenses->sum(fn($a) => $a->journal_entries_sum_debit - $a->journal_entries_sum_credit));
        $netProfit = $operatingProfit - $financeCosts;

        return view('reports.profit-loss', compact(
            'startDate', 'endDate', 'revenue', 'otherIncome', 'cos', 
            'adminTotal', 'operatingExpenses', 'financeCosts', 
            'grossProfit', 'operatingProfit', 'netProfit'
        ));
    }
}