<?php

namespace App\Models;

use App\Models\BaseModel;

class PaymentNotificationLog extends BaseModel
{
    protected $table = 'payment_notification_logs';

    // CI: useTimestamps = false (created_at / sent_at are managed manually)
    public $timestamps = false;

    protected $fillable = [
        '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 $casts = [
        'parent_id'         => 'integer',
        'invoice_id'         => 'integer',
        'period_year'        => 'integer',
        'period_month'       => 'integer',
        'head_fa_notified'   => 'boolean',
        'balance_snapshot'   => 'decimal:2', // adjust precision if needed
        'created_at'         => 'datetime',
        'sent_at'            => 'datetime',
    ];

    /* Optional relationships */
    public function parent()
    {
        return $this->belongsTo(User::class, 'parent_id');
    }

    public function invoice()
    {
        return $this->belongsTo(Invoice::class, 'invoice_id');
    }

    /**
     * Equivalent of CI existsForPeriod()
     */
    public static function existsForPeriod(int $parentId, int $year, int $month, string $type): bool
    {
        return static::query()
            ->where('parent_id', $parentId)
            ->where('period_year', $year)
            ->where('period_month', $month)
            ->where('type', $type)
            ->exists();
    }

    /**
     * Equivalent of CI listLogs()
     * $from/$to should be DATETIME strings.
     */
    public static function listLogs(?string $from = null, ?string $to = null, ?string $type = null): array
    {
        $q = static::query()->orderByDesc('sent_at');

        if (!empty($from)) {
            $q->where('sent_at', '>=', $from);
        }
        if (!empty($to)) {
            $q->where('sent_at', '<=', $to);
        }
        if (!empty($type)) {
            $q->where('type', $type);
        }

        return $q->get()->toArray();
    }
}