<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'first_name', 'last_name', 'company_name', 'email', 'phone', 'job_title',
        'lead_source_id', 'assigned_to', 'score', 'status', 'priority',
        'estimated_value', 'notes', 'converted_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        '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[new,contacted,qualified,unqualified,converted]',
        'priority'   => 'permit_empty|in_list[low,medium,high]',
    ];

    public function scopeForList(
        ?string $search = null,
        ?string $status = null,
        ?int $sourceId = null,
        ?int $assignedTo = null,
        ?string $priority = null,
        bool $excludeConverted = false
    ): self {
        if ($search) {
            $this->groupStart()
                ->like('first_name', $search)
                ->orLike('last_name', $search)
                ->orLike('company_name', $search)
                ->orLike('email', $search)
                ->orLike('phone', $search)
                ->groupEnd();
        }

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

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

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

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

        if ($excludeConverted) {
            $this->where('status !=', 'converted');
        }

        return $this;
    }

    public function getUnassigned(): array
    {
        return $this->where('assigned_to', null)
            ->where('status !=', 'converted')
            ->orderBy('created_at', 'ASC')
            ->findAll();
    }

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