<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Notification extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'message',
        'deep_link_url',
        'target_type',
        'target_value',
        'scheduled_at',
        'sent_at',
        'status',
        'image',
        'user_id',
        'type',
        'data',
        'read_at',
    ];

    protected $casts = [
        'target_value' => 'array',
        'data' => 'array', // Cast data as JSON/Array
        'scheduled_at' => 'datetime',
        'sent_at' => 'datetime',
        'read_at' => 'datetime',
    ];

    /**
     * Scope for a specific user.
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('target_type', 'all')
                     ->orWhere('user_id', $userId);
    }

    /**
     * Get the targeting rules for this notification.
     */
    public function targetingRules(): HasMany
    {
        return $this->hasMany(NotificationTargetingRule::class);
    }

    /**
     * Get the deliveries for this notification.
     */
    public function deliveries(): HasMany
    {
        return $this->hasMany(NotificationDelivery::class);
    }

    /**
     * Scope to get notifications that are ready to be sent.
     */
    public function scopeReadyToSend($query)
    {
        return $query->where(function ($q) {
            $q->where('status', 'scheduled')
              ->where('scheduled_at', '<=', now());
        })->orWhere(function ($q) {
            $q->where('status', 'draft')
              ->whereNull('scheduled_at');
        });
    }

    /**
     * Scope to get sent notifications.
     */
    public function scopeSent($query)
    {
        return $query->whereIn('status', ['sent', 'failed']);
    }

    /**
     * Get the notification status label.
     */
    public function getStatusLabelAttribute(): string
    {
        return match($this->status) {
            'draft' => 'Draft',
            'scheduled' => 'Scheduled',
            'sending' => 'Sending',
            'sent' => 'Sent',
            'failed' => 'Failed',
            default => 'Unknown'
        };
    }

    /**
     * Get the target type label.
     */
    public function getTargetTypeLabelAttribute(): string
    {
        return match($this->target_type) {
            'all' => 'All Users',
            'single_user' => 'Single User',
            'premium_plan' => 'Premium Plan Users',
            'custom' => 'Custom Segment',
            default => 'Unknown'
        };
    }

    /**
     * Check if notification is scheduled.
     */
    public function isScheduled(): bool
    {
        return $this->status === 'scheduled' && $this->scheduled_at !== null;
    }

    /**
     * Check if notification is ready to send.
     */
    public function isReadyToSend(): bool
    {
        if ($this->status === 'draft' && $this->scheduled_at === null) {
            return true;
        }
        
        if ($this->status === 'scheduled' && $this->scheduled_at !== null) {
            return $this->scheduled_at <= now();
        }
        
        return false;
    }
}
