<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class EmailMarketingSubscriber extends Model
{
    use HasFactory;

    protected $fillable = [
        'email', 'first_name', 'last_name', 'client_id',
        'status', 'opted_in_at', 'unsubscribed_at',
        'unsubscribe_token', 'source', 'meta',
    ];

    protected $casts = [
        'meta' => 'array',
        'opted_in_at' => 'datetime',
        'unsubscribed_at' => 'datetime',
    ];

    protected $attributes = [
        'status' => 'subscribed',
        'source' => 'manual',
    ];

    protected static function booted(): void
    {
        static::creating(function (EmailMarketingSubscriber $s) {
            if (! $s->unsubscribe_token) {
                $s->unsubscribe_token = bin2hex(random_bytes(16));
            }
            if ($s->status === 'subscribed' && ! $s->opted_in_at) {
                $s->opted_in_at = now();
            }
        });
    }

    public function lists(): BelongsToMany
    {
        return $this->belongsToMany(
            EmailMarketingList::class,
            'email_marketing_list_subscriber',
            'email_marketing_subscriber_id',
            'email_marketing_list_id',
        )->withPivot(['joined_at', 'source'])->withTimestamps();
    }

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

    public function scopeSubscribed($q)
    {
        return $q->where('status', 'subscribed');
    }

    public function unsubscribe(): void
    {
        $this->update([
            'status' => 'unsubscribed',
            'unsubscribed_at' => now(),
        ]);
    }
}
