<?php

namespace Modules\Accounting\Controllers;

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

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

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

        $db = Database::getInstance();
        $status = $this->request->get('status', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $query = $db->table('petty_cash pc')
            ->select('pc.*, u.first_name, u.last_name')
            ->leftJoin('users u', 'pc.created_by', '=', 'u.id');

        if (!empty($status)) {
            $query->where('pc.status', $status);
        }

        $items = $query->orderBy('pc.created_at', 'DESC')->paginate($perPage, $page);

        $this->view('Accounting/petty_cash', [
            'title' => 'Petty Cash',
            'breadcrumb' => ['Petty Cash' => url('accounting/petty-cash')],
            'items' => $items,
            'status' => $status,
        ]);
    }

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

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

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

        Database::getInstance()->table('petty_cash')->insert($validated);
        $this->logActivity('create', 'Petty cash request: ' . $validated['description']);

        $this->redirectWith(url('accounting/petty-cash'), 'success', 'Petty cash request submitted.');
    }

    public function approve(int $id): void
    {
        $this->requirePermission('accounting_pettycash_approve');

        $db = Database::getInstance();
        $item = $db->table('petty_cash')->find($id);
        if (!$item) {
            $this->redirectWith(url('accounting/petty-cash'), 'error', 'Petty cash item not found.');
        }

        $db->table('petty_cash')->where('id', $id)->update([
            'status' => 'approved',
            'approved_by' => Auth::id(),
            'approved_at' => date(DATE_TIME_FORMAT),
        ]);

        $this->logActivity('approve', 'Approved petty cash request #' . $id);
        $this->logAudit('approve', 'petty_cash', $id, (array)$item, ['status' => 'approved']);

        $this->redirectWith(url('accounting/petty-cash'), 'success', 'Petty cash request approved.');
    }
}
