<?php

namespace App\Http\Controllers;

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

class BalanceSheetController extends Controller
{
    public function index(Request $request)
    {
        $companyId = Auth::user()->current_company_id;
        $endDate = $request->get('end_date', Carbon::now()->format('Y-m-d'));

        // Helper to fetch total balance for a category up to the end date
        $getCategoryTotal = function($categoryName) use ($companyId, $endDate) {
            $accounts = Account::where('company_id', $companyId)
                ->byCategory($categoryName)
                ->withSum(['journal_entries' => function ($q) use ($endDate) {
                    $q->where('transaction_date', '<=', $endDate);
                }], 'debit')
                ->withSum(['journal_entries' => function ($q) use ($endDate) {
                    $q->where('transaction_date', '<=', $endDate);
                }], 'credit')
                ->get();

            $debits = $accounts->sum('journal_entries_sum_debit');
            $credits = $accounts->sum('journal_entries_sum_credit');

            // Assets increase on Debit, Liabilities/Equity on Credit
            if (in_array(strtolower($categoryName), ['asset', 'non-current assets', 'current assets'])) {
                return $debits - $credits;
            }
            return $credits - $debits;
        };

        // 1. Assets
        $nonCurrentAssets = $getCategoryTotal('Non-current assets');
        $currentAssets = $getCategoryTotal('Current assets');
        $totalAssets = $nonCurrentAssets + $currentAssets;

        // 2. Liabilities
        $currentLiabilities = $getCategoryTotal('Current liabilities');
        $nonCurrentLiabilities = $getCategoryTotal('Non-current liabilities');
        
        // 3. Equity (Includes Retained Earnings calculation)
        $equityAccounts = $getCategoryTotal('Equity');
        
        // P&L Net Profit for Retained Earnings (Simplified for this view)
        // In a full system, you'd calculate all-time Revenue - all-time Expenses
        $netProfit = $this->calculateRetainedEarnings($companyId, $endDate);
        
        $totalEquity = $equityAccounts + $netProfit;
        $totalEquityAndLiabilities = $totalEquity + $currentLiabilities + $nonCurrentLiabilities;

        return view('reports.balance-sheet', compact(
            'endDate', 'nonCurrentAssets', 'currentAssets', 'totalAssets',
            'currentLiabilities', 'nonCurrentLiabilities', 'totalEquity', 
            'totalEquityAndLiabilities'
        ));
    }

    private function calculateRetainedEarnings($companyId, $endDate)
    {
        $revenue = Account::where('company_id', $companyId)->byCategory('Revenue')->get()->sum(fn($a) => $a->getBalance(null, $endDate));
        $expenses = Account::where('company_id', $companyId)->byCategory('Expenses')->get()->sum(fn($a) => $a->getBalance(null, $endDate));
        $cos = Account::where('company_id', $companyId)->byCategory('Cost of Sales')->get()->sum(fn($a) => $a->getBalance(null, $endDate));
        
        return $revenue - ($expenses + $cos);
    }
}