<?php

namespace App\Models;

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

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

    // ✅ legacy: soft deletes + timestamps
    use SoftDeletes;
    public $timestamps = true;

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

    protected $casts = [
        'scheduled_at' => 'datetime',
        'expires_at' => 'datetime',
    ];

    /**
     * MySQL stores channels as SET('in_app','email','sms'); expose as array in PHP.
     */
    protected function deliveryChannels(): Attribute
    {
        return Attribute::make(
            get: static function (?string $value): array {
                if ($value === null || $value === '') {
                    return [];
                }

                $trimmed = trim($value);
                if (str_starts_with($trimmed, '[')) {
                    $decoded = json_decode($trimmed, true);

                    return is_array($decoded) ? array_values($decoded) : [];
                }

                return array_values(array_filter(array_map('trim', explode(',', $value))));
            },
            set: static function ($value): string {
                if (is_array($value)) {
                    return implode(',', array_values(array_filter(array_map('strval', $value))));
                }

                return (string) $value;
            }
        );
    }

    /**
     * Equivalent of legacy 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 legacy getDeletedNotifications()
     */
    public static function getDeletedNotifications(): array
    {
        return static::onlyTrashed()
            ->orderByDesc('deleted_at')
            ->get()
            ->toArray();
    }

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

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

    /**
     * Equivalent of legacy 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
    }
}