<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Campaign extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'user_id', 'parent_id', 'type', 'title', 'slug', 'available_urls', 'status',
        'template_id', 'email_subject', 'email_pre_header',
        'email_body', 'recipients_count', 'recipients_config',
        'delay', 'utm_status', 'utm_source', 'utm_medium', 'utm_campaign',
        'utm_term', 'utm_content', 'design_template', 'scheduled_at',
        'send_mode', 'range_start', 'range_end', 'emails_sent', 'emails_failed', 'emails_bounced',
        'opens_count', 'unique_opens', 'clicks_count', 'unique_clicks',
        'unsubscribes_count', 'conversions_count',
        'settings', 'created_by',
        // Recurring email
        'frequency', 'recurring_days', 'recurring_time', 'recurring_timezone', 'auto_send',
        'start_date', 'end_type', 'end_date', 'end_count', 'occurrences_sent',
        'last_sent_at', 'next_run_at',
    ];

    protected $casts = [
        'settings'          => 'array',
        'recipients_config' => 'array',
        'utm_status'        => 'boolean',
        'scheduled_at'      => 'datetime',
        'range_start'       => 'datetime',
        'range_end'         => 'datetime',
        // Recurring email
        'recurring_days'    => 'array',
        'auto_send'         => 'boolean',
        'start_date'        => 'date',
        'end_date'          => 'date',
        'last_sent_at'      => 'datetime',
        'next_run_at'       => 'datetime',
    ];

    public function occurrences()
    {
        return $this->hasMany(Campaign::class, 'parent_id');
    }

    public function parentCampaign()
    {
        return $this->belongsTo(Campaign::class, 'parent_id');
    }

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

    protected static function booted(): void
    {
        static::creating(function (Campaign $campaign) {
            if (empty($campaign->slug)) {
                $base = Str::slug($campaign->title);
                $slug = $base;
                $i    = 1;
                while (static::where('slug', $slug)->exists()) {
                    $slug = "{$base}-{$i}";
                    $i++;
                }
                $campaign->slug = $slug;
            }
        });
    }
}
