<?php
ini_set("display_errors", 1);
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class User_model extends CI_Model {


	private function hash_password($password){
	    return password_hash($password, PASSWORD_BCRYPT);
    }

    public function isDuplicate($correo)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $otherdb->get_where('ed_clientes', array('correo' => $correo), 1);
        return $otherdb->affected_rows() > 0 ? TRUE : FALSE;
    }

    public function isDuplicateUsern($email)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $otherdb->get_where('ed_clientes', array('correo' => $email), 1);
        return $otherdb->affected_rows() > 0 ? TRUE : FALSE;
    }

    public function insertToken($email)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $token = substr(sha1(rand()), 0, 30);
        $date = date('Y-m-d');

				$otherdb->select('*');
				$otherdb->from('ed_clientes');
				$otherdb->where('correo', $email);
				$return = $otherdb->get()->result_array();

				if($return[0]['id']){
	        $string = array(
	                'token'=> $token.$return[0]['id'],
	                'user_id'=>$return[0]['id'],
	                'created'=>$date
	            );
	        $query = $otherdb->insert_string('ed_tokens',$string);
	        $test = $otherdb->query($query);
					if($test){
						return $token.$return[0]['id'];
					} else {
						return false;
					}
				} else {
					return false;
				}
    }

    public function isTokenValid($token)
    {
		$otherdb = $this->load->database('patsy', TRUE);
       $tkn = substr($token,0,30);
       $uid = substr($token,30);

        $q = $otherdb->get_where('ed_tokens', array(
            'token' => $token,
            'user_id' => $uid), 1);

        if($otherdb->affected_rows() > 0){
            $row = $q->row();

            $created = $row->created;
            $createdTS = strtotime($created);
            $today = date('Y-m-d');
            $todayTS = strtotime($today);

            if($createdTS != $todayTS){
                return false;
            }

            $user_info = $this->getUserInfo($row->user_id);
            return $user_info;

        } else {
            return false;
        }

    }

    public function getUserInfo($id)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $q = $otherdb->get_where('ed_clientes', array('id' => $id), 1);
        if($otherdb->affected_rows() > 0){
            $row = $q->row();
            unset($row->password_hash);
            return $row;
        }else{
            error_log('no user found getUserInfo('.$id.')');
            return false;
        }
    }

		public function getUser()
		{
			$otherdb = $this->load->database('patsy', TRUE);
				$q = $otherdb->get_where('ed_clientes');
				if($otherdb->affected_rows() > 0){
						$row = $q->result_array();
						unset($row->password_hash);
						unset($row->fecha_nacimiento);
						return $row;
				}else{
						error_log('no user found getUserInfo('.$id.')');
						return false;
				}
		}

    public function updateUserInfo($post)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $data = array(
               'password_hash' => $post['password_hash'],
               'last_login' => date('Y-m-d h:i:s A'),
               'status' => $this->status[1]
            );
        $otherdb->where('id', $post['user_id']);
        $otherdb->update('ed_clientes', $data);
        $success = $otherdb->affected_rows();

        if(!$success){
            error_log('Unable to updateUserInfo('.$post['user_id'].')');
            return false;
        }

        $user_info = $this->getUserInfo($post['user_id']);
        return $user_info;
    }

    public function checkLogin($post)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $this->load->library('password');
        $otherdb->select('*');
        $otherdb->where('correo', $post['email']);
        $query = $otherdb->get('ed_clientes');
        $userInfo = $query->row();

	    if(isset($userInfo->id)) {
            unset($userInfo->imagen);

						if(!$this->password->validate_password($post['password'], $userInfo->password_hash)){
								error_log('Unsuccessful login attempt('.$post['email'].')');
								return false;
						}
									$this->updateLoginTime($userInfo->id);


									$token = substr(sha1(rand()), 0, 30);
									$date = date('Y-m-d');

									if($userInfo->id){
										$string = array(
														'token'=> $token.$userInfo->id,
														'user_id'=>$userInfo->id,
														'created'=>$date
												);
										$query = $otherdb->insert_string('ed_tokens',$string);
										$test = $otherdb->query($query);
										if($test){
											$token = $token.$userInfo->id;
										} else {
											$token = '';
                                        }

                                        $otherdb->select('id,nombre,apellido,direccion,ciudad,estado,pais,codigo,email,
                                        telefono,name_card AS nameCard,month_expira,year_expira,digitos_tdc');
                                        $otherdb->from('tl_pagos');
                                        $otherdb->where('user_id', $userInfo->id);
                                        $otherdb->where('status', 1);
                                        $otherdb->group_by("digitos_tdc");
                                        $tdc = $otherdb->get()->result_array();
                                        $userInfo->tdc =  $tdc;

									} else {
										$token = '';
									}
									$userInfo->token = $token;

									unset($userInfo->password_hash);
									unset($userInfo->sexo);
									unset($userInfo->direccion);
									unset($userInfo->fecha_nacimiento);
									unset($userInfo->about);
									unset($userInfo->intro);

								//  $userInfo->main_banner = array('id' => 1,'nombre' => test,'url' => 'https://twitter.com/','fecha' => '2018-09-30 06:00:00','ed_negocios_id' => 1,'image' => 'http://easydog.pet/admin/web/uploads/1/11537558360.png', 'activo' => 1 );
								//  $userInfo->map_ads = array('0' => array('id' => 1,'nombre' => test,'url' => 'https://twitter.com/','fecha' => '2018-09-30 06:00:00','ed_negocios_id' => 1,'image' => 'http://easydog.pet/admin/web/uploads/1/11537558360.png'), '1' => array('id' => 2,'nombre' => test,'url' => 'https://twitter.com/','fecha' => '2018-09-30 06:00:00','ed_negocios_id' => 1,'image' => 'http://easydog.pet/admin/web/uploads/1/11537558360.png') );
									return $userInfo;

		} else {
			return FALSE;
		}


    }

    public function userInfo($token)
    {

		$otherdb = $this->load->database('patsy', TRUE);
			$otherdb->select('*');
			$otherdb->from('ed_tokens');
			$otherdb->where('token', $token);
			$user = $otherdb->get()->result_array();

			if (isset($user[0]['user_id'])) {

			$otherdb->select('*');
			$otherdb->where('id', $user[0]['user_id']);
			$query = $otherdb->get('ed_clientes');
			$userInfo = $query->row();

			if(isset($userInfo->id)) {

					unset($userInfo->imagen);

								$this->updateLoginTime($userInfo->id);


								$token = substr(sha1(rand()), 0, 30);
								$date = date('Y-m-d');

								if($userInfo->id){
									$string = array(
													'token'=> $token.$userInfo->id,
													'user_id'=>$userInfo->id,
													'created'=>$date
											);
									$query = $otherdb->insert_string('ed_tokens',$string);
									$test = $otherdb->query($query);
									if($test){
										$token = $token.$userInfo->id;
									} else {
										$token = '';
																			}

																			$otherdb->select('id,nombre,apellido,direccion,ciudad,estado,pais,codigo,email,
																			telefono,name_card AS nameCard,month_expira,year_expira,digitos_tdc');
																			$otherdb->from('tl_pagos');
																			$otherdb->where('user_id', $userInfo->id);
																			$otherdb->where('status', 1);
																			$otherdb->group_by("digitos_tdc");
																			$tdc = $otherdb->get()->result_array();
																			$userInfo->tdc =  $tdc;

								} else {
									$token = '';
								}
								$userInfo->token = $token;

								unset($userInfo->password_hash);
								unset($userInfo->sexo);
								unset($userInfo->direccion);
								unset($userInfo->fecha_nacimiento);
								unset($userInfo->about);
								unset($userInfo->intro);

							//  $userInfo->main_banner = array('id' => 1,'nombre' => test,'url' => 'https://twitter.com/','fecha' => '2018-09-30 06:00:00','ed_negocios_id' => 1,'image' => 'http://easydog.pet/admin/web/uploads/1/11537558360.png', 'activo' => 1 );
							//  $userInfo->map_ads = array('0' => array('id' => 1,'nombre' => test,'url' => 'https://twitter.com/','fecha' => '2018-09-30 06:00:00','ed_negocios_id' => 1,'image' => 'http://easydog.pet/admin/web/uploads/1/11537558360.png'), '1' => array('id' => 2,'nombre' => test,'url' => 'https://twitter.com/','fecha' => '2018-09-30 06:00:00','ed_negocios_id' => 1,'image' => 'http://easydog.pet/admin/web/uploads/1/11537558360.png') );
								return $userInfo;

							} else return FALSE;
	} else return FALSE;



    }

    public function updateLoginTime($id)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $otherdb->where('id', $id);
        $otherdb->update('ed_clientes', array('last_login' => date('Y-m-d h:i:s A')));
        return;
    }

    public function getUserInfoBycorreo($correo)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $q = $otherdb->get_where('ed_clientes', array('correo' => $correo), 1);
        if($otherdb->affected_rows() > 0){
            $row = $q->row();
            return $row;
        }else{
            error_log('no user found getUserInfo('.$correo.')');
            return false;
        }
    }

    public function updatePassword($post)
    {
		$otherdb = $this->load->database('patsy', TRUE);
        $otherdb->where('id', $post['user_id']);
        $otherdb->update('ed_clientes', array('password_hash' => $this->password->create_hash($post['password']) ) );
        $success = $otherdb->affected_rows();

        if(!$success){
            error_log('Unable to updatePassword('.$post['user_id'].')');
            return false;
        }
        return true;
    }

}
