<?php defined('BASEPATH') or exit('No direct script access allowed');

class Pyr_instancia_model extends CI_Model {
    protected $table = 'evi02instan'; 
public function listar()
{
    return $this->db
        ->select('i.*, COUNT(c.ID_CANDID) AS total_candidatos')
        ->from('evi02instan i')
        ->join('evi04candidat_mr c', 'c.ID_INSTAN = i.ID_INSTAN AND (c.IS_DELETE = 0 OR c.IS_DELETE IS NULL)', 'left')
        ->where('(i.IS_DELETE = 0 OR i.IS_DELETE IS NULL)')
        ->group_by('i.ID_INSTAN')
        ->order_by('CAST(i.NUM_ORDEN AS UNSIGNED)', 'ASC', false)
        ->get()
        ->result();
}


public function cambiarEstado($id, $estado)
{
    return $this->db
        ->where('ID_INSTAN', $id)
        ->update('evi02instan', ['BOL_ACTIVO' => (int)$estado]);
}

 


 public function eliminar($id) {
 return $this->db
        ->where('ID_INSTAN', $id)
        ->update('evi02instan', ['IS_DELETE' => 1]);
  
    }


    public function getById($id){
        return $this->db
            ->where('ID_INSTAN', $id)
            ->get($this->table)
            ->row();
    }

    // Pyr_instancia_model
public function guardar($data){
    $this->db->insert('evi02instan',$data);
    return $this->db->insert_id();
}
public function actualizar($id,$data){
    $this->db->where('ID_INSTAN',$id)->update('evi02instan',$data);
}
public function obtener($id){
    return $this->db->get_where('evi02instan', ['ID_INSTAN' => $id])->row();
}


public function existeOrden($orden, $idInstancia = null){
    $this->db->where('NUM_ORDEN', $orden);
    if($idInstancia){
        $this->db->where('ID_INSTAN !=', $idInstancia);
    }
    return $this->db->count_all_results('evi02instan') > 0;
}

public function getMaxOrden() {
    // el FALSE evita que CI escape el CAST
    $this->db->select('MAX(CAST(NUM_ORDEN AS UNSIGNED)) AS max_orden', FALSE);
    $row = $this->db->get('evi02instan')->row();
    return $row ? (int)$row->max_orden : 0;
}


}
