<?php

namespace ChurchCRM\model\ChurchCRM;

use ChurchCRM\model\ChurchCRM\Base\Expense as BaseExpense;
use ChurchCRM\model\ChurchCRM\ExpenseQuery;

/**
 * Expense class for managing church expenses and withdrawals
 */
class Expense extends BaseExpense
{
    /**
     * Get formatted amount as currency
     */
    public function getFormattedAmount()
    {
        return '₦' . number_format($this->getAmount(), 2);
    }

    /**
     * Get status as badge HTML
     */
    public function getStatusBadge()
    {
        $statusClasses = [
            'Pending' => 'badge bg-warning text-dark',
            'Approved' => 'badge bg-info',
            'Rejected' => 'badge bg-danger',
            'Paid' => 'badge bg-success'
        ];
        
        $class = $statusClasses[$this->getStatus()] ?? 'badge bg-secondary';
        return sprintf('<span class="%s">%s</span>', $class, htmlspecialchars($this->getStatus()));
    }

    /**
     * Approve an expense
     */
    public function approve($userId)
    {
        $this->setStatus('Approved');
        $this->setApprovedBy($userId);
        return $this->save();
    }

    /**
     * Reject an expense
     */
    public function reject($userId)
    {
        $this->setStatus('Rejected');
        $this->setApprovedBy($userId);
        return $this->save();
    }

    /**
     * Mark expense as paid
     */
    public function markAsPaid($userId)
    {
        $this->setStatus('Paid');
        $this->setApprovedBy($userId);
        return $this->save();
    }

    /**
     * Get total expenses for a category in a date range
     */
    public static function getTotalByCategory($categoryId, $startDate = null, $endDate = null)
    {
        $query = ExpenseQuery::create()->filterByCategory($categoryId);
        
        if ($startDate) {
            $query->filterByDate(['min' => $startDate]);
        }
        if ($endDate) {
            $query->filterByDate(['max' => $endDate]);
        }
        
        $total = 0;
        foreach ($query->find() as $expense) {
            $total += $expense->getAmount();
        }
        
        return $total;
    }

    /**
     * Get total expenses by fund
     */
    public static function getTotalByFund($fundId, $startDate = null, $endDate = null)
    {
        $query = ExpenseQuery::create()->filterByFund($fundId);
        
        if ($startDate) {
            $query->filterByDate(['min' => $startDate]);
        }
        if ($endDate) {
            $query->filterByDate(['max' => $endDate]);
        }
        
        $total = 0;
        foreach ($query->find() as $expense) {
            $total += $expense->getAmount();
        }
        
        return $total;
    }
}
