<?php
use application\models\hclinica\tables\PacienteTable;
//use application\models\hclinica\models\PacienteModel;
use application\models\hclinica\tables\Persona;
//use application\models\hclinica\models\PersonaModel;
//use application\models\hclinica\models\DomicilioModel;
use application\models\hclinica\tables\Domicilio;

//namespace application\controllers\paciente;

class Paciente extends CI_Controller
{
    /*private $pacienteModel;
    private $personaModel;
    private $domicilioModel;*/
    public $conexion;
    
    public function __construct()
    {
        parent::__construct();
        $helpers=array("url","form");
        $libraries=array("session","parser",'Form_validation',"encryption");
        $this->load->helper($helpers);
        $this->load->library($libraries);
        $this->encryption->initialize(array('driver' => "openssl"));
                
        $this->conexion=$this->load->database("hclinica",true);
        $this->load->model("hclinica/models/PacienteModel","pacienteModel");
        $this->load->model("hclinica/models/PersonaModel");
        $this->load->model("hclinica/models/DomicilioModel");
    }
    public function index()
    {
        //echo "aqui";
        //$this->load->model("hclinica/models/CitaModel");
        $this->session->set_userdata("formPaciente","una session");
        print_r($_SESSION);
    }
    public function ver(){
        echo "pacientes";
    }
    public function formPaciente($d=null)
    {
        $data=array("idPaciente"=>"",
            "idPersona"=>"",
            "codigo"=>"",
            "comentario"=>"",
            "status"=>1,
            "nombre"=>"",
            "appat"=>"",
            "apmat"=>"",
            "genero"=>"",
            "rfc"=>"",
            "email"=>"",
            "tipo"=>"PACIENTE",
            "curp"=>"",
            "fechaNacimiento"=>date("d-m-Y"),
            "telefono"=>"",
            "idDomicilio"=>"",
            "codigoPostal"=>"",
            "calle"=>"",
            "noExt"=>"",
            "noInt"=>"",
            "colonia"=>"",
            "localidad"=>"",
            "municipio"=>"",
            "estado"=>"ESTADO DE MEXICO",
            "referencia"=>"",
        );
        $this->load->view("hclinica/form/paciente/formPaciente",$data);
    }
    public function postPaciente($id=null)
    {
        if($id==null){
            $paciente=array("idPaciente"=>"",
                "idPersona"=>"",
                "codigo"=>"",
                "comentario"=>"se ingresa paciente",
                "status"=>1,
                "nombre"=>"",
                "appat"=>"",
                "apmat"=>"",
                "genero"=>"",
                "rfc"=>"",
                "email"=>"",
                "tipo"=>"PACIENTE",
                "curp"=>"",
                "fechaNacimiento"=>"",
                "telefono"=>"",
                //"idPersona"=>$this->input->post("idPersona"),
                "idDomicilio"=>"",
                "codigoPostal"=>"",
                "calle"=>"",
                "noExt"=>"",
                "noInt"=>"",
                "colonia"=>"",
                "localidad"=>"",
                "municipio"=>"",
                "estado"=>"",
                "referencia"=>"",
                //"idDomicilio"=>$this->input->post("idDomicilio")
            );
        }else{
            $paciente=$this->pacienteModel->getPacienteById($id);
            if($paciente==null){
                show_404();
            }
            $persona=$this->PersonaModel->getPersonaById($paciente["idPersona"]);
            $persona["fechaNacimiento"]=date("d-m-Y",strtotime($persona["fechaNacimiento"]));
            $domicilio=$this->DomicilioModel->getDomicilioById($persona["idDomicilio"]);
            
            $data=array_merge($paciente,$persona,$domicilio);
            file_put_contents("datos.txt", $data);
            //$this->load->view("hclinica/form/paciente/formPaciente",$data);
            $data["tituloApp"]="Actualizar Paciente";
            $this->parser->parse("hclinica/form/paciente/formPaciente",$data);
        }
    }
    public function guardarPaciente()
    {
        $res=["res"=>false,"msg"=>"Error al guardar paciente"];
        if($this->input->server("REQUEST_METHOD")=="POST")
        {
            file_put_contents(__DIR__."/datos1.txt", json_encode($this->input->post()));
            $this->form_validation->set_rules("nombre","Nombre","min_length[4]|required");
            $this->form_validation->set_rules("appat","Apellido Paterno","min_length[3]|required");
            $this->form_validation->set_rules("apmat","Apellido Materno","min_length[3]|required");
            
            if($this->form_validation->run()){
                $paciente=array("idPaciente"=>$this->input->post("idPaciente"),
                    "idPersona"=>$this->input->post("idPersona"),
                    "codigo"=>$this->input->post("codigo"),
                    "comentario"=>$this->input->post("comentario"),
                    "status"=>1                 
                );
                $persona=array("nombre"=>$this->input->post("nombre"),
                    "appat"=>$this->input->post("appat"),
                    "apmat"=>$this->input->post("apmat"),
                    "genero"=>$this->input->post("genero"),
                    "rfc"=>$this->input->post("rfc"),
                    "email"=>$this->input->post("email"),
                    "tipo"=>"PACIENTE",
                    "curp"=>$this->input->post("curp"),
                    "fechaNacimiento"=>date("Y-m-d",strtotime($this->input->post("fechaNacimiento"))),
                    "telefono"=>$this->input->post("telefono"),
                    "idPersona"=>$this->input->post("idPersona"),
                    "idDomicilio"=>$this->input->post("idDomicilio")
                );
                $domicilio=array("codigoPostal"=>$this->input->post("codigoPostal"),
                    "calle"=>$this->input->post("calle"),
                    "noExt"=>$this->input->post("noExt"),
                    "noInt"=>$this->input->post("noInt"),
                    "colonia"=>$this->input->post("colonia"),
                    "localidad"=>$this->input->post("localidad"),
                    "municipio"=>$this->input->post("municipio"),
                    "estado"=>$this->input->post("estado"),
                    "referencia"=>$this->input->post("referencia"),
                    "idDomicilio"=>$this->input->post("idDomicilio")
                );
                
                $array=array_merge($paciente,$persona,$domicilio);
                
                $this->DomicilioModel->guardarRegistro($domicilio);
                $persona["idDomicilio"]=$domicilio["idDomicilio"];
                $this->PersonaModel->guardarRegistro($persona);
                $paciente["idPersona"]=$persona["idPersona"];
                $this->pacienteModel->guardarRegistro($paciente);
                
                $this->session->set_userdata("nombreTmp",$persona["nombre"]." ".$persona["appat"]." ".$persona["apmat"]);
                
                
                /*$domicilioTable=new Domicilio($array);
                $this->DomicilioModel->guardar($domicilioTable);
                $personaTable=new Persona($array);
                $personaTable->__set("idDomicilio", $domicilioTable->__get("idDomicilio"));
                $this->PersonaModel->guardar($personaTable);
                $pacienteTable=new PacienteTable($array);
                $pacienteTable->__set("idPersona", $personaTable->__get("idPersona"));
                $this->PacienteModel->guardar($pacienteTable);*/
                //$this->session->set_userdata("nombreTmp",$personaTable->nombre." ".$personaTable->appat." ".$personaTable->apmat);
                
                //echo $this->session
                //redirect("pacientes/paciente/listPaciente");
                //$this->load->view("hclinica/lista/paciente/listPaciente");
                //file_put_contents("datos.txt", json_encode(array_merge($paciente,$persona,$domicilio)));
                $res["res"]=true;
                $res["msg"]="Paciente guardado";
            }else{
                //convertir a mensaje
                $msg["mensaje"]="";
                //var_dump($this->form_validation->error_array());
                foreach ($this->form_validation->error_array() as $key => $value) {
                    $msg["mensaje"].=$value;
                }
                //echo json_encode($this->form_validation->error_array());
                //echo json_encode($msg);
                $res["msg"]=$msg["mensaje"];
                //var_dump(validation_errors());
                //show_404();
            }
        }
        echo json_encode($res);
    }
    public function listPaciente()
    {
        $this->load->view("hclinica/lista/paciente/listPaciente");
        //var_dump($this->input->is_ajax_request());
        
        //var_dump($row);
        /*$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 listPagoPaciente()
    {
        $this->load->view("hclinica/lista/paciente/listPagoPaciente");
    }
    public function datosPaciente()
    {
        $res=array("res"=>false,"message"=>"","datos"=>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();
            foreach ($row as $key => $val) {
                $var=$val;
                $var["clavePaciente"]=$this->encryption->encrypt($val["idPaciente"]);
                $res["datos"][]=$var;
            }
            //$res["datos"]=$row;
            $res["res"]=true;
        }
        echo json_encode($res);
    }
    public function datosPacienteModal()
    {
        $post=$this->input->post();
        $res=array("res"=>false,"message"=>"","datos"=>array());
        $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");
        $this->conexion->where("paciente.status",1);
        $query = $this->conexion->get();
        $row = $query->result_array();
        foreach ($row as $key => $val) {
            $var=$val;
            $var["nombreCompleto"]=$val["nombre"]." ".$val["appat"]." ".$val["apmat"];
            $var["clavePaciente"]=$this->encryption->encrypt($val["idPaciente"]);
            $res["datos"][]=$var;
        }
        $res["todos"]=$post["todos"]=='true'?true:false;
        $res["func"]=$post["func"];
        $this->load->view("hclinica/lista/paciente/listPacienteView",$res);
    }
    public function getNombrePaciente()
    {
        $res=array("res"=>false,"message"=>"No se encontró paciente","nombreCompleto"=>"");
        if($this->input->server("REQUEST_METHOD")=="POST")
        {
            //aqui va todo
        }
        $this->conexion->select('idPaciente,codigo,nombre,appat,apmat');
        $this->conexion->from('persona');
        $this->conexion->join('paciente', 'paciente.idPersona=persona.idPersona', 'inner');
        $this->conexion->join("domicilio","persona.idDomicilio=domicilio.idDomicilio","inner");
        $this->conexion->where("idPaciente",$this->input->post("idPaciente"));
        $query = $this->conexion->get();
        $row = $query->row_array();
        if($row!=null){
            $res["nombreCompleto"]=$row["nombre"]." ".$row["appat"]." ".$row["apmat"];
        }
        $res["res"]=true;
        $res["message"]="Datos encontrados";
        
        echo json_encode($res);
    }
    public function eliminarPaciente()
    {
        if($this->input->server("REQUEST_METHOD")=="POST")
        {
            $post=$this->input->post();
        }
    } 
    public function admin2()
    {
        $this->load->view("template/admin2.4.5/template.php");
    }
}

