<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
	
	class Users extends CI_Controller {

		public function __construct()
    	    {
        	        parent::__construct();
					$this->load->model('Users_model');
	        }


	    
	    public function login() {
       		//$datos['contenido'] = 'users/login';
       		$this->load->view('admin/users/login');
        }

        
		public function dologin() {
			if(!($this->session->userdata('id')))  {
				$usuario = $this->security->xss_clean(strip_tags($this->input->post('user')));
				$password = $this->security->xss_clean(strip_tags($this->input->post('password')));
				$datos['dbUser'] = $this->Users_model->login($usuario, $password);
				$datos['cuantos'] = 0;
				if ( $datos['dbUser']) {
					//if ($datos['dbUser']->password == MD5($password)) {
					if ($datos['dbUser']->clave == $password) {	
						$datos['cuantos'] = 1;
						$this->session->set_userdata('id', $datos['dbUser']->id);
						$this->session->set_userdata('name', $datos['dbUser']->nombre);
						$this->session->set_userdata('avatar', $datos['dbUser']->foto_perfil);
						$this->session->set_userdata('profile', $datos['dbUser']->tipo_usuario);
						$this->session->set_userdata('email',  $datos['dbUser']->correo);
						$this->session->set_userdata('condominio',  $datos['dbUser']->condominio_id);
						//$this->load->view('backend/index');
						redirect(base_url());
					} else {
						//error de contraseña
						//$this->load->view('users/wrongcredential', $datos);
						$datos['error'] = "Contraseña inválida";
						//$datos['contenido'] = 'users/login';
       					$this->load->view('admin/users/login', $datos);
					}
				} else {
					//error de usario
					//$this->load->view('users/wrongcredential2', $datos);
					$datos['error'] = "Usuario inválido";
					//$datos['contenido'] = 'users/login';
       				$this->load->view('admin/users/login', $datos);
				}

			} else {
				redirect(base_url());
			}
		}



		public function logout() {
			$this->session->sess_destroy;
			$this->session->unset_userdata('id');
			redirect(base_url());
		}


		function index() {
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."login");
			};

			if($this->session->userdata('profile') != 'admin')
			{
				redirect(base_url());
			};

			$datos['users'] = $this->Users_model->lista();
			$datos['editable'] = TRUE;
			$datos['controlador'] = 'users';
			$datos['titulo'] = "USERS";
			$datos['contenido'] = 'users/index';
			$this->load->view('templates/template_admin', $datos);
	    }

		public function new_user() {
			//verificacion de sesion activa
			if(!($this->session->userdata('id'))) 
				{
					redirect(base_url()."login");
				};


			$datos['titulo'] = "New User";
			$datos['contenido'] = 'users/new';
			$datos['editable'] = FALSE;
			$datos['controlador'] = 'users';
			$this->load->view('templates/template_admin', $datos);

		}

		public function save() {
			//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};

			$usuario = $this->security->xss_clean(strip_tags($this->input->post('username')));
			$password = $this->security->xss_clean(strip_tags($this->input->post('password')));

			 
			$valido = $this->Users_model->search($usuario);
			if ($valido->totalusers == 0) {
				$data['username'] = $usuario;
				$data['password'] = MD5($password);
				$data['name'] = $this->security->xss_clean(strip_tags($this->input->post('name')));
				$data['image'] = "profilepic.png";
				$data['profile'] =  $this->input->post('profile');
				$this->Users_model->insertar($data);
				redirect(base_url('admin/users'));
			} else {
				$datos['titulo'] = "New User";
				$datos['contenido'] = 'users/new';
				$datos['error'] = 'User already exists';
				$datos['editable'] = FALSE;
				$datos['controlador'] = 'users';
				$this->load->view('templates/template_admin', $datos);
			}
		}

		public function activate($idPic) {

	    	//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};

			$this->Users_model->activar($idPic);
			redirect($_SERVER['HTTP_REFERER']);

		}

	    public function deactivate($idPic) {

	    	//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};

			$this->Users_model->desactivar($idPic);
			redirect($_SERVER['HTTP_REFERER']);

		}

		public function edit($_id) {
			//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};

			$datos['detalle'] = $this->Users_model->detalle($_id);

			$datos['id'] = $_id;
			$datos['titulo'] = "Edit User Information";
			$datos['contenido'] = 'users/edit';
			$datos['controlador'] = 'users';
			$datos['editable'] = FALSE;
			$this->load->view('templates/template_admin', $datos);
		}

		public function update($_id) {
			//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};

			$usuario = $this->security->xss_clean(strip_tags($this->input->post('username')));
			$anteriorusuario = $this->security->xss_clean(strip_tags($this->input->post('oldusername')));
			$valido = $this->Users_model->search($usuario);
			if ($valido->totalusers == 0 || ($valido->totalusers == 1 && $usuario == $anteriorusuario)) {
				$data['username'] = $usuario;
				$data['name'] = $this->security->xss_clean(strip_tags($this->input->post('name')));
				$data['profile'] =  $this->input->post('profile');
				$this->Users_model->editar($data, $_id);
				redirect(base_url('admin/users'));
			} else {
				$datos['id'] = $_id;
				$datos['detalle'] = $this->Users_model->detalle($_id);
				$datos['titulo'] = "Edit User Information";
				$datos['contenido'] = 'users/edit';
				$datos['controlador'] = 'users';
				$datos['editable'] = FALSE;
				$datos['error'] = 'User already exists';
				$this->load->view('templates/template_admin', $datos);
			}
		}

		public function profile() {
			//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};

			$datos['detalle'] = $this->Users_model->profile($this->session->userdata('id'));

			
			$datos['titulo'] = "Edit My Profile";
			$datos['contenido'] = 'users/profile';
			$datos['controlador'] = 'users';
			$datos['editable'] = FALSE;
			$this->load->view('templates/template_admin', $datos);
		}

		public function updateprofile() {
			//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};


			if(!empty($_FILES['userfile']['name'])){
				$config['upload_path'] = './assets/img';
				$config['allowed_types'] = 'jpg|png';
				$config['max_filename'] = 20;
				//$config['filename'] = convert_accented_characters($FILES['userfile']['name']);

				$this->load->library('upload', $config);
				if (!$this->upload->do_upload()) {
					$datos['error'] = $this->upload->display_errors('<p>',' (Image) </p>');
					$datos['detalle'] = $this->Users_model->profile($this->session->userdata('id'));
					$datos['titulo'] = "Edit My Profile";
					$datos['contenido'] = 'users/profile';
					$datos['controlador'] = 'users';
					$datos['editable'] = FALSE;
					$this->load->view('templates/template_admin', $datos);
				} else {
					$data['image'] =  $this->upload->data('file_name');			
				}
			}
	
			$data['name'] = $this->security->xss_clean(strip_tags($this->input->post('name')));
			$this->Users_model->ActualizarProfile($data, $this->session->userdata('id'));
			redirect(base_url('admin/profile'));
		}

		public function changepassword() {
			//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};

		
			$datos['titulo'] = "Change Password";
			$datos['contenido'] = 'users/changepassword';
			$datos['controlador'] = 'users';
			$datos['editable'] = FALSE;
			$this->load->view('templates/template_admin', $datos);
		}

		public function updatepassword() {
			//verificacion de sesion activa
	    	if(!($this->session->userdata('id'))) 
			{
				redirect(base_url()."admin/login");
			};

			$usuario = $this->session->userdata('id');
			$oldpassword = $this->security->xss_clean(strip_tags($this->input->post('oldpassword')));
			$newpassword = $this->security->xss_clean(strip_tags($this->input->post('newpassword')));

			$datos['dbUser'] = $this->Users_model->login($usuario, $oldpassword);
			if ( $datos['dbUser']) {
				if ($datos['dbUser']->password == MD5($oldpassword)) {
					$data['password'] = MD5($newpassword);
					$this->Users_model->ActualizarClave($data, $usuario);
					redirect(base_url('admin'));
				}
				else {
					$datos['titulo'] = "Change Password";
					$datos['error'] = "Wrong Actual Password";
					$datos['contenido'] = 'users/changepassword';
					$datos['controlador'] = 'users';
					$datos['editable'] = FALSE;
					$this->load->view('templates/template_admin', $datos);
				}
			} else {
					$datos['titulo'] = "Change Password";
					$datos['error'] = "Wrong Actual Password";
					$datos['contenido'] = 'users/changepassword';
					$datos['controlador'] = 'users';
					$datos['editable'] = FALSE;
					$this->load->view('templates/template_admin', $datos);
				}
		}

		
}
	