<?php

namespace App\Models\Tarifas;

class TarifaEnvioModel extends \App\Models\BaseModel
{
    protected $table = "lg_tarifas_envios";

    /**
     * Whether primary key uses auto increment.
     *
     * @var bool
     */
    protected $useAutoIncrement = true;

    const SORTABLE = [
        0 => "t1.nombre",
        1 => "t2.nombre",
    ];

    protected $allowedFields = ["pais_id", "nombre", "code", "comment", "deleted_at", "is_deleted"];
    protected $returnType = "App\Entities\Tarifas\TarifaEnvioEntity";

    protected $useTimestamps = true;
    protected $useSoftDeletes = false;

    protected $createdField = "created_at";

    protected $updatedField = "updated_at";

    public static $labelField = "nombre";

    protected $validationRules = [
        "nombre" => [
            "label" => "TarifasEnvios.nombre",
            "rules" => "trim|required|max_length[255]",
        ],
    ];

    protected $validationMessages = [
        "nombre" => [
            "max_length" => "TarifasEnvios.validation.nombre.max_length",
            "required" => "TarifasEnvios.validation.nombre.required",
        ],
    ];

    public function findAllWithPaises(string $selcols = "pais_id, t1.nombre", int $limit = null, int $offset = 0)
    {
        $sql =
            "SELECT t1." .
            $selcols .
            ",  t2.nombre AS pais_id FROM " .
            $this->table .
            " t1  LEFT JOIN lg_paises t2 ON t1.pais_id = t2.id";
        if (!is_null($limit) && intval($limit) > 0) {
            $sql .= " LIMIT " . $limit;
        }

        if (!is_null($offset) && intval($offset) > 0) {
            $sql .= " OFFSET " . $offset;
        }

        $query = $this->db->query($sql);
        $result = $query->getResultObject();
        return $result;
    }

    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource(string $search = "")
    {
        $builder = $this->db->table($this->table . " t1")->select("t1.id as id, t1.nombre AS nombre,t1.code AS code, t2.nombre AS pais_id");
        $builder->join("lg_paises t2", "t1.pais_id = t2.id", "left");

        //JJO
        $builder->where("t1.is_deleted", 0);

        return empty($search)
            ? $builder
            : $builder
            ->groupStart()
            ->like("t1.nombre", $search)
            ->orLike("t2.code", $search)
            ->orLike("t2.id", $search)
            ->orLike("t1.pais_id", $search)
            ->orLike("t1.nombre", $search)
            ->orLike("t2.nombre", $search)
            ->groupEnd();
    }

    public function getTarifaEnvio($paisId, string $cp, $peso, $tipo_envio)
    {
        // Si el pais es españa se tienen que tener en cuenta los postales
        // Se busca primero la tarifa a la que corresponde
        $builder = $this->db->table($this->table . " t1")
            ->select("t1.id AS tarifa_envio_id, t2.importe_fijo as importe_fijo, t3.nombre as pais")
            ->join("tarifas_envios_zonas t2", "t1.id = t2.tarifa_envio_id")
            ->join("lg_paises t3", "t1.pais_id = t3.id")
            ->where("t1.pais_id", $paisId)
            ->where("t1.is_deleted", 0)
            ->where("t2.is_deleted", 0);
            

        if ($paisId == 1) { // España
            $builder->where("CAST(t2.cp_inicial AS UNSIGNED)<=", intval($cp))
                ->where("CAST(t2.cp_final AS UNSIGNED) >=", intval($cp));
        }
        $tarifas = $builder->get()->getResultObject();

        $resultado = [];

        $model = model('App\Models\Tarifas\TarifaEnvioPrecioModel');
        foreach ($tarifas as $tarifa) {
            $precio_tarifas = $model->getEnvioPrecio($tarifa->tarifa_envio_id, $peso, $tipo_envio);
            foreach ($precio_tarifas as $precio_tarifa) {
                $precio_tarifa->importe_fijo = $tarifa->importe_fijo;
                $precio_tarifa->pais = $tarifa->pais;
                array_push($resultado, $precio_tarifa);
            }
        }


        return $resultado;
    }
}
