<?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 = 'apellido', $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');

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

    function restaurar($sort_by = 'apellido', $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 . "/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');

        $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/obras_sociales_model', '', TRUE);
        $this->load->model('admin/localidades_model', '', TRUE);
        $sqlOL['habilitado'] = 1;
        $sqlOL['empresa'] = $this->user_reg['company'];
        $sqlOL['sort_order'] =  'asc';
        $sqlOL['sort_by'] = 'nombre';
        /* - Obras Sociales - */
        $obras_sociales = $this->obras_sociales_model->getAll($sqlOL);
        $this->data['obras_sociales'] = $obras_sociales['rows'];
        /* - Localidades - */
        $localidades = $this->localidades_model->getAll($sqlOL);
        $this->data['localidades'] = $localidades['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('nombre', 'Nombre', 'required');
        $this->form_validation->set_rules('apellido', 'Apellido', 'required');
        $this->form_validation->set_rules('idObraSocial', 'Obra Social', 'required');
        $this->form_validation->set_rules('numero_afiliado', 'Numero de afiliado', '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('piso', 'Piso');
        $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'],
                    'nombre' => $this->input->post('nombre'),
                    'apellido' => $this->input->post('apellido'),
                    'idLocalidad' => $this->input->post('idLocalidad'),
                    'idObraSocial' => $this->input->post('idObraSocial'),
                    'numero_afiliado' => $this->input->post('numero_afiliado'),
                    'email' => $this->input->post('email'),
                    'direccion' => $this->input->post('direccion'),
                    'piso' => $this->input->post('piso'),
                    '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'),
                    'nombre' => $this->input->post('nombre'),
                    'apellido' => $this->input->post('apellido'),
                    'idLocalidad' => $this->input->post('idLocalidad'),
                    'idObraSocial' => $this->input->post('idObraSocial'),
                    'numero_afiliado' => $this->input->post('numero_afiliado'),
                    'email' => $this->input->post('email'),
                    'direccion' => $this->input->post('direccion'),
                    'piso' => $this->input->post('piso'),
                    '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;

            if ($id == 0):

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

                $id = $this->modelo->save($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>";
                $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->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 . '/index', 'refresh');
    }

    /* - Sub AMB - */
    function sub_index($id, $idLocalidad = NULL)
    {
        $this->data['fields'] = array(
            'profesional' => 'Profesional',
            'hora_sesion' => 'Hora|Sesi&oacute;n',
            //'duracion_sesion' => 'Duraci&oacute;n',
            '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',
            'hora_sesion' => 'Hora|Sesi&oacute;n',
            //'duracion_sesion' => 'Duraci&oacute;n',
            '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('hora_sesion', 'Hora | Sesion', 'required');
        /* - Campos NO requeridos - */
        $this->form_validation->set_rules('idProfesional', 'Profesional');
        $this->form_validation->set_rules('honorarios_s', 'Honorarios');
        $this->form_validation->set_rules('honorarios_h', 'Honorarios');
        $this->form_validation->set_rules('duracion_sesion_s', 'Duraci&oacute;n');
        $this->form_validation->set_rules('duracion_sesion_h', 'Duraci&oacute;n');
        $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;

                if($this->input->post('hora_sesion') == '0'):
                    $duracion = date("H:i", mktime(0, $this->input->post('duracion_sesion_s')));
                    $objeto['duracion_sesion'] = $duracion;
                    $objeto['honorarios'] = $this->input->post('honorarios_s');
                else:
                    $duracion = gmdate('H:i:s', ($this->input->post('duracion_sesion_h') * 3600));
                    $objeto['duracion_sesion'] = $duracion;
                    $objeto['honorarios'] = $this->input->post('honorarios_h');
                endif;
                unset($objeto['duracion_sesion_s'], $objeto['duracion_sesion_h'], $objeto['honorarios_s'], $objeto['honorarios_h']);

                $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']);

               if($this->input->post('hora_sesion') == '0'):
                    $duracion = date("H:i", mktime(0, $this->input->post('duracion_sesion_s')));
                    $objeto['duracion_sesion'] = $duracion;
                    $objeto['honorarios'] = $this->input->post('honorarios_s');
                else:
                    $duracion = gmdate('H:i:s', ($this->input->post('duracion_sesion_h') * 3600));
                    $objeto['duracion_sesion'] = $duracion;
                    $objeto['honorarios'] = $this->input->post('honorarios_h');
                endif;
                unset($objeto['duracion_sesion_s'], $objeto['duracion_sesion_h'], $objeto['honorarios_s'], $objeto['honorarios_h']);
                
                $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'));
    }
}