<?php
namespace App\Entities\Clientes;

use App\Entities\Usuarios\UserEntity;
use App\Models\Clientes\ClienteContactoModel;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Entity;

class ClienteEntity extends \CodeIgniter\Entity\Entity
{
    protected $attributes = [
        "id" => null,
        "nombre" => null,
        "alias" => null,
        "cif" => null,
        "direccion" => null,
        "ciudad" => null,
        "comunidad_autonoma_id" => null,
        "provincia_id" => 0,
        "cp" => null,
        "pais_id" => null,
        "telefono" => null,
        "email" => null,
        "comercial_id" => 1,
        "soporte_id" => 1,
        "forma_pago_id" => null,
        "vencimiento" => 15,
        "fecha_vencimiento" => null,
        "margen" => 40.0,
        "descuento" => 0.0,
        "limite_credito" => 0.0,
        "limite_credito_user_id" => 1,
        "limite_credito_change_at" => null,
        "credito_asegurado" => false,
        "ccc" => null,
        "ccc_cliente" => null,
        "num_cuenta" => null,
        "message_tracking" => true,
        "message_production_start" => true,
        "tirada_flexible" => false,
        "descuento_tirada_flexible" => 20.0,
        "comentarios_tirada_flexible" => null,
        "margen_plantilla_id" => null,
        "comentarios" => null,
        "is_deleted" => 0,
        "deleted_at" => null,
        "created_at" => null,
        "updated_at" => null,
        "user_created_id" => 1,
        "user_update_id" => 1,
    ];
    protected $casts = [
        "comunidad_autonoma_id" => "?int",
        "provincia_id" => "int",
        "pais_id" => "?int",
        "comercial_id" => "int",
        "soporte_id" => "int",
        "forma_pago_id" => "?int",
        "vencimiento" => "int",
        "margen" => "float",
        "descuento" => "float",
        "limite_credito" => "float",
        "limite_credito_user_id" => "int",
        "credito_asegurado" => "?boolean",
        "message_tracking" => "boolean",
        "message_production_start" => "boolean",
        "tirada_flexible" => "boolean",
        "descuento_tirada_flexible" => "float",
        "margen_plantilla_id" => "?int",
        "is_deleted" => "int",
        "user_created_id" => "int",
        "user_update_id" => "int",
    ];
    
    public function comercial() : ?UserEntity
    {
        $m = model(UserModel::class);
        return $m->find($this->attributes["comercial_id"]);
    }
    public function user() : ?UserEntity
    {
        $m = model(UserModel::class);
        return $m->where("cliente_id",$this->attributes["id"])->first();
    }
    /**
     * Devuelve un array con los contactos del cliente
     *
     * @return array<ClienteContactoEntity>
     */
    public function contactos() : array
    {
        $m = model(ClienteContactoModel::class);
        $clienteContactos = $m->where('cliente_id',$this->attributes['id'])->findAll();
        return $clienteContactos ?? [];
    }
}
