<?php
/**
 * Report Controller — Financial Summary (P&L, Balance Sheet, Trial Balance)
 */

class ReportController {
    private PDO $db;
    private object $user;

    public function __construct(PDO $db, object $user) {
        $this->db = $db;
        $this->user = $user;
    }

    /** GET /reports/financial-summary */
    public function financialSummary(): void {
        // Fetch all active accounts with their running balances
        // We use the same battle-tested query from AccountController
        $sql = "SELECT a.id, a.name, a.type, a.sub_type, a.opening_balance, a.balance_type, 
                       COALESCE(SUM(CASE WHEN j.is_reversed = 0 AND j.narration NOT LIKE 'REVERSAL%' THEN je.debit ELSE 0 END), 0) as total_dr,
                       COALESCE(SUM(CASE WHEN j.is_reversed = 0 AND j.narration NOT LIKE 'REVERSAL%' THEN je.credit ELSE 0 END), 0) as total_cr
                FROM accounts a
                LEFT JOIN journal_entries je ON je.account_id = a.id
                LEFT JOIN journals j ON je.journal_id = j.id
                WHERE a.is_active = 1
                GROUP BY a.id
                ORDER BY a.name ASC";

        $stmt = $this->db->query($sql);
        $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $summary = [
            'income' => [], // Credit is positive
            'expenses' => [], // Debit is positive
            'banks_cash' => [], // Debit is positive
            'receivables' => [], // Debit is positive
            'payables' => [], // Credit is positive
            'capital' => [] // Credit is positive
        ];

        $totals = [
            'total_income' => 0,
            'total_expense' => 0,
            'net_profit' => 0,
            'total_banks_cash' => 0,
            'total_receivables' => 0,
            'total_payables' => 0,
            'total_capital' => 0,
            'overall_available' => 0 // Cash + Receivables - Payables
        ];

        foreach ($accounts as $acc) {
            // Calculate final numerical balance: Dr is Positive, Cr is Negative
            $opening = floatval($acc['opening_balance']);
            if ($acc['balance_type'] === 'Cr') {
                $opening = -$opening;
            }
            $balance = $opening + (floatval($acc['total_dr']) - floatval($acc['total_cr']));
            $absBalance = abs($balance);

            if ($balance == 0) continue; // Skip zero balances to keep report clean

            $item = [
                'id' => $acc['id'],
                'name' => $acc['name'],
                'type' => $acc['type'],
                'sub_type' => $acc['sub_type'],
                'balance' => $absBalance
            ];

            // Categorize based on Type and Balance
            if ($acc['type'] === 'bank_cash') {
                // Bank/Cash (Asset)
                // Even if it goes negative (overdraft), we put it in banks_cash with negative value
                $item['balance'] = $balance; // Keep sign
                $summary['banks_cash'][] = $item;
                $totals['total_banks_cash'] += $balance;
            } 
            elseif ($acc['type'] === 'capital') {
                // Capital (Equity - Credit balance is normal)
                $val = -$balance; // Convert Cr to positive
                $item['balance'] = $val;
                $summary['capital'][] = $item;
                $totals['total_capital'] += $val;
            }
            elseif ($acc['type'] === 'system_income') {
                // Income (Credit balance is normal)
                $val = -$balance; 
                $item['balance'] = $val;
                $summary['income'][] = $item;
                $totals['total_income'] += $val;
            }
            elseif ($acc['type'] === 'system_expense') {
                // Expense (Debit balance is normal, but Mazdoori/Tora can be Credit if deducted and not paid)
                // If it's a Credit balance (negative), it means we owe it (liability) or it's an income (commission from deduction)
                // For simplicity in P&L, Expense is Dr, Income is Cr
                if ($balance > 0) {
                    $item['balance'] = $balance;
                    $summary['expenses'][] = $item;
                    $totals['total_expense'] += $balance;
                } else {
                    $item['balance'] = -$balance;
                    $summary['income'][] = $item; // Treat Credit expense accounts as Income/Liability
                    $totals['total_income'] += -$balance;
                }
            }
            elseif ($acc['type'] === 'party') {
                if ($balance > 0) {
                    // Receivable (نام)
                    $item['balance'] = $balance;
                    $summary['receivables'][] = $item;
                    $totals['total_receivables'] += $balance;
                } else {
                    // Payable (جمع)
                    $item['balance'] = -$balance;
                    $summary['payables'][] = $item;
                    $totals['total_payables'] += -$balance;
                }
            }
        }

        $totals['net_profit'] = $totals['total_income'] - $totals['total_expense'];
        $totals['overall_available'] = $totals['total_banks_cash'] + $totals['total_receivables'] - $totals['total_payables'];

        Response::success([
            'summary' => $summary,
            'totals' => $totals
        ]);
    }
}
