<?php

namespace Modules\Accounting\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Security;

class CashBookController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(): void
    {
        $this->requirePermission('accounting_cashbook_view');

        $db = Database::getInstance();
        $fromDate = $this->request->get('from_date', date('Y-m-01'));
        $toDate = $this->request->get('to_date', date('Y-m-t'));

        $transactions = $db->query(
            "SELECT * FROM cash_book
             WHERE transaction_date BETWEEN :from_date AND :to_date
             ORDER BY transaction_date ASC, created_at ASC",
            [':from_date' => $fromDate, ':to_date' => $toDate]
        );

        $balance = 0;
        $runningBalance = 0;

        $opening = $db->query(
            "SELECT COALESCE(SUM(CASE WHEN type = 'inflow' THEN amount ELSE 0 END), 0) -
                    COALESCE(SUM(CASE WHEN type = 'outflow' THEN amount ELSE 0 END), 0) as balance
             FROM cash_book WHERE transaction_date < :from_date",
            [':from_date' => $fromDate]
        );
        $runningBalance = (float)($opening[0]->balance ?? 0);

        foreach ($transactions as $txn) {
            if ($txn->type === 'inflow') {
                $runningBalance += (float)$txn->amount;
            } else {
                $runningBalance -= (float)$txn->amount;
            }
            $txn->running_balance = $runningBalance;
        }

        $this->view('Accounting/cash_book', [
            'title' => 'Cash Book',
            'breadcrumb' => ['Cash Book' => url('accounting/cash-book')],
            'transactions' => $transactions,
            'fromDate' => $fromDate,
            'toDate' => $toDate,
            'openingBalance' => (float)($opening[0]->balance ?? 0),
        ]);
    }

    public function store(): void
    {
        $this->requirePermission('accounting_cashbook_create');

        $validated = $this->validate([
            'type' => 'required|in:inflow,outflow',
            'amount' => 'required|numeric|min:0',
            'description' => 'required|max_length:500',
            'date' => 'required|date',
        ]);

        $validated['amount'] = (float)$validated['amount'];
        $validated['created_by'] = Auth::id();
        $validated['transaction_date'] = $validated['date'];
        unset($validated['date']);

        Database::getInstance()->table('cash_book')->insert($validated);
        $this->logActivity('create', 'Added cash ' . $validated['type'] . ': ' . $validated['description']);

        $this->redirectWith(url('accounting/cash-book'), 'success', 'Cash transaction added successfully.');
    }
}
