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

class Empresas extends MY_Controller
{
    private $dir = 'empresas';
    private $nom = 'Empresas';
    private $dir1 = 'Nueva empresa';
    private $dir2 = 'Editar empresa';
    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['group']['name'] == 'admin') {
            $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;

            $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['group']['name'] == 'admin') {
            $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;

            $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/profesionales/index', 'refresh');
        }
    }

    function update()
    {
        /* - Campos requeridos - */
        $this->form_validation->set_rules('nombre', 'Nombre', 'required');
        $this->form_validation->set_rules('razon_social', 'Razon Social', 'required');
        $this->form_validation->set_rules('cuit', 'C.U.I.T.', 'required');
        /* - Campos NO requeridos - */
        $this->form_validation->set_rules('condicion_iva', 'I.V.A.');
        $this->form_validation->set_rules('telefono', 'Tel&eacute;fono');
        $this->form_validation->set_rules('domicilio_legal', 'Domicilio lega');
        $this->form_validation->set_rules('domicilio_fiscal', 'Domicilio fiscal');
        $this->form_validation->set_rules('localidad', 'Localidad');
        $this->form_validation->set_rules('web', 'WEB');
        $this->form_validation->set_rules('email', 'E-Mail');
        $this->form_validation->set_rules('logo', 'Logo');

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

            /* - Logo - */
            $config['upload_path'] = 'assets/archivos/' . $this->dir . '/logos/';
            $config['allowed_types'] = 'gif|jpg|jpeg|png';
            $config['max_size'] = '';
            $config['carpeta'] = array();

            $archivo = '';
            $error = NULL;

            if (isset($_FILES['logo']) && $_FILES['logo']['name'] != ''):
                $this->load->model('imagenes_model', '', TRUE);
                $archivo = $this->imagenes_model->do_upload($config, 'logo');
            endif;

            if ($archivo == FALSE) $this->index();

            $objeto = array(
                'nombre' => $this->input->post('nombre'),
                'razon_social' => $this->input->post('razon_social'),
                'cuit' => $this->input->post('cuit'),
                'condicion_iva' => $this->input->post('condicion_iva'),
                'telefono' => $this->input->post('telefono'),
                'localidad' => $this->input->post('localidad'),
                'domicilio_legal' => $this->input->post('domicilio_legal'),
                'domicilio_fiscal' => $this->input->post('domicilio_fiscal'),
                'web' => $this->input->post('web'),
                'email' => $this->input->post('email'),
                'habilitado' => $this->input->post('habilitado')
            );

            if ($id == 0):

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

                if ($archivo != '') $objeto['logo'] = $archivo;

                $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:

                if ($archivo != '') $objeto['logo'] = $archivo;

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

    /* - Sub AMB - */
    function sub_index($id)
    {
        $this->data['fields'] = array(
            'nombre' => 'Nombre',
            'localidad' => 'Localidad',
            'email' => 'E-Mail',
            'telefono' => 'Tel&eacute;fono',
            'habilitado' => 'Habilitado'
        );
        $this->data['empresa'] = $id;
        $this->data['habilitado'] = 1;
        $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_edit($id)
    {
        $this->data['empresa'] = $this->input->post('empresa');

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

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

    function sub_restaurar($id)
    {
        $this->data['fields'] = array(
            'nombre' => 'Nombre',
            'localidad' => 'Localidad',
            'email' => 'E-Mail',
            'telefono' => 'Tel&eacute;fono',
            'habilitado' => 'Habilitado'
        );
        $this->data['empresa'] = $id;
        $this->data['habilitado'] = 0;
        $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_update()
    {
        $id = $this->input->post('id');

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

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

            $id = $this->modelo->saveSucursal($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();
            $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('empresa'));
    }

    function sub_delete()
    {
        $this->modelo->deleteSucursal($this->input->post('sub_ele'), $this->input->post('empresa'));

        $this->load->model('admin/usuarios_model', '', TRUE);
        $this->usuarios_model->deleteSucursalYusuario($this->input->post('sub_ele'));

        //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('empresa'));
    }

    function sub_restore()
    {
        $this->modelo->restoreSucursal($this->input->post('sub_ele'), $this->input->post('empresa'));

        $this->load->model('admin/usuarios_model', '', TRUE);
        $this->usuarios_model->restoreSucursalYusuario($this->input->post('sub_ele'));

        //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('empresa'));
    }
}