<?php

namespace App\Models;

use CodeIgniter\Model;

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

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

    protected $validationRules = [
        'supplier_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 $supplierId = 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 ($supplierId) {
            $this->where('supplier_id', $supplierId);
        }

        return $this;
    }

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

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