<?php

namespace App\Models;

use CodeIgniter\Model;

class CustomerHistoryModel extends Model
{
    protected $table         = 'customer_history';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $updatedField  = 'updated_at';

    protected $allowedFields = [
        'company_id', 'contact_id', 'event_type', 'title', 'description',
        'event_at', 'created_by',
    ];

    protected $validationRules = [
        'company_id' => 'required|is_natural_no_zero',
        'title'      => 'required|min_length[2]|max_length[200]',
        'event_type' => 'required|in_list[note,call,email,meeting,status_change,document,other]',
        'event_at'   => 'required',
    ];

    public function scopeForList(
        ?string $search = null,
        ?string $eventType = null,
        ?int $companyId = null
    ): self {
        if ($search) {
            $this->groupStart()
                ->like('title', $search)
                ->orLike('description', $search)
                ->groupEnd();
        }

        if ($eventType) {
            $this->where('event_type', $eventType);
        }

        if ($companyId) {
            $this->where('company_id', $companyId);
        }

        return $this;
    }
}
