<?php

declare(strict_types=1);

namespace App\Models;

use CodeIgniter\Model;

class LeadModel extends Model
{
    protected $table            = 'leads';
    protected $primaryKey       = 'id';
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'lead_number',
        'name',
        'email',
        'phone',
        'company_name',
        'license_number',
        'status_id',
        'assigned_to',
    ];
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $deletedField     = 'deleted_at';
    protected $validationRules  = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;

    public function getWithStatus(?int $id = null)
    {
        $builder = $this->builder();
        $builder->select('leads.*, lead_statuses.name as status_name, lead_statuses.color as status_color, users.full_name as assigned_name, users.username as assigned_username');
        $builder->join('lead_statuses', 'lead_statuses.id = leads.status_id', 'left');
        $builder->join('users', 'users.id = leads.assigned_to', 'left');

        if ($id !== null) {
            $builder->where('leads.id', $id);
            return $builder->get()->getRowArray();
        }

        return $builder->get()->getResultArray();
    }

    public function generateLeadNumber(): string
    {
        $maxId = $this->builder()->selectMax('id')->get()->getRowArray();
        $nextId = (int) ($maxId['id'] ?? 0) + 1;
        return 'LEAD-' . str_pad((string) $nextId, 6, '0', STR_PAD_LEFT);
    }
}
