<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;

class Notification extends BaseModel
{
    protected $table = 'notifications';

    // ✅ CI: soft deletes + timestamps
    use SoftDeletes;

    public $timestamps = true;

    protected $fillable = [
        'title',
        'message',
        'target_group',
        'delivery_channels',
        'priority',
        'status',
        'action_url',
        'attachment_path',
        'scheduled_at',
        'sent_at',
        'expires_at',
        'created_at',
        'updated_at',
        'deleted_at',
        'school_year',
        'semester',
    ];

    protected $casts = [
        'scheduled_at'      => 'datetime',
        'expires_at'        => 'datetime',
        // If delivery_channels is JSON in DB:
        'delivery_channels' => 'array',
    ];

    /**
     * Equivalent of CI getActiveNotifications()
     * Active = scheduled_at <= now AND (expires_at is null OR expires_at > now)
     */
    public static function getActiveNotifications(?string $targetGroup = null): array
    {
        $q = static::query()
            ->where('scheduled_at', '<=', now())
            ->where(function ($w) {
                $w->whereNull('expires_at')
                  ->orWhere('expires_at', '>', now());
            });

        if (!empty($targetGroup)) {
            $q->where('target_group', $targetGroup);
        }

        return $q->orderByDesc('priority')
            ->orderByDesc('scheduled_at')
            ->get()
            ->toArray();
    }

    /**
     * Equivalent of CI getDeletedNotifications()
     */
    public static function getDeletedNotifications(): array
    {
        return static::onlyTrashed()
            ->orderByDesc('deleted_at')
            ->get()
            ->toArray();
    }

    /**
     * Equivalent of CI getAllNotificationsWithDeleted()
     */
    public static function getAllNotificationsWithDeleted(): array
    {
        return static::withTrashed()
            ->orderByDesc('created_at')
            ->get()
            ->toArray();
    }

    /**
     * Equivalent of CI restoreNotification()
     */
    public static function restoreNotification(int $id): bool
    {
        $row = static::withTrashed()->find($id);
        if (!$row) return false;
        return (bool) $row->restore();
    }

    /**
     * Equivalent of CI deleteExpiredNotifications()
     * Soft-deletes rows with expires_at < now (and expires_at not null)
     */
    public static function deleteExpiredNotifications(): int
    {
        return static::query()
            ->whereNotNull('expires_at')
            ->where('expires_at', '<', now())
            ->delete(); // soft delete
    }
}