<?php

namespace App\Models;

use CodeIgniter\Model;

class ContactModel extends Model
{
    protected $table         = 'contacts';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'company_id', 'first_name', 'last_name', 'email', 'phone', 'job_title',
        'is_primary', 'status', 'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'company_id' => 'required|is_natural_no_zero',
        'first_name' => 'required|min_length[1]|max_length[100]',
        'last_name'  => 'required|min_length[1]|max_length[100]',
        'email'      => 'permit_empty|valid_email|max_length[191]',
        'status'     => 'permit_empty|in_list[active,inactive]',
    ];

    public function scopeForList(
        ?string $search = null,
        ?string $status = null,
        ?int $companyId = null
    ): self {
        if ($search) {
            $this->groupStart()
                ->like('first_name', $search)
                ->orLike('last_name', $search)
                ->orLike('email', $search)
                ->orLike('phone', $search)
                ->orLike('job_title', $search)
                ->groupEnd();
        }

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

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

        return $this;
    }

    public function getFullName(array $contact): string
    {
        return trim($contact['first_name'] . ' ' . $contact['last_name']);
    }

    public function getByCompany(int $companyId): array
    {
        return $this->where('company_id', $companyId)
            ->where('status', 'active')
            ->orderBy('is_primary', 'DESC')
            ->orderBy('first_name', 'ASC')
            ->findAll();
    }
}
