<?php

namespace App\Models;

use CodeIgniter\Model;

class RefundModel extends Model
{
    protected $table = 'refunds';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'parent_id',
        'school_year',
        'invoice_id',
        'refund_amount',
        'requested_at',
        'approved_at',
        'refunded_at',
        'status',
        'reason',
        'refund_paid_amount',
        'request',
        'note',
        'semester',
        'school_year',
        'approved_by',
        'updated_by',
        'refund_method',
        'check_nbr',
        'check_file'
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    /**
     * Get total approved refund for a parent in a specific school year.
     *
     * @param int $parentId
     * @param string $schoolYear
     * @return float
     */
    public function getTotalApprovedRefundByParentIdAndSchoolYear(int $parentId, string $schoolYear): float
    {
        // Sum refunds that have been at least partially paid out to the parent
        $result = $this->selectSum('refund_paid_amount', 'total_paid')
            ->where('parent_id', $parentId)
            ->where('school_year', $schoolYear)
            ->whereIn('status', ['Partial', 'Paid'])
            ->get()
            ->getRowArray();

        return $result && isset($result['total_paid']) ? (float) $result['total_paid'] : 0.00;
    }
}
