<?php

namespace App\Models;

use CodeIgniter\Model;

class PaymentNotificationLogModel extends Model
{
    protected $table         = 'payment_notification_logs';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useSoftDeletes = false;

    protected $allowedFields = [
        'parent_id',
        'invoice_id',
        'school_year',
        'period_year',
        'period_month',
        'type',
        'to_email',
        'cc_email',
        'head_fa_notified',
        'subject',
        'body',
        'status',
        'error_message',
        'balance_snapshot',
        'created_at',
        'sent_at',
    ];

    protected $useTimestamps = false;

    public function existsForPeriod(int $parentId, int $year, int $month, string $type): bool
    {
        return $this->where('parent_id', $parentId)
            ->where('period_year', $year)
            ->where('period_month', $month)
            ->where('type', $type)
            ->first() !== null;
    }

    public function listLogs(?string $from = null, ?string $to = null, ?string $type = null): array
    {
        $builder = $this->orderBy('sent_at', 'DESC');
        if ($from) {
            $builder->where('sent_at >=', $from);
        }
        if ($to) {
            $builder->where('sent_at <=', $to);
        }
        if ($type) {
            $builder->where('type', $type);
        }
        return $builder->findAll();
    }
}

