<?php

namespace App\Models;

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

class EmailBroadcast extends Model
{
    public const STATUS_DRAFT = 'draft';
    public const STATUS_SENDING = 'sending';
    public const STATUS_SENT = 'sent';
    public const STATUS_FAILED = 'failed';

    public const GROUP_ALL_USERS = 'all_users';
    public const GROUP_VERIFIED_USERS = 'verified_users';
    public const GROUP_UNVERIFIED_USERS = 'unverified_users';
    public const GROUP_PREMIUM_USERS = 'premium_users';
    public const GROUP_FREE_USERS = 'free_users';
    public const GROUP_MENTORS = 'mentors';
    public const GROUP_SUPPORT_TEAM = 'support_team';

    protected $fillable = [
        'subject',
        'message',
        'recipient_group',
        'status',
        'total_recipients',
        'sent_count',
        'failed_count',
        'created_by',
        'sent_at',
    ];

    protected function casts(): array
    {
        return [
            'sent_at' => 'datetime',
            'total_recipients' => 'integer',
            'sent_count' => 'integer',
            'failed_count' => 'integer',
        ];
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public static function recipientGroups(): array
    {
        return [
            self::GROUP_ALL_USERS => 'All users',
            self::GROUP_VERIFIED_USERS => 'Verified users only',
            self::GROUP_UNVERIFIED_USERS => 'Unverified users only',
            self::GROUP_PREMIUM_USERS => 'Premium users',
            self::GROUP_FREE_USERS => 'Free users',
            self::GROUP_MENTORS => 'Mentors',
            self::GROUP_SUPPORT_TEAM => 'Support team',
        ];
    }

    public static function statuses(): array
    {
        return [
            self::STATUS_DRAFT,
            self::STATUS_SENDING,
            self::STATUS_SENT,
            self::STATUS_FAILED,
        ];
    }

    public function scopeSent(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_SENT);
    }
}
