<?php

namespace App\Models;

class CampaignModel extends TenantModel
{
    protected $table            = 'campaigns';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'subject',
        'body',
        'audience_filter',
        'status',
        'sent_count',
        'sent_at',
        'created_by',
    ];

    protected $validationRules = [
        'subject' => 'required|max_length[150]',
        'body'    => 'required',
    ];

    public function withCreator()
    {
        return $this->select('campaigns.*, users.full_name as created_by_name')
            ->join('users', 'users.id = campaigns.created_by', 'left')
            ->orderBy('campaigns.created_at', 'desc');
    }

    /** Decodes the stored filter back into the array shape GuestModel::filterList() expects. */
    public function decodedFilter(object $campaign): array
    {
        return $campaign->audience_filter ? (json_decode($campaign->audience_filter, true) ?: []) : [];
    }
}
