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

class Sucursales extends MY_Controller
{
    private $dir = 'sucursales';
    private $nom = 'Sucursales';
    private $dir1 = 'Nueva sucursal';
    private $dir2 = 'Editar sucursal';
    private $dir3 = 'Sucursales';

    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;
    }

    function index($sort_by = 'nombre', $sort_order = 'asc', $offset = 0)
    {
        if($this->user_reg['sucursal'] == 'Master') {
            $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;
            /* - Habilitado 1 - Activo | 0 - Eliminado */
            $sql['habilitado'] = 1;
            /* - Empresa - */
            $sql['empresa'] = $this->user_reg['company'];

            $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);
        }
        else {
            redirect('admin/profesionales/index', 'refresh');
        }
    }

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

        $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 restaurar($sort_by = 'nombre', $sort_order = 'asc', $offset = 0)
    {
        if($this->user_reg['sucursal'] == 'Master') {
            $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;
            /* - Habilitado 1 - Activo | 0 - Eliminado */
            $sql['habilitado'] = 0;
            /* - Empresa - */
            $sql['empresa'] = $this->user_reg['company'];

            $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);
        }
        else {
            redirect('admin/' . $this->dir . '/index', 'refresh');
        }
    }

    function update()
    {
        /* - Campos requeridos - */
        $this->form_validation->set_rules('nombre', 'Nombre', 'required');
        /* - Campos NO requeridos - */
        $this->form_validation->set_rules('telefono', 'Tel&eacute;fono');
        $this->form_validation->set_rules('domicilio_legal', 'Domicilio legal');
        $this->form_validation->set_rules('localidad', 'Localidad');
        $this->form_validation->set_rules('email', 'E-Mail');
        $this->form_validation->set_rules('habilitado', 'Habilitado');

        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:

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

            $objeto = array(
                'empresa' => $this->user_reg['company'],
                'nombre' => $this->input->post('nombre'),
                'domicilio' => $this->input->post('domicilio_legal'),
                'localidad' => $this->input->post('localidad'),
                'telefono' => $this->input->post('telefono'),
                'email' => $this->input->post('email'),
                'habilitado' => $this->input->post('habilitado')
            );

            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');
            else:

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

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

        $this->load->model('admin/usuarios_model', '', TRUE);
        $this->usuarios_model->deleteEmpresaYusuario($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->load->model('admin/usuarios_model', '', TRUE);
        $this->usuarios_model->restoreEmpresaYusuario($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');
    }
}