<?php
ini_set("display_errors", 1);
//namespace application\controllers\paciente;

require_once APPPATH."/libraries/hclinica/ActionNotaVenta.php";

class Paciente extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper("url");
        $this->load->helper("form");
        $this->load->library('Form_validation');
        $this->load->library("parser");
        $this->load->library("session");
        
        $this->load->library("LibApp");
        $this->load->library("hclinica/itemPaciente",null,"itemPaciente");
        
        $this->conexion=$this->load->database("hclinica",true);
        $this->load->model("hclinica/DetalleHistoriaModel","detalleHistoriaModel");
        $this->load->model("hclinica/EncHistoriaModel","encHistoriaModel");
        $this->load->model("hclinica/NotaVentaModel","notaVentaModel");

        //var_dump($this->libapp->getUsuarioSession());  //array assoc
    }
    public function index()
    {
        //$this->ver();
        $get=$this->input->get();

        $data=array("listConcepto"=>array(),"nombrePaciente"=>"Ninguno seleccionado","encHistoriaAdd"=>false,"idEncHistoria"=>0);
        $list=$this->_getDatos();
        $data["listConcepto"]=$list;
        $data["listNota"]=[];

        if(isset($get["idEnc"]))
        {
            $data["encHistoriaAdd"]=true;
            //echo $get["idEnc"];
            $encHistoria=$this->encHistoriaModel->getEncHistoriaById($get["idEnc"]);
            if($encHistoria!=null)
            {
                $itemPaciente=(array)$this->itemPaciente->getItemPaciente($encHistoria->idPaciente);
                $data["nombrePaciente"]=trim($itemPaciente["nombre"]." ".$itemPaciente["appat"]." ".$itemPaciente["apmat"]);
                $list=$this->detalleHistoriaModel->getListDetalleByidEncHistoria($encHistoria->idEncHistoria);

                $detalle=array();
                $stmt=$this->conexion->query("SELECT serie, folio, total FROM notaventa WHERE idEncHistoria=? AND status=?",array($encHistoria->idEncHistoria,1));
                $l=$stmt->result_array();
                $data["listNota"]=$l;

                foreach ($list as $key => $value) 
                {    
                    $v=array();
                    $v["nombre"] = $value["nombre"];
                    $v["row"] = $value["row"];
                    $v["col"] = $value["col"];
                    $v["value"] = $value["value"];
                    $v["label"] = $value["label"];
                    $v["colw"] = $value["colw"];
                    $v["typefield"] = $value["typefield"];
                    $keyTmp=(int)$value["row"];
                    $detalle[$keyTmp][]=$v;
                }
                $data["listConcepto"]=$detalle;
                $data["idEncHistoria"]=$encHistoria->idEncHistoria;

               // $listNotas=$this->encHistoriaModel->getListNotaByIdEncHistoria($encHistoria->idEncHistoria);
            }
        }
        $this->parser->parse("hclinica/form/historiaclinica/formHistoriaClinica",$data);
    }
    public function guardarHistoriaClinica()
    {
        $res=array("res"=>false,"message"=>"Error al guardar datos");
        //var_dump(get_defined_functions());
        if($this->input->server("REQUEST_METHOD")=="POST")
        {
            $post=$this->input->post();
            $encHistoria=array("idEncHistoria"=>null,"idPaciente"=>$post["idPaciente"],"fechaCreacion"=>date("Y-m-d H:i:s"),"situacion"=>"ALTA","status"=>1);

            if(intval($post["idPaciente"])!=0)
            {
                $decode=utf8_encode(base64_decode($post["listDetalle"]));
                $list=(array)json_decode($decode,true);

                $encHistoriaO=(object)$encHistoria;
                $this->encHistoriaModel->guardarStdEncHistoria($encHistoriaO);

                //guardar detalle en forma de arreglo dibimensional
                foreach ($list as $key => $value) 
                {
                    foreach ($value as $k=>$concepto)
                    {
                        $concepto["status"]=1;
                        $concepto["idEncHistoria"]=$encHistoriaO->idEncHistoria;
                        $objeto=(object)$concepto;
                        $this->detalleHistoriaModel->guardarDetalleHistoria($objeto);
                    }
                }
                $res["idEncHistoria"]=$objeto->idEncHistoria;
                $res["res"]=true;
                $res["message"]="Historia Clinica guardada";
            }else{
                $res["message"]="No se ha seleccionado paciente";
            }
        }
        header('Content-Type: application/json');
        echo json_encode($res);
    }
    public function ver(){
        $xml=file_get_contents(APPPATH."/../assets/res/templates/hclinica/default.xml");
        //echo htmlentities(file_get_contents(APPPATH."/../assets/res/templates/hclinica/default.xml"));
        //echo realpath(APPPATH."/../assets/res/templates/hclinica/default.xml");
        $form=new SimpleXMLElement($xml);       
        
        foreach ($form->Conceptos->Concepto as $key=>$value) {
            //var_dump($value->UnConcepto["nombre"]);
            //echo $value->UnConcepto;
            //var_dump($value);
            foreach ($value as $k) //un concepto
            {
                var_dump($k["nombre"]);
            }
        }
    }
    public function _getDatos()
    {
        $datos=array();
        $xml=file_get_contents(APPPATH."/../assets/res/templates/hclinica/default.xml");
        $form=new SimpleXMLElement($xml);
        $i=0;
        foreach ($form->Conceptos->Concepto as $key=>$value) 
        {
            $concepto=array();
            $y=0;
            foreach ($value as $k) //un concepto
            {
                //var_dump($k->getName()); nombre concepto           
                $cargaXml=simplexml_import_dom($k);
                
                //$cargaXml->addAttribute("index1",$key);
                
                $atributos=array();
                foreach ($cargaXml->attributes() as $j=>$nodo)
                {
                    if($nodo->getName()!="index")
                    {
                        $atributos[$nodo->getName()]=$nodo->__toString();
                        //$concepto[$key]=$atributos;
                        //$atributos["index"]=$value;
                        $atributos["row"]=$i;
                        $atributos["col"]=$y;
                    }
                }
                $y++;
                //echo $y;
                $concepto[]=$atributos;
            }
            $y=0;
            $i++;
            $datos[]=$concepto;
        }
        return $datos;
    }
    public function getTemplate()
    {
        $datos=$this->_getDatos();
        $res["datos"]=$datos;
        echo json_encode($res);
    }
    public function historiasClinicas()
    {
        $this->load->view("hclinica/lista/paciente/listHistoriaClinica");
        //var_dump($this->input->is_ajax_request());
        
        /*$data = array(
            'blog_title' => 'My Blog Title',
            'blog_heading' => 'My Blog Heading',
            'blog_entries' => array(
                array('title' => 'Title 1', 'body' => 'Body 1'),
                array('title' => 'Title 2', 'body' => 'Body 2'),
                array('title' => 'Title 3', 'body' => 'Body 3'),
                array('title' => 'Title 4', 'body' => 'Body 4'),
                array('title' => 'Title 5', 'body' => 'Body 5')
            )
        );
        //$parse["body"]=$this->load->view("hclinica/form/paciente/formPaciente",$data,true);
        //$this->parser->parse("hclinica/ejemplo1",$parse);
        $this->parser->parse("hclinica/ejemplo1",$data);*/
    }
    public function listHistoriaClinicaPaciente()
    {
        $res=array("res"=>false,"message"=>"","historias"=>array());
        
        if($this->input->is_ajax_request())
        {
            /*$this->conexion->select('idPaciente,codigo,nombre,appat,apmat,calle');
            $this->conexion->from('persona');
            $this->conexion->join('paciente', 'paciente.idPersona=persona.idPersona', 'inner');
            $this->conexion->join("domicilio","persona.idDomicilio=domicilio.idDomicilio","inner");
            $query = $this->conexion->get();
            $row = $query->result_array();*/
            $this->conexion->select("idEncHistoria,paciente.idPaciente,nombre,appat,apmat,fechaCreacion,IFNULL((select sum(total) from notaventa where notaventa.idEncHistoria=enchistoria.idEncHistoria),0) as totalCosto");
            $this->conexion->from("enchistoria");
            $this->conexion->join("paciente","enchistoria.idPaciente=paciente.idPaciente","inner");
            $this->conexion->join('persona','paciente.idPersona=persona.idPersona', 'inner');
            $this->conexion->where("enchistoria.status",1);
            $this->conexion->where("paciente.status",1);
            $query = $this->conexion->get();
            $row = $query->result_array();
            $res["historias"]=$row;
            $res["res"]=true;
        }
        echo json_encode($res);
    }
    public function listHistoriaClinicaPacienteFecha()
    {
        $post=$this->input->post();
        $res=array("res"=>false,"message"=>"","historias"=>array());
        
        if($this->input->is_ajax_request())
        {
            $this->conexion->select("idEncHistoria,paciente.idPaciente,nombre,appat,apmat,fechaCreacion,(select sum(total) from notaventa where notaventa.idEncHistoria=enchistoria.idEncHistoria) as totalCosto");
            $this->conexion->from("encHistoria");
            $this->conexion->join("paciente","enchistoria.idPaciente=paciente.idPaciente","inner");
            $this->conexion->join('persona','paciente.idPersona=persona.idPersona', 'inner');
            $this->conexion->where('enchistoria.fechaAlta >=',$post["fechaInicial"]);
            $this->conexion->where('DATE(enchistoria.fechaAlta) <=',$post["fechaFinal"]);
            $this->conexion->where("enchistoria.status",1);
            //$this->conexion->where("paciente.status",1);
            $query = $this->conexion->get();
            $row = $query->result_array();
            $res["historias"]=$row;
            $res["res"]=true;
        }
        echo json_encode($res);
    }
    public function addNotaVentaHistoria()
    {
        $res=array("res"=>false,"message"=>"No se puede agregar nota de venta","nota"=>[]);
        if($this->input->server("REQUEST_METHOD")=="POST")
        {
            $post=$this->input->post();
            //var_dump(intval($post["idEncHistoria"]));
            if(intval($post["idEncHistoria"])>0)
            {
                $notaVenta=$this->_instanciarNota();
                $encHistoria=$this->encHistoriaModel->getEncHistoriaById($post["idEncHistoria"]);
                //verificar si no hay nota alguna
                if($encHistoria!=null)
                {
                    $chkCreditoPaciente=$post["chkCreditoPaciente"]=="true"?true:false;

                    try 
                    {
                       // echo "notaX";
                        $notaVenta["idPaciente"]=$encHistoria->idPaciente;
                        $notaVenta["idUsuario"]=$this->libapp->getUsuarioSession()["idUsuario"];
                        $notaVenta["serie"]="V".$this->libapp->getUsuarioSession()["idUsuario"];
                        $folio=$this->notaVentaModel->getDato("SELECT IF(MAX(folio)>0,MAX(folio)+1,1) FROM notaventa WHERE serie=?",[$notaVenta["serie"]]);
                        //echo $folio;
                        $notaVenta["idEncHistoria"]=$encHistoria->idEncHistoria;
                        $notaVenta["folio"]=$folio;
                        $notaVenta["total"]=floatval($post["total"]);
                        $notaVenta["fechaAlta"]=date("Y-m-d H:i:s");
                        $notaVenta=(object)$notaVenta;
                        $this->notaVentaModel->guardarStdNotaVenta($notaVenta);
                        $nota=["folio"=>$notaVenta->serie."-".$notaVenta->folio,"total"=>floatval($notaVenta->total)];
    
                        if($chkCreditoPaciente)
                        {
                            $this->load->library("hclinica/actionNotaVenta",["notaVenta"=>$notaVenta],"actionNotaVenta");
                            $this->actionNotaVenta->addCredito();
                        }
    
                        $res["message"]="Nota creada";
                        $res["res"]=true;
                        $res["nota"]=$nota;
                    } catch (Exception $e) {
                        $res["message"]=$e->getMessage();
                    }
                }
            }
        }
        echo json_encode($res);
    }
    public function _instanciarNota()
    {
        $notaVenta=["idNotaVenta"=>null,"idEncHistoria"=>0,"idUsuario"=>0,"serie"=>"","folio"=>0,"fechaAlta"=>"","total"=>0,"situacion"=>"VENTA","status"=>1];
        return $notaVenta;
    }
    function getInstPaciente()
    {
        return "paciente";
    }
    function probar()
    {
        $this->load->library("general/databaseLib",["conexion"=>$this->conexion],"databaseLib");
        var_dump($this->databaseLib);
    }
}

