<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class NotificationLog extends Model
{
    protected $fillable = [
        'application_id', 'type', 'channel', 'status', 'message', 'subject',
        'wa_message', 'recipient_name', 'recipient_contact', 'error', 'sent_at', 'scheduled_at',
    ];

    protected function casts(): array
    {
        return [
            'sent_at' => 'datetime',
            'scheduled_at' => 'datetime',
        ];
    }

    public function application(): BelongsTo
    {
        return $this->belongsTo(Application::class);
    }

    /**
     * Scope: only scheduled (pending with scheduled_at in future)
     */
    public function scopeScheduled($query)
    {
        return $query->where('status', 'scheduled');
    }

    /**
     * Scope: ready to send (scheduled_at has passed)
     */
    public function scopeReadyToSend($query)
    {
        return $query->where('status', 'scheduled')
                     ->where('scheduled_at', '<=', now());
    }

    /**
     * Scope: pending (old-style pending or scheduled)
     */
    public function scopePendingOrScheduled($query)
    {
        return $query->whereIn('status', ['pending', 'scheduled']);
    }

    /**
     * Check if this notification can be cancelled
     */
    public function isCancellable(): bool
    {
        return $this->status === 'scheduled';
    }

    /**
     * Human-readable status label
     */
    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            'scheduled' => 'Dijadwalkan',
            'pending' => 'Menunggu',
            'sent' => 'Terkirim',
            'failed' => 'Gagal',
            'cancelled' => 'Dibatalkan',
            default => ucfirst($this->status),
        };
    }
}
