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

class Pacientes extends MY_Controller
{
    private $dir = 'pacientes';
    private $nom = 'Pacientes';
    private $dir1 = 'Nuevo paciente';
    private $dir2 = 'Editar paciente';
    private $dir3 = 'Profesionales';
    private $dir4 = 'Editar Profesionales';

    private $user_reg = '';

    function __construct()
    {
        parent::__construct();
        if ($this->session->userdata('ubicacion') != $this->dir):
            $array_items = array('per_page' => NULL, 'sort_order' => NULL, 'sort_by' => NULL,);
            $this->session->unset_userdata($array_items);
            $this->session->set_userdata('ubicacion', $this->dir);
        endif;

        $this->user_reg = $this->session->userdata('user_reg');

        $this->load->model($this->dir . '_model', 'modelo', TRUE);
        $this->data['dir'] = $this->dir;
        $this->data['nom'] = $this->nom;
        $this->data['dir1'] = $this->dir1;
        $this->data['dir2'] = $this->dir2;
        $this->data['dir3'] = $this->dir3;
        $this->data['dir4'] = $this->dir4;
    }

    function index($sort_by = 'nombreyapellido', $sort_order = 'asc', $offset = 0)
    {
        $this->load->helper('text');
        $this->load->library('pagination');
        $this->load->library('table');

        $this->data['fields'] = $this->modelo->getCampos();

        /* - search - */
        if ($this->get_search($this->dir) != '') $sql['search'] = $this->get_search($this->dir);
        /* - limit - */
        $sql['limit'] = $this->get_limit($this->dir);
        /* - sort_order - */
        $sql['sort_order'] = $this->get_sort_order($this->dir, $sort_order);
        /* - sort_by - */
        $sql['sort_by'] = $this->get_sort_by($this->dir, $sort_by);
        /* - offset - */
        $sql['offset'] = ($offset > 1) ? $offset : NULL;
        /* - Empresa y Sucursal- */
        $sql['empresa'] = ($this->user_reg['company'] != '')?$this->user_reg['company']:'';
        if($this->user_reg['sucursal'] != "Master"):
            $sql['sucursal'] = ($this->user_reg['sucursal'] != '')?$this->user_reg['sucursal']:'';
        endif;
        /* - Habilitado 1 - Activo | 0 - Eliminado */
        $sql['habilitado'] = array("0" => "1", "1" => "2");

        $results = $this->modelo->getAll($sql);

        $this->data['rows'] = $results['rows'];
        $this->data['num_results'] = $results['num_rows'];

        $config = array();
        $config['base_url'] = site_url("admin/" . $this->dir . "/index/$sort_by/$sort_order");
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->data['num_results'];
        $config['per_page'] = $sql['limit'];

        if ($this->session->flashdata('template_msg'))
            $this->data['message'] = $this->session->flashdata('template_msg');

        $this->pagination->initialize($config);
        $this->data['pagination'] = $this->pagination->create_links();
        $this->data['cur_page'] = $this->pagination->cur_page;
        $this->data['pagination_tot'] = ceil(($config['total_rows'] / $this->pagination->per_page));
        $this->data['action'] = site_url('admin/' . $this->dir . '/index');
        $this->data['search'] = $this->session->userdata($this->dir . '_search');

        /* - Equipos en domicilio - */
        $equipos = $this->modelo->getAllPacientesXEquipos();
        $this->data['equipos'] = $equipos;

        $this->template->title($this->data['nombre'], 'Administración');
        $this->template->build('admin/' . $this->dir . '/list', $this->data);
    }

    function restaurar($sort_by = 'nombreyapellido', $sort_order = 'asc', $offset = 0)
    {
        $this->load->helper('text');
        $this->load->library('pagination');
        $this->load->library('table');

        $this->data['fields'] = $this->modelo->getCampos();

        /* - search - */
        if ($this->get_search($this->dir) != '') $sql['search'] = $this->get_search($this->dir);
        /* - limit - */
        $sql['limit'] = $this->get_limit($this->dir);
        /* - sort_order - */
        $sql['sort_order'] = $this->get_sort_order($this->dir, $sort_order);
        /* - sort_by - */
        $sql['sort_by'] = $this->get_sort_by($this->dir, $sort_by);
        /* - offset - */
        $sql['offset'] = ($offset > 1) ? $offset : NULL;
        /* - Empresa y Sucursal- */
        $sql['empresa'] = ($this->user_reg['company'] != '')?$this->user_reg['company']:'';
        if($this->user_reg['sucursal'] != "Master"):
            $sql['sucursal'] = ($this->user_reg['sucursal'] != '')?$this->user_reg['sucursal']:'';
        endif;
        /* - Habilitado 1 - Activo | 0 - Eliminado */
        $sql['habilitado'] = 0;

        $results = $this->modelo->getAll($sql);

        $this->data['rows'] = $results['rows'];
        $this->data['num_results'] = $results['num_rows'];

        $config = array();
        $config['base_url'] = site_url("admin/" . $this->dir . "/restaurar/$sort_by/$sort_order");
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->data['num_results'];
        $config['per_page'] = $sql['limit'];

        if ($this->session->flashdata('template_msg'))
            $this->data['message'] = $this->session->flashdata('template_msg');

        $this->pagination->initialize($config);
        $this->data['pagination'] = $this->pagination->create_links();
        $this->data['cur_page'] = $this->pagination->cur_page;
        $this->data['pagination_tot'] = ceil(($config['total_rows'] / $this->pagination->per_page));
        $this->data['action'] = site_url('admin/' . $this->dir . '/restaurar');
        $this->data['search'] = $this->session->userdata($this->dir . '_search');

        $this->template->title($this->data['nombre'], 'Administración');
        $this->template->build('admin/' . $this->dir . '/restaurar', $this->data);
    }

    function edit($id)
    {
        $this->load->library('googlemaps');

        $config['center'] = 'mar del plata';
        $config['zoom'] = 'auto';
        $config['places'] = TRUE;
        $config['placesAutocompleteInputID'] = 'direccion';
        $config['placesAutocompleteBoundsMap'] = TRUE;
        $config['placesAutocompleteOnChange'] = 'autocompletar(map);';
        $config['onclick'] = 'obtenerData(map, event.latLng, event.latLng.lat(), event.latLng.lng());';

        $this->load->model('admin/localidades_model', '', TRUE);
        $sqlOL['habilitado'] = 1;
        $sqlOL['empresa'] = $this->user_reg['company'];
        $sqlOL['sort_order'] =  'asc';
        $sqlOL['sort_by'] = 'nombre';
        /* - Localidades - */
        $localidades = $this->localidades_model->getAll($sqlOL);
        $this->data['localidades'] = $localidades['rows'];

        $this->load->model('admin/equipos_model', '', TRUE);
        $this->data['pacxequipo'] = $this->modelo->getPacientesXEquipos($id);
        $sqlEquipos['habilitado'] = 1;
        $sqlEquipos['empresa'] = $this->user_reg['company'];
        $sqlEquipos['sort_order'] =  'asc';
        $sqlEquipos['sort_by'] = 'nombre';
        $equipos = $this->equipos_model->getAll($sqlEquipos);
        $this->data['equipos'] = $equipos['rows'];

        if($this->user_reg['sucursal'] == "Master"):
            $this->load->model('admin/sucursales_model', '', TRUE);
            $sucursales = $this->sucursales_model->getAll($sqlOL);
            $this->data['sucursales'] = $sucursales['rows'];
            $this->data['master'] = TRUE;
        endif;

        if ($id != 0):
            $sql['id'] = $id;
            $results = $this->modelo->getAll($sql);
            $this->data['row'] = $results['rows'][0];
            $this->data['num_results'] = $results['num_rows'];

            if ($this->data['row']->latitud != '') {
                $config['center'] = $this->data['row']->latitud . ',' . $this->data['row']->longitud;
                $config['zoom'] = '16';
                $config['scrollwheel'] = false;
                $marker = array();
                $marker['position'] = $this->data['row']->latitud . ',' . $this->data['row']->longitud;
            }
        endif;

        $this->googlemaps->initialize($config);
        if (isset($marker)) $this->googlemaps->add_marker($marker);
        $this->data['map'] = $this->googlemaps->create_map();

        $this->data['action'] = site_url('admin/' . $this->dir . '/update');

        $this->template->title($this->data['nombre'] . ' :: Administración');
        $this->template->build('admin/' . $this->dir . '/edit', $this->data);
    }

    function update()
    {
        $id = $this->input->post('id');

        /* - Campos requeridos - */
        $this->form_validation->set_rules('nombreyapellido', 'Nombre y Apellido', 'required');
        /* - Campos NO requeridos - */
        $this->form_validation->set_rules('idLocalidad', 'Localidad');
        $this->form_validation->set_rules('email', 'E-Mail');
        $this->form_validation->set_rules('direccion', 'Direcci&oacute;n');
        $this->form_validation->set_rules('ref_direccion', 'Referencia para direccion');
        $this->form_validation->set_rules('telefono', 'Telefono');
        $this->form_validation->set_rules('latitud', 'Latitud');
        $this->form_validation->set_rules('longitud', 'Longitud');
        $this->form_validation->set_rules('observaciones', 'Observaciones');

        if ($this->form_validation->run() == FALSE):

            $this->data['action'] = site_url('admin/' . $this->dir . '/update');

            $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Errores !</h4>" . validation_errors() . "</div>";

            $this->template->title($this->data['nombre'] . ' :: Administración');

            $this->template->build('admin/' . $this->dir . '/edit', $this->data);

        else:

            if($this->user_reg['sucursal'] != "Master"):
                $objeto = array(
                    'empresa' => $this->user_reg['company'],
                    'sucursal' => $this->user_reg['sucursal'],
                    'nombreyapellido' => $this->input->post('nombreyapellido'),
                    'idLocalidad' => $this->input->post('idLocalidad'),
                    'email' => $this->input->post('email'),
                    'direccion' => $this->input->post('direccion'),
                    'ref_direccion' => $this->input->post('ref_direccion'),
                    'telefono' => $this->input->post('telefono'),
                    'latitud' => $this->input->post('latitud'),
                    'longitud' => $this->input->post('longitud'),
                    'observaciones' => $this->input->post('observaciones'),
                    'habilitado' => $this->input->post('habilitado')
                );
            else:
                $objeto = array(
                    'empresa' => $this->user_reg['company'],
                    'sucursal' => $this->input->post('sucursal'),
                    'nombreyapellido' => $this->input->post('nombreyapellido'),
                    'idLocalidad' => $this->input->post('idLocalidad'),
                    'email' => $this->input->post('email'),
                    'direccion' => $this->input->post('direccion'),
                    'ref_direccion' => $this->input->post('ref_direccion'),
                    'telefono' => $this->input->post('telefono'),
                    'latitud' => $this->input->post('latitud'),
                    'longitud' => $this->input->post('longitud'),
                    'observaciones' => $this->input->post('observaciones'),
                    'habilitado' => $this->input->post('habilitado')
                );
            endif;

            $objetoEquipo = array(
                'idPaciente' => $id,
                'idEquipo' => $this->input->post('equipos')
            );

            if ($id == 0):

                $creado = date("Y-m-d H:i:s");
                $objeto['creado'] = $creado;

                $id = $this->modelo->save($objeto);

                if ($this->input->post('equipos') != FALSE) {
                    $objetoEquipo = array(
                        'idPaciente' => $id,
                        'idEquipo' => $this->input->post('equipos')
                    );
                    $this->modelo->updateEquipos($objetoEquipo);
                }

                $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Guardado</div>";
                $this->session->set_flashdata('template_msg', $this->data['message']);
                
                //redirect('admin/' . $this->dir . '/index', 'refresh');
                redirect('admin/' . $this->dir . '/edit/' . $id, 'refresh');
            else:

                if($objeto['habilitado'] == 1):
                    $this->modelo->restoreProfesionalesAsignados($id);
                elseif($objeto['habilitado'] == 2):
                    $this->modelo->deshabilitarProfesionalesAsignados($id);
                endif;

                $this->modelo->update($id, $objeto);

                $this->modelo->updateEquipos($objetoEquipo);

                $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Modificado</div>";
                $this->session->set_flashdata('template_msg', $this->data['message']);

                //redirect('admin/' . $this->dir . '/index', 'refresh');
                redirect('admin/' . $this->dir . '/edit/' . $id, 'refresh');
            endif;
        endif;
    }

    function delete()
    {
        $this->modelo->delete($this->input->post('ele'));

        $this->modelo->deleteProfesionalesAsignados($this->input->post('ele'));

        $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Eliminado</div>";
        $this->session->set_flashdata('template_msg', $this->data['message']);
        redirect('admin/' . $this->dir . '/index', 'refresh');
    }

    function restore()
    {
        $this->modelo->restore($this->input->post('ele'));

        $this->modelo->restoreProfesionalesAsignados($this->input->post('ele'));

        $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Eliminado</div>";
        $this->session->set_flashdata('template_msg', $this->data['message']);
        redirect('admin/' . $this->dir . '/restaurar', 'refresh');
    }

    /* - Sub AMB - */
    function sub_index($id, $idLocalidad = NULL)
    {
        $this->data['fields'] = array(
            'profesional' => 'Profesional',
            'visitasxmes' => 'Visitas por mes',
            'honorarios' => 'Honorarios'
        );
        $this->data['idPaciente'] = $id;
        $this->data['idLocalidad'] = $idLocalidad;
        $this->data['estado'] = array("0" => "1", "1" => "2");
        if($this->user_reg['sucursal'] != "Master"):
            $this->data['sucursal'] = $this->user_reg['sucursal'];
        endif;
        $results = $this->modelo->getAllList($this->data);
        $this->data['rows'] = $results['rows'];
        //$this->data['num_results'] = $results['num_rows'];

        $this->load->view('admin/' . $this->dir . '/sub_list', $this->data);
    }

    function sub_restaurar($id, $idLocalidad = NULL)
    {
        $this->data['fields'] = array(
            'profesional' => 'Profesional',
            'visitasxmes' => 'Visitas por mes',
            'honorarios' => 'Honorarios'
        );
        $this->data['idPaciente'] = $id;
        $this->data['idLocalidad'] = $idLocalidad;
        $this->data['estado'] = 0;
        if($this->user_reg['sucursal'] != "Master"):
            $this->data['sucursal'] = $this->user_reg['sucursal'];
        endif;
        $results = $this->modelo->getAllList($this->data);
        $this->data['rows'] = $results['rows'];
        //$this->data['num_results'] = $results['num_rows'];

        $this->load->view('admin/' . $this->dir . '/sub_restaurar', $this->data);
    }

    function sub_edit($id)
    {
        $this->data['idPaciente'] = $this->input->post('idPaciente');
        $this->data['idLocalidad'] = $this->input->post('idLocalidad');

        $this->data['estado'] = 1;
        $this->data['filtro'] = $id;
        $profesionalesAsignados = $this->modelo->getAllList($this->data);
        foreach($profesionalesAsignados['rows'] as $profesionalAsignado):
            $sql['asignado'][] = $profesionalAsignado->idProfesional;
        endforeach;

        $this->load->model('admin/profesionales_model', '', TRUE);
        $this->load->model('admin/especialidades_model', '', TRUE);

        $sql['habilitado'] = 1;
        $sql['empresa'] = $this->user_reg['company'];
        $sql['sucursal'] = $this->user_reg['sucursal'];

        $especialidades = $this->especialidades_model->getAll($sql);
        $this->data['especialidades'] = $especialidades['rows'];

        $sql['sort_order'] =  'asc';
        $sql['sort_by'] = 'apellido';

        $profesionales = $this->profesionales_model->getAll($sql);
        $this->data['profesionales'] = $profesionales['rows'];

        if ($id != 0) {
            $sql['id'] = $id;
            $results = $this->modelo->getProfesional($sql);
            $this->data['row'] = $results['rows'][0];
        }

        $this->load->view('admin/' . $this->dir . '/sub_edit', $this->data);
    }

    function filtrarProfesionalXEspecialidadYLocalidad($idEspecialidad, $idLocalidad, $idPaciente, $filtro)
    {
        //$sql['estado'] = 1;
        $sql['idPaciente'] = $idPaciente;
        $sql['filtro'] = $filtro;
        $profesionalesAsignados = $this->modelo->getAllList($sql);
        foreach($profesionalesAsignados['rows'] as $profesionalAsignado):
            $sql['asignado'][] = $profesionalAsignado->idProfesional;
        endforeach;
        /* - Filtros - */
        $sql['empresa'] = $this->user_reg['company'];
        $sql['sucursal'] = $this->user_reg['sucursal'];
        $sql['sort_order'] = 'asc';
        $sql['sort_by'] = 'apellido';
        $sql['habilitado'] = 1;
        $sql['idEspecialidad'] = $idEspecialidad;
        $sql['idLocalidad'] = $idLocalidad;

        $this->load->model('admin/profesionales_model', '', TRUE);
        $profesionales = $this->profesionales_model->getAll($sql);
        $this->data['profesionales'] = $profesionales['rows'];

        $this->load->view('admin/pacientes/select_profesionales', $this->data);
    }

    function sub_update()
    {
        $id = $this->input->post('id');

        /* - Campos requeridos - */
        $this->form_validation->set_rules('visitasxmes', 'Visitas por mes', 'required');
        /* - Campos NO requeridos - */
        $this->form_validation->set_rules('idProfesional', 'Profesional');
        $this->form_validation->set_rules('honorarios', 'Honorarios');
        $this->form_validation->set_rules('idPaciente', 'Paciente');

        if ($this->form_validation->run() == FALSE):

            $this->data['action'] = site_url('admin/' . $this->dir . '/sub_update');

            $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Errores !</h4>" . validation_errors() . "</div>";

            $this->template->title($this->data['nombre'] . ' :: Administración');

            $this->template->build('admin/' . $this->dir . '/sub_edit', $this->data);

        else:
            if ($id == 0) {
                $objeto = $this->input->post();

                unset($objeto['idLocalidad']);

                $creado = date("Y-m-d H:i:s");
                $objeto['creado'] = $creado;

                $id = $this->modelo->saveProfesional($objeto);
                $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Guardado</div>";
            } else {
                $objeto = $this->input->post();

                unset($objeto['idLocalidad']);
                
                $this->modelo->sub_update($objeto);
                $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Modificado</div>";
            }
            $this->session->set_flashdata('template_msg', $this->data['message']);
            $this->sub_index($this->input->post('idPaciente'), $this->input->post('idLocalidad'));
        endif;
    }

    function sub_delete()
    {
        $this->modelo->deleteProfesional($this->input->post('sub_ele'), $this->input->post('idPaciente'));
        //echo $this->db->last_query();
        $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Eliminado</div>";
        $this->session->set_flashdata('template_msg', $this->data['message']);
        $this->sub_index($this->input->post('idPaciente'), $this->input->post('idLocalidad'));
    }

    function sub_restore()
    {
        $this->modelo->restoreProfesional($this->input->post('sub_ele'), $this->input->post('idPaciente'));
        //echo $this->db->last_query();
        $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Eliminado</div>";
        $this->session->set_flashdata('template_msg', $this->data['message']);
        $this->sub_index($this->input->post('idPaciente'), $this->input->post('idLocalidad'));
    }
    
	protected function parse_dir( $dir )
	{
		$dir = strtolower( $dir );
		
		$arr = array(
			'p.',
			'piso',
			'dto',
			'pb',
			'(entre',
			'timbre',
			'e/',
			'entre ',
			'timbre',
			'(y',
			'depto.'
		);
		
		$arrs = count($arr);
		
		for ( $i = 0; $i < $arrs; $i++ )
		{
			$pos = strpos( $dir, $arr[$i] );
			
			if ( $pos > 0 )
			{
				$dir = substr( $dir, 0, $pos );
			}
		}
		
		for ( $i = 1; $i < 30; $i++ )
		{
			$pos = strpos( $dir, $i . 'º' );
			
			if ( $pos > 0 )
			{
				$dir = substr( $dir, 0, $pos );
			}
		}
		
		$dir = str_replace( ' - ', '', $dir );
		
		return ucwords_camelcase($dir);
	}
	
	protected function clean_phone( $phone )
	{
		$ret = "";
		
		if ( isset( $phone ) && !empty( $phone ) )
		{
			$len = strlen( $phone );
			
			for ( $i = 0; $i < $len; $i++ )
			{
				if ( ' ' == $phone[$i] )
				{
					$ret .= ' ';
				}
				else if ( is_numeric( $phone[$i] ) )
				{
					$ret .= $phone[$i];
				}
			}
			
			$ret = trim( $ret );
			$ret = str_replace( ' ', ',', $ret );
			$ret = str_replace( ',,', ',', $ret );
			$ret = str_replace( ',,', ',', $ret );
			$ret = str_replace( ',,', ',', $ret );
		}
		
		return $ret;
	}
	
	protected function parse_phone( $phone, $phone_alt )
	{
		$p1 = $this->clean_phone( $phone );
		$p2 = $this->clean_phone( $phone_alt );
		
		if ( !empty( $p1 ) && !empty( $p2 ) )
		{
			return $p1 . ',' . $p2;
		}
		else if ( !empty( $p1 ) )
		{
			return $p1;
		}
		
		return $p2;
	}
	
    public function file_validate( $path )
    {
		$ret = "";
		
		$this->load->model('admin/pacientes_model','pacientes', TRUE);
		$this->load->model('admin/equipos_model', 'equipos', TRUE);
		$this->load->model('admin/localidades_model', 'localidades', TRUE);
		$this->load->model('admin/profesionales_model', 'profesionales', TRUE);
		$this->load->model('admin/empresas_model', 'empresas', TRUE);
		
		define( 'CODSUC', 0 );
		define( 'PRODN', 1 );
		define( 'PID', 2 );
		define( 'PNAME', 3 );
		define( 'PADDR', 4 );
		define( 'PADDRREF', 5 );
		define( 'PLOC', 6 );
		define( 'PPHONE', 7 );
		define( 'PPHONE2', 8 );
		define( 'PROFID', 9 );
		define( 'PROFN', 10 );
		
		$handle = @fopen( $path, "r" );
		
		$res = '';
		
		if ( $handle )
		{
			$string		= file_get_contents( $path );
			$string		= str_replace("\r\n", "\n", $string); // normalize line endings
			$row		= 1;
			$success	= true;
			$hwadded	= array();
			$separator	= ';';
			$guesssep	= true;
			
			$suc = array();
			$eq = array();
			$pc = array();
			$loc = array();
			$prof = array();
			$locids = array();
			$eqids = array();
			$pacids = array();
			$sucids = array();
			
			if ( !( @iconv( 'utf-8', 'utf-8//IGNORE', $string ) == $string ) )
			{
				$string = @iconv( 'iso-8859-1', 'utf-8', $string );
			}
			
			$buffers	= explode( "\n", $string );
			$len		= count( $buffers );
			
			for ( $c = 0; $c < $len; $c++ )
			{
				$buffer	= $buffers[ $c ];
				$err	= false;
				$edit	= false;
				$buflen	= strlen( $buffer );
				$buffer	= ( $buflen >= 1 && $buffer[ $buflen - 1 ] == "\n" ) ? substr( $buffer, 0, $buflen - 1 ) : $buffer;
				
				if ( $guesssep )
				{
					$guesssep	= false;
					$c2			= substr_count( $buffer, ',' );
					
					if ( $c2 == 8 || $c2 == 10 )
					{
						$separator = ',';
					}
					
					$c2			= substr_count( $buffer, '	' );
					
					if ( $c2 == 8 || $c2 == 10 )
					{
						$separator = '	';
					}
				}
				
				$data	= str_getcsv( $buffer, $separator );
				$msg	= '';
				$num = count( $data );
				
				if ( is_numeric( $data[CODSUC] ) && $num >= 8 )
				{
					$key = (string)$data[CODSUC];
					if ( !isset( $suc[$key] ) )
					{
						$suc[$key]['empresa'] = $this->user_reg['company'];
						$suc[$key]['nombre'] = (string)$data[CODSUC];
						$suc[$key]['creado'] = date("Y-m-d H:i:s", time());
						$suc[$key]['habilitado'] = 1;
						$suc[$key]['estado'] = 1;
					}
					
					$key = ucwords_camelcase( $data[PRODN] );
					if ( !isset( $eq[$key] ) )
					{
						$eq[$key] = array();
						$eq[$key]['oriname'] = $key;
						$eq[$key]['empresa'] = $this->user_reg['company'];
						$eq[$key]['nombre'] = ucwords_camelcase($data[PRODN]);
						$eq[$key]['creado'] = date("Y-m-d H:i:s", time());
						$eq[$key]['habilitado'] = 1;
					}
					
					$key = ucwords_camelcase( $data[PLOC] );
					if ( !isset( $loc[$key] ) )
					{
						$loc[$key] = array();
						$loc[$key]['oriname'] = $key;
						$loc[$key]['empresa'] = $this->user_reg['company'];
						$loc[$key]['nombre'] = ucwords_camelcase( $data[PLOC] );
						$loc[$key]['creado'] = date("Y-m-d H:i:s", time());
						$loc[$key]['habilitado'] = 1;
					}
					
					$key = $data[PID];
					if ( !isset( $pc[$key] ) )
					{
						$pc[$key] = array();
						$pc[$key]['locid'] = ucwords_camelcase( $data[PLOC] );
						$pc[$key]['empresa'] = $this->user_reg['company'];
						
						if ( $this->user_reg['sucursal'] != "Master" && $this->user_reg['sucursal'] != '' )
						{
							$pc[$key]['sucursal'] = $this->user_reg['sucursal'];
						}
						else
						{
							$pc[$key]['sucursal'] = (string)$data[CODSUC];
						}
						
						$pc[$key]['nombreyapellido'] = ucwords_camelcase($data[PNAME]);
						$pc[$key]['direccion'] = $this->parse_dir( $data[PADDR] );
						$pc[$key]['telefono'] = $this->parse_phone( $data[PPHONE], $data[PPHONE2] );
						$pc[$key]['creado'] = date("Y-m-d H:i:s", time());
						$pc[$key]['habilitado'] = 1;
						$pc[$key]['direccion_completa'] = ucwords_camelcase($data[PADDR]);
						$pc[$key]['idPaciente'] = intval( $key );
						$pc[$key]['ref_direccion'] = ucwords_camelcase($data[PADDRREF]);
						$pc[$key]['auditado'] = 0;
					}
					
					if ( isset( $data[PROFID] ) && isset( $data[PROFN] ) )
					{
						$key = $data[PROFID];
						if ( !isset( $prof[$key] ) )
						{
							$prof[$key]['empresa'] = $this->user_reg['company'];
							
							if ( $this->user_reg['sucursal'] != "Master" && $this->user_reg['sucursal'] != '' )
							{
								$prof[$key]['sucursal'] = $this->user_reg['sucursal'];
							}
							else
							{
								$prof[$key]['sucursal'] = (string)$data[CODSUC];
							}
							
							$prof[$key]['apellidoynombre'] = ucwords_camelcase( $data[PROFN] );
							$prof[$key]['usuario'] = ucusername( $data[PROFN] );
							$prof[$key]['idEspecialidad'] = 25;
							$prof[$key]['creado'] = date("Y-m-d H:i:s", time());
							$prof[$key]['habilitado'] = 1;
							$password = rand_string(8);
							$prof[$key]['password'] = md5( $password );
							$prof[$key]['observaciones'] = 'password: ' . $password;
						}
					}
					
					$eq_id = ucwords_camelcase( $data[PRODN] );
					
					if ( isset( $pc[ $data[PID] ]['equipos'][ $eq_id ] ) )
					{
						$eq_id_c = 2;
						$created = false;
						
						do
						{
							$eq_id = ucwords_camelcase( $data[PRODN] . " ($eq_id_c)" );
							
							if ( !isset( $pc[ $data[PID] ]['equipos'][ $eq_id ] ) )
							{
								if ( !isset( $eq[$eq_id] ) )
								{
									$eq[$eq_id] = array();
									$eq[$eq_id]['oriname'] = $eq_id;
									$eq[$eq_id]['empresa'] = $this->user_reg['company'];
									$eq[$eq_id]['nombre'] = $eq_id;
									$eq[$eq_id]['creado'] = date("Y-m-d H:i:s", time());
									$eq[$eq_id]['habilitado'] = 1;
								}
								
								$pc[ $data[PID] ]['equipos'][ $eq_id ] = $eq_id;
								
								$created = true;
							}
							else
							{
								$eq_id_c++;
							}
						} while ( !$created && $eq_id_c < 10 );
					}
					else
					{
						$pc[ $data[PID] ]['equipos'][ $eq_id ] = $eq_id;
					}
					
					$prof[ $data[PROFID] ]['pacientes'][ $data[PID] ] = $data[PID];
				}
			}
			
			fclose( $handle );
			
			foreach ( $suc as $s )
			{
				$sucids[ $s['nombre'] ] = $this->empresas->upsertSucursal($s);
			}
			
			foreach ( $sucids as $sid )
			{
				$this->pacientes->disable( $this->user_reg['company'], $sid );
			}
			
			foreach ( $loc as $l )
			{
				$n = $l['oriname'];
				unset( $l['oriname'] );
				$locids[ $n ] = $this->localidades->upsert($l);
			}
			
			foreach ( $eq as $e )
			{
				$n = $e['oriname'];
				unset( $e['oriname'] );
				$eqids[ $n ] = $this->equipos->upsert($e);
			}
			
			if ( $this->user_reg['sucursal'] != "Master" && $this->user_reg['sucursal'] != '' )
			{
				$this->pacientes->resetSucursal( $this->user_reg['sucursal'] );
			}
			
			$sucursales_reset = array();
		
			foreach ( $pc as $p )
			{
				if ( $this->user_reg['sucursal'] == "Master" || $this->user_reg['sucursal'] == '' )
				{
					$sucursales_reset[ $sucids[ $p['sucursal'] ] ] = $sucids[ $p['sucursal'] ];
				}
			}
			
			if ( !empty( $sucursales_reset ) )
			{
				foreach ( $sucursales_reset as $sr )
				{
					$this->pacientes->resetSucursal( $sr );
				}
			}
			
			foreach ( $pc as $p )
			{
				$p['idLocalidad'] = $locids[ $p['locid'] ];
				
				$equipos = $p['equipos'];
				
				unset( $p['locid'] );
				unset( $p['equipos'] );
				
				$idPaciente = $this->pacientes->upsert($p);
				
				$pacids[ $p['idPaciente'] ] = $idPaciente;
				
				$earr = array();
				
				foreach ( $equipos as $e )
				{
					$earr[] = $eqids[ $e ];
				}
				
				$this->pacientes->updateEquipos( array( 'idPaciente' => $idPaciente, 'idEquipo' => $earr ) );
			}
			
			foreach ( $prof as $p )
			{
				$pacientes = $p['pacientes'];
				
				if ( $this->user_reg['sucursal'] == "Master" || $this->user_reg['sucursal'] == '' )
				{
					$p['sucursal'] = $sucids[ $p['sucursal'] ];
				}
				
				unset($p['pacientes']);
				
				$idProfesional = $this->profesionales->upsert($p);
				
				$parr = array();
				
				foreach ( $pacientes as $pac )
				{
					$parr[] = $pacids[ $pac ];
				}
				
				$this->profesionales->updatePacientes( array( 'idProfesional' => $idProfesional, 'idPaciente' => $parr ) );
			}
			
			return "SUBIDO";
		}
		
		return "ERROR";
	}
    
    public function upload()
    {
		$this->load->library( 'UploadHandler', array( 'script_url' => base_url('/admin/pacientes/upload/') ) );
		
		$resp = $this->uploadhandler->post(false);
		
		if ( isset( $resp['files'][0] ) && file_exists( TMPPATH . $resp['files'][0]->name ) )
		{
			$full_path	= TMPPATH . $resp['files'][0]->name;
			
			$resp['files'][0]->result = $this->file_validate( $full_path );
		}
		
		echo json_encode( $resp );
	}
}