<?php

class FinanceController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('finance', 'view');

        $accountModel = new FinanceAccount();
        $expenseModel = new Expense();
        $txnModel = new FinanceTransaction();

        $accountId = $this->input('account', 'ALL');
        $category = $this->input('category', 'ALL');
        $dateFrom = $this->input('date_from', '');
        $dateTo = $this->input('date_to', '');

        $summary = $txnModel->monthSummary();
        $monthIncome = (float) $summary['month_income'];
        $monthExpense = (float) $summary['month_expense'];
        $lastMonthIncome = (float) $summary['last_month_income'];
        $lastMonthExpense = (float) $summary['last_month_expense'];

        $incomeChange = $lastMonthIncome > 0 ? round((($monthIncome - $lastMonthIncome) / $lastMonthIncome) * 100, 1) : null;
        $expenseChange = $lastMonthExpense > 0 ? round((($monthExpense - $lastMonthExpense) / $lastMonthExpense) * 100, 1) : null;

        $negativeAccounts = $accountModel->negativeBalanceAccounts();
        $alerts = [];
        if (count($negativeAccounts) > 0) {
            $alerts[] = ['icon' => 'fa-triangle-exclamation', 'color' => 'red', 'text' => count($negativeAccounts) . ' account(s) have a negative balance'];
        }
        if ($expenseChange !== null && $expenseChange > 20) {
            $alerts[] = ['icon' => 'fa-arrow-trend-up', 'color' => 'gold', 'text' => "Expenses up {$expenseChange}% vs last month"];
        }
        if (($monthIncome - $monthExpense) < 0) {
            $alerts[] = ['icon' => 'fa-scale-balanced', 'color' => 'red', 'text' => 'Net P&L is negative this month'];
        }

        $this->view('finance.index', [
            'pageTitle'     => 'Finance Overview',
            'accounts'      => $accountModel->allActive(),
            'totalBalance'  => $accountModel->totalBalance(),
            'monthIncome'   => $monthIncome,
            'monthExpense'  => $monthExpense,
            'incomeChange'  => $incomeChange,
            'expenseChange' => $expenseChange,
            'netPnl'        => $monthIncome - $monthExpense,
            'alerts'        => $alerts,
            'trend'         => $txnModel->cashFlowTrend(7),
            'transactions'  => $txnModel->listWithFilters($accountId, $category, $dateFrom, $dateTo),
            'expenses'      => $expenseModel->listWithAccount(),
            'expenseMonthTotal' => $expenseModel->monthTotal(),
            'activeAccount' => $accountId,
            'activeCategory'=> $category,
            'dateFrom'      => $dateFrom,
            'dateTo'        => $dateTo,
            'csrf'          => $this->csrfField(),
        ]);
    }

    // --- Accounts ---

    public function storeAccount(): void
    {
        Auth::requirePermission('finance', 'add');
        $this->verifyCsrf();

        $name = trim($this->input('account_name', ''));
        if ($name === '') {
            $this->redirect('finance');
            return;
        }

        $accountModel = new FinanceAccount();
        $accountModel->insert([
            'account_name'    => $name,
            'account_type'    => $this->input('account_type', 'CASH'),
            'current_balance' => (float) $this->input('opening_balance', 0),
            'is_active'       => 1,
        ]);

        AuditLogger::log(Auth::id(), 'FINANCE_ACCOUNT_CREATE', 'finance', "Added finance account: {$name}");
        $this->redirect('finance');
    }

    public function toggleAccount(): void
    {
        Auth::requirePermission('finance', 'edit');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $accountModel = new FinanceAccount();
        $account = $accountModel->find($id);
        if ($account) {
            $accountModel->update($id, ['is_active' => $account['is_active'] ? 0 : 1]);
            AuditLogger::log(Auth::id(), 'FINANCE_ACCOUNT_TOGGLE', 'finance', "Account #{$id} active -> " . ($account['is_active'] ? '0' : '1'));
        }
        $this->redirect('finance');
    }

    public function manualEntry(): void
    {
        Auth::requirePermission('finance', 'add');
        $this->verifyCsrf();

        $accountId = (int) $this->input('finance_account_id', 0);
        $amount = (float) $this->input('amount', 0);
        $type = $this->input('type', 'CREDIT');
        $category = $this->input('category', 'MISC');
        $description = trim($this->input('description', ''));

        if ($accountId > 0 && $amount > 0) {
            $accountModel = new FinanceAccount();
            $accountModel->manualEntry($accountId, $amount, $type, $category, $description, Auth::id());
            AuditLogger::log(Auth::id(), 'FINANCE_MANUAL_ENTRY', 'finance', "{$type} " . formatMoney($amount) . " on account #{$accountId}");
        }
        $this->redirect('finance');
    }

    // --- Expenses ---

    public function storeExpense(): void
    {
        Auth::requirePermission('expenses', 'add');
        $this->verifyCsrf();

        $category = trim($this->input('expense_category', ''));
        $amount = (float) $this->input('amount', 0);
        $accountId = (int) $this->input('finance_account_id', 0);
        $date = $this->input('expense_date', date('Y-m-d'));
        $notes = trim($this->input('notes', ''));

        if ($category === '' || $amount <= 0 || $accountId <= 0) {
            $this->redirect('finance');
            return;
        }

        $expenseModel = new Expense();
        $expenseId = $expenseModel->createExpense($category, $amount, $accountId, $date, $notes, Auth::id());

        AuditLogger::log(Auth::id(), 'EXPENSE_CREATE', 'expenses', "Added expense #{$expenseId}: {$category} " . formatMoney($amount));
        $this->redirect('finance');
    }

    public function deleteExpense(): void
    {
        Auth::requirePermission('expenses', 'delete');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $expenseModel = new Expense();
        $expenseModel->deleteExpense($id);

        AuditLogger::log(Auth::id(), 'EXPENSE_DELETE', 'expenses', "Deleted expense #{$id} (balance reversed)");
        $this->redirect('finance');
    }
}
