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


class Md_patsyapp extends CI_Model
{

	public function putPosition($token, $lat, $long)
	{
		$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'])) {
			$user = $user[0]['user_id'];
			$otherdb->select('*');
			$otherdb->from('ed_user_location');
			$otherdb->where('user_id', $user);
			$data = $otherdb->get()->result_array();
			if ($data) {

				$data2 = array(
					'lat' => $lat,
					'longitud' => $long,
					'time' => date("Y-m-d H:i:s"),
				);
				$otherdb->where('user_id', $user);
				$return = $otherdb->update('ed_user_location', $data2);
			} else {
				$data2 = array(
					'lat' => $lat,
					'longitud' => $long,
					'time' => date("Y-m-d H:i:s"),
					'user_id' => $user,
				);
				$otherdb->insert('ed_user_location', $data2);
				$return = $otherdb->insert_id();
			}
		} else {
			$return = FALSE;
		}

		return $return;
	}
	public function insertOrder($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($cleanPost['token'])) $token = $cleanPost['token'];
		else $token = '';
		if (isset($cleanPost['tl_negocios_id'])) $tl_negocios_id = $cleanPost['tl_negocios_id'];
		else $tl_negocios_id = '';
		if (isset($cleanPost['latitude'])) $latitude = $cleanPost['latitude'];
		else $latitude = '';
		if (isset($cleanPost['longitude'])) $longitude = $cleanPost['longitude'];
		else $longitude = '';
		if (isset($cleanPost['information'])) $information = $cleanPost['information'];
		else $information = '';
		if (isset($cleanPost['address'])) $address = $cleanPost['address'];
		else $address = '';
		if (isset($cleanPost['tl_tipos_pago_id'])) $tl_tipos_pago_id = $cleanPost['tl_tipos_pago_id'];
		else $tl_tipos_pago_id = '';
		if (isset($cleanPost['orders'])) $orders = $cleanPost['orders'];
		else $orders = '';

		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();

		if (isset($user[0]['user_id']) && !empty($tl_negocios_id) && !empty($latitude) && !empty($longitude) && !empty($orders)) {
			$data = array(
				'ed_clientes_id' => $user[0]['user_id'],
				'tl_negocios_id' => $tl_negocios_id,
				'latitude' => $latitude,
				'longitude' => $longitude,
				'date_created' => date('Y-m-d H:i:s'),
				'address' => $address,
				'information' => $information,
				'tl_tipos_pago_id' => $tl_tipos_pago_id,
				'status' => 0,
			);
			$error = $otherdb->insert('tl_compras2', $data);
			if (isset($error)) {
				$tl_compras_id = $otherdb->insert_id();


			/*	error_log(json_encode($orders));

				{"tl_productos_id":"1","quantity":"3","instructions":"Test5"}

				if (is_array($orders)) {
					$order = $orders;
				} else $order = json_decode($orders);*/

				if ($orders) {

					foreach ($orders as $value) {

						error_log(json_encode($value));

						if (isset($value['tl_productos_id'])) $tl_productos_id = $value['tl_productos_id'];
						else $tl_productos_id = '';
						if (isset($value['quantity'])) $quantity = $value['quantity'];
						else $quantity = '';
						if (isset($value['instructions'])) $instructions = $value['instructions'];
						else $instructions = '';

						error_log($value['tl_productos_id']);

						$data2 = array(
							'tl_productos_id' => $tl_productos_id,
							'quantity' => $quantity,
							'instructions' => $instructions,
							'tl_compras_id' => $tl_compras_id,
						);
						$error = $otherdb->insert('tl_orders', $data2);

						error_log(json_encode($data2));
					}

					$data3 = array(
						'ed_clientes_id' => $user[0]['user_id'],
						'type' => 3,
						'status' => 1,
						'date_created' => date('Y-m-d H:i:s', (time() - 6 * 60 * 60)),
						'date_updated' => date('Y-m-d H:i:s', (time() - 6 * 60 * 60)),
						'tl_compras_id' => $tl_compras_id,
						'description' => 'Su #'.$tl_compras_id.' compra está en espera de recolección',
					);
					$error = $otherdb->insert('tl_notificaciones', $data3);


				}

				$return = $tl_compras_id;

			} else $return = FALSE;
		} else $return = FALSE;

		return $return;
	}

	public function insertLike($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($cleanPost['token'])) $token = $cleanPost['token'];
		else $token = '';
		if (isset($cleanPost['tl_productos_id'])) $tl_productos_id = $cleanPost['tl_productos_id'];
		else $tl_productos_id = '';

		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();

		if (isset($user[0]['user_id']) && !empty($tl_productos_id)) {
			$data = array(
				'ed_clientes_id' => $user[0]['user_id'],
				'tl_productos_id' => $tl_productos_id,
			);
			$return = $otherdb->insert('tl_likes', $data);
		} else $return = FALSE;
		return $return;
	}

	public function insertClient($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($cleanPost['title'])) $title = $cleanPost['title'];
		else $title = '';
		if (isset($cleanPost['description'])) $description = $cleanPost['description'];
		else $description = '';
		if (isset($cleanPost['color1'])) $color1 = $cleanPost['color1'];
		else $color1 = '';
		if (isset($cleanPost['color2'])) $color2 = $cleanPost['color2'];
		else $color2 = '';
		if (isset($cleanPost['color3'])) $color3 = $cleanPost['color3'];
		else $color3 = '';
		if (isset($cleanPost['logo'])) $logo = $cleanPost['logo'];
		else $logo = '';
		if (isset($cleanPost['splash'])) $splash = $cleanPost['splash'];
		else $splash = '';
		if (isset($cleanPost['url1'])) $url1 = $cleanPost['url1'];
		else $url1 = '';
		if (isset($cleanPost['url2'])) $url2 = $cleanPost['url2'];
		else $url2 = '';
		if (isset($cleanPost['cliente'])) $cliente = $cleanPost['cliente'];
		else $cliente = '';

		$data = array(
				'title' => $title,
				'description' => $description,
				'color1' => $color1,
				'color2' => $color2,
				'color3' => $color3,
				'logo' => $logo,
				'splash' => $splash,
				'url1' => $url1,
				'url2' => $url2,
				'cliente' => $cliente,
		);
		$return = $otherdb->insert('tl_clientes', $data);
	
		return $return;
	}

	public function deleteTdc($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($cleanPost['token'])) $token = $cleanPost['token'];
		else $token = '';
		if (isset($cleanPost['tdc_id'])) $tdc_id = $cleanPost['tdc_id'];
		else $tdc_id = '';

		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();

		if (isset($user[0]['user_id']) && !empty($tdc_id)) {
			$data = array(
				'status' => 0,
			);
			$otherdb->where('id', $tdc_id);
			$otherdb->where('user_id', $user[0]['user_id']);
			$otherdb->update('tl_pagos', $data);
			$return = TRUE;
		} else $return = FALSE;

		return $return;
	}

	public function insertLiken($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($cleanPost['token'])) $token = $cleanPost['token'];
		else $token = '';
		if (isset($cleanPost['tl_negocios_id'])) $tl_negocios_id = $cleanPost['tl_negocios_id'];
		else $tl_negocios_id = '';

		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();

		if (isset($user[0]['user_id']) && !empty($tl_negocios_id)) {
			$data = array(
				'ed_clientes_id' => $user[0]['user_id'],
				'tl_negocios_id' => $tl_negocios_id,
			);
			$return = $otherdb->insert('tl_likes', $data);
		} else $return = FALSE;
		return $return;
	}

	public function insertPayment($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($cleanPost['token'])) $token = $cleanPost['token'];
		else $token = '';
		if (isset($cleanPost['tl_compras_id'])) $tl_compras_id = $cleanPost['tl_compras_id'];
		else $tl_compras_id = '';
		if (isset($cleanPost['amount'])) $amount = $cleanPost['amount'];
		else $amount = '';
		if (isset($cleanPost['nombre'])) $nombre = $cleanPost['nombre'];
		else $nombre = '';
		if (isset($cleanPost['apellido'])) $apellido = $cleanPost['apellido'];
		else $apellido = '';
		if (isset($cleanPost['direccion'])) $direccion = $cleanPost['direccion'];
		else $direccion = '';
		if (isset($cleanPost['ciudad'])) $ciudad = $cleanPost['ciudad'];
		else $ciudad = '';
		if (isset($cleanPost['estado'])) $estado = $cleanPost['estado'];
		else $estado = '';
		if (isset($cleanPost['pais'])) $pais = $cleanPost['pais'];
		else $pais = '';
		if (isset($cleanPost['codigo'])) $codigo = $cleanPost['codigo'];
		else $codigo = '';
		if (isset($cleanPost['email'])) $email = $cleanPost['email'];
		else $email = '';
		if (isset($cleanPost['telefono'])) $telefono = $cleanPost['telefono'];
		else $telefono = '';
		if (isset($cleanPost['month_expira'])) $month_expira = $cleanPost['month_expira'];
		else $month_expira = '';
		if (isset($cleanPost['year_expira'])) $year_expira = $cleanPost['year_expira'];
		else $year_expira = '';
		if (isset($cleanPost['digitos_tdc'])) $digitos_tdc = $cleanPost['digitos_tdc'];
		else $digitos_tdc = '';
		if (isset($cleanPost['nameCard'])) $nameCard = $cleanPost['nameCard'];
		else $nameCard = '';
		if (isset($cleanPost['cvvCard'])) $cvvCard = $cleanPost['cvvCard'];
		else $cvvCard = '';
		/*if (isset($cleanPost['ref'])) $ref = $cleanPost['ref'];
		else $ref = '';*/

		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();

		if (isset($user[0]['user_id']) && !empty($tl_compras_id) && !empty($amount)) {

			$time = date('Y-m-d H:i:s');

			/*$tar = explode("-", $digitos_tdc);
			$digitos_tdc = $tar[0].$tar[1].$tar[2].$tar[3];*/
/*
			$empresa = array(
			    'idenEmpresa'=> 'S295449903',
			    'key_secret' => 'cuf1jiYWTjLxThTuakbl4PW4OEEsKJSRFVQK14hI',
					'key_public' => 'VthIsQGVYauScLydpz5FvemFLrDK82ckBU2Mhth4',
			);

			$cliente= array(
				'firstName'   => $nombre,
				'lastName'    => $apellido,
				'street1'     => $direccion,
				'phone'       => $telefono,
				'country'     => $pais,
				'city'        => $ciudad,
				'state'       => $estado,
				'postalCode'  => $codigo,
				'email'       => $email,
				'ipAddress'   => '207.180.216.245',
				'Total'       => $amount,
				'fecha_transaccion' => $time,
				'currency' 	  => 'GTQ',
				'deviceFingerprintID' => '',
			);

			$detalle=[];
			  $detalle[] = array(
				'id_producto'   => 1,
				'cantidad'      => 1,
				'tipo'          => 'W',
				'nombre'        => 'Compra',
				'precio'        => $amount,
				'Subtotal'      => $amount,
			);

			$tarjetaPagalo = array(
			  'nameCard'       => $nameCard,
			  'accountNumber'  => $digitos_tdc,
			  'expirationMonth'=> $month_expira,
			  'expirationYear' => $year_expira,
			  'CVVCard'        => $cvvCard,
			);

			$str_empresa = json_encode($empresa);
			$str_cliente = json_encode($cliente);
			$str_detalle = json_encode($detalle);
			$str_tarjeta = json_encode($tarjetaPagalo);

			$data=array('empresa' => $str_empresa, 'cliente' => $str_cliente, 'detalle' => $str_detalle, 'tarjetaPagalo' => $str_tarjeta);
				$str_data = json_encode($data);

				$url = 'https://app.pagalocard.com/api/v1/integracion/UvlDZngwKGsSeaIkhSKF';
				$ch = curl_init($url);

				curl_setopt($ch, CURLOPT_POST,1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);

			$result = curl_exec($ch);
			$result = json_decode($result,true);
			$decision = json_encode($result,true);
			$response = curl_exec($ch);
			$err = curl_error($ch);
			curl_close($ch);
*/

			$decision = 1;  //QUITARR!!!!!
			$result = array(); //QUITARR!!!
			$result['estado']=1; //QUITAR!!!!!!!!!!


			if(isset($result['estado'])){

				if ($result['estado'] == 2) {
					$return = FALSE;

					$last_four = substr ($digitos_tdc, -4);
					$data = array(
					  'tl_compras_id' => $tl_compras_id,
					  'amount' => $amount,
					  'date_created' => $time,
					  'nombre' => $nombre,
					  'apellido' => $apellido,
					  'direccion' => $direccion,
					  'ciudad' => $ciudad,
					  'estado' => $estado,
					  'pais' => $pais,
					  'codigo' => $codigo,
					  'email' => $email,
					  'telefono' => $telefono,
					  'month_expira' => $month_expira,
					  'year_expira' => $year_expira,
					  'digitos_tdc' => $last_four,
					  'digitos_tdc' => $nameCard,
					  'user_id' => $user[0]['user_id'],
					  'name_card' => $nameCard,
					  'ref' => $decision,
					  'status' => 0,
				  );
				  $error = $otherdb->insert('tl_pagos', $data);

				} else if ($result['estado'] == 1) {
					$last_four = substr ($digitos_tdc, -4);
					  $data = array(
						'tl_compras_id' => $tl_compras_id,
						'amount' => $amount,
						'date_created' => $time,
						'nombre' => $nombre,
						'apellido' => $apellido,
						'direccion' => $direccion,
						'ciudad' => $ciudad,
						'estado' => $estado,
						'pais' => $pais,
						'codigo' => $codigo,
						'email' => $email,
						'telefono' => $telefono,
						'month_expira' => $month_expira,
						'year_expira' => $year_expira,
						'digitos_tdc' => $last_four,
						'user_id' => $user[0]['user_id'],
						'name_card' => $nameCard,
						'ref' => $decision,
						'status' => 1,
					);
					$error = $otherdb->insert('tl_pagos', $data);
					if ($error) {
						$data = array(
							'status' => 1,
						);
						$otherdb->where('id', $tl_compras_id);
						$otherdb->update('tl_compras2', $data);

						return $return = $tl_compras_id;
					} else $return = FALSE;

				}
			} else $return = FALSE;

		} else $return = FALSE;
		return $return;
	}

	public function insertPayment3($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($cleanPost['token'])) $token = $cleanPost['token'];
		else $token = '';

		$amount = 1;
		if (isset($cleanPost['nombre'])) $nombre = $cleanPost['nombre'];
		else $nombre = '';
		if (isset($cleanPost['apellido'])) $apellido = $cleanPost['apellido'];
		else $apellido = '';
		if (isset($cleanPost['direccion'])) $direccion = $cleanPost['direccion'];
		else $direccion = '';
		if (isset($cleanPost['ciudad'])) $ciudad = $cleanPost['ciudad'];
		else $ciudad = '';
		if (isset($cleanPost['estado'])) $estado = $cleanPost['estado'];
		else $estado = '';
		if (isset($cleanPost['pais'])) $pais = $cleanPost['pais'];
		else $pais = '';
		if (isset($cleanPost['codigo'])) $codigo = $cleanPost['codigo'];
		else $codigo = '';
		if (isset($cleanPost['email'])) $email = $cleanPost['email'];
		else $email = '';
		if (isset($cleanPost['telefono'])) $telefono = $cleanPost['telefono'];
		else $telefono = '';
		if (isset($cleanPost['month_expira'])) $month_expira = $cleanPost['month_expira'];
		else $month_expira = '';
		if (isset($cleanPost['year_expira'])) $year_expira = $cleanPost['year_expira'];
		else $year_expira = '';
		if (isset($cleanPost['digitos_tdc'])) $digitos_tdc = $cleanPost['digitos_tdc'];
		else $digitos_tdc = '';
		if (isset($cleanPost['nameCard'])) $nameCard = $cleanPost['nameCard'];
		else $nameCard = '';
		if (isset($cleanPost['cvvCard'])) $cvvCard = $cleanPost['cvvCard'];
		else $cvvCard = '';
	/*	if (isset($cleanPost['ref'])) $ref = $cleanPost['ref'];
		else $ref = '';*/

		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();

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


			$time = date('Y-m-d H:i:s');

			/*$tar = explode("-", $digitos_tdc);
			$digitos_tdc = $tar[0].$tar[1].$tar[2].$tar[3];*/


					$return = TRUE;

					$last_four = substr ($digitos_tdc, -4);
					$data = array(
					  'tl_compras_id' => 1,
					  'amount' => 1,
					  'date_created' => $time,
					  'nombre' => $nombre,
					  'apellido' => $apellido,
					  'direccion' => $direccion,
					  'ciudad' => $ciudad,
					  'estado' => $estado,
					  'pais' => $pais,
					  'codigo' => $codigo,
					  'email' => $email,
					  'telefono' => $telefono,
					  'month_expira' => $month_expira,
					  'year_expira' => $year_expira,
					  'digitos_tdc' => $last_four,
					  'name_card' => $nameCard,
					  'user_id' => $user[0]['user_id'],
					  'ref' => 1,
					  'status' => 1,
				  );
				  $error = $otherdb->insert('tl_pagos', $data);






		} else $return = FALSE;
		return $return;
	}

	public function insertPayment2($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($cleanPost['token'])) $token = $cleanPost['token'];
		else $token = '';
		if (isset($cleanPost['tl_compras_id'])) $tl_compras_id = $cleanPost['tl_compras_id'];
		else $tl_compras_id = '';
		if (isset($cleanPost['amount'])) $amount = $cleanPost['amount'];
		else $amount = '';
		if (isset($cleanPost['tdc_id'])) $tdc_id = $cleanPost['tdc_id'];
		else $tdc_id = '';


		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();

		if (isset($user[0]['user_id']) && !empty($tl_compras_id) && !empty($amount) && !empty($tdc_id)) {

			$time = date('Y-m-d H:i:s');

			$result = array();
			$result['estado'] = 1;


						$data = array(
							'status' => 1,
						);
						$otherdb->where('id', $tl_compras_id);
						$otherdb->update('tl_compras2', $data);
						$return = $tl_compras_id;

		} else $return = FALSE;
		return $return;
	}

	public function getPosition($user)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_user_location');
		$otherdb->where('user_id', $user);
		$return = $otherdb->get()->result_array();

		return $return;
	}

	public function getClients()
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('tl_clientes');
		$return = $otherdb->get()->result_array();

		return $return;
	}

	public function getAll()
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_clientes');
		$return = $otherdb->get()->result_array();

		return $return;
	}

	public function getOrders($token)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();
		$return = array();
		if (isset($user[0]['user_id'])) {
			$otherdb->select('tl_status.name AS status, tl_compras2.date_created AS time, tl_negocios.name AS from_address, tl_compras2.address AS to_address');
			$otherdb->from('tl_compras2');
			$otherdb->join('tl_status', 'tl_compras2.status = tl_status.id');
			$otherdb->join('tl_negocios', 'tl_compras2.tl_negocios_id = tl_negocios.id');
			$otherdb->where('ed_clientes_id', $user[0]['user_id']);
			//$otherdb->where('status', 1);
			$return = $otherdb->get()->result_array();
		}
		return $return;
	}

	public function getDelivery($token)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();
		$return = array();
		if (isset($user[0]['user_id'])) {
			$otherdb->select('tl_compras2.id AS compraId, tl_negocios.name AS negocio, tl_negocios.latitude AS latNegocio, tl_negocios.longitude AS lngNegocio, tl_repartidor_orden.latitud AS latRepartidor,
			tl_repartidor_orden.longitud AS lngRepartidor, tl_compras2.latitude AS latEntrega
			, tl_compras2.longitude AS lngEntrega, tl_repartidores.name AS repartidorName, tl_repartidores.phone AS repartidorPhone
			, tl_status_orden.name AS status, tl_repartidor_orden.status AS statusId, tl_repartidor_orden.date_updated');
			$otherdb->from('tl_repartidor_orden');
			$otherdb->join('tl_status_orden', 'tl_repartidor_orden.status = tl_status_orden.id');
			$otherdb->join('tl_compras2', 'tl_repartidor_orden.tl_compras_id = tl_compras2.id');
			$otherdb->join('tl_negocios', 'tl_compras2.tl_negocios_id = tl_negocios.id');
			$otherdb->join('tl_repartidores', 'tl_repartidor_orden.tl_repartidor_id = tl_repartidores.id');
			$otherdb->where('tl_compras2.ed_clientes_id', $user[0]['user_id']);
			//$otherdb->where('tl_repartidor_orden.status', 1);
			$return = $otherdb->get()->result_array();

			if (!isset($return[0])) {

				$otherdb->select('tl_compras2.id AS compraId, tl_negocios.name AS negocio, tl_negocios.latitude AS latNegocio, tl_negocios.longitude AS lngNegocio, tl_compras2.latitude AS latEntrega
				, tl_compras2.longitude AS lngEntrega, tl_compras2.date_created AS date_updated');
				$otherdb->from('tl_compras2');
				$otherdb->join('tl_negocios', 'tl_compras2.tl_negocios_id = tl_negocios.id');
				$otherdb->where('tl_compras2.ed_clientes_id', $user[0]['user_id']);
				$otherdb->where('tl_compras2.status', 1);
				$return = $otherdb->get()->result_array();

				if (isset($return[0])) {
					$return[0]['latRepartidor'] = "";
					$return[0]['lngRepartidor'] = "";
					$return[0]['repartidorName'] = "No asignado";
					$return[0]['repartidorPhone'] = "No asignado";
					$return[0]['status'] = "EN ESPERA";
					$return[0]['statusId'] = 0;
				}

			}
		}
		return $return;
	}

	public function getNotifications($token)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $token);
		$user = $otherdb->get()->result_array();
		$return = array();
		if (isset($user[0]['user_id'])) {
			$otherdb->select('tl_type.name AS status, date_created AS time, description');
			$otherdb->from('tl_notificaciones');
			$otherdb->join('tl_type', 'tl_notificaciones.type = tl_type.id');
			$otherdb->where('ed_clientes_id', $user[0]['user_id']);
			$otherdb->where('status', 1);
			$return = $otherdb->get()->result_array();
		}
		return $return;
	}

	public function getEvents()
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_eventos');
		$otherdb->where("(start >= '" . date('Y-m-d H:i:s') . "')");
		$return = $otherdb->get()->result_array();

		return $return;
	}

	public function getMainBanner($user)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_main_banner');
		$otherdb->where('activo', 1);
		$return = $otherdb->get()->result_array();

		return $return;
	}

	public function getMascotas($user)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_mascotas');
		$otherdb->where('ed_clientes_id', $user);
		$return = $otherdb->get()->result_array();

		return $return;
	}

	public function getNearby($lat, $long)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		//$otherdb->select('*, (ACOS(COS(RADIANS(' . $lat . ')) * COS(RADIANS(latitud)) * COS(RADIANS(longitud) - RADIANS(' . $long . ')) + SIN(RADIANS(' . $lat . ')) * SIN(RADIANS(latitud)))) / 0.000156961230576 AS distance FROM ed_negocios WHERE mapa = 1 HAVING distance <= 1000');
		$otherdb->select('*, (ACOS(COS(RADIANS(' . $lat . ')) * COS(RADIANS(latitud)) * COS(RADIANS(longitud) - RADIANS(' . $long . ')) + SIN(RADIANS(' . $lat . ')) * SIN(RADIANS(latitud)))) / 0.000156961230576 AS distance FROM ed_negocios WHERE mapa = 1');
		$return = $otherdb->get()->result_array();

		$array = array();
		foreach ($return as $value) {

			$otherdb->select('*');
			$otherdb->from('ed_negocios_tipos');
			$otherdb->where('id', $value['tipo']);

			$return2 = $otherdb->get()->result_array();

			if (isset($return2[0]['imagen'])) {
				$value['icono'] =  'http://easydog.pet/admin/web/uploads/' . $return2[0]['imagen'];
			} else {
				$value['icono'] =  'http://easydog.pet/admin/web/uploads/MERCADO_1544989361.png';
			}


			if (isset($value['id'])) {
				$otherdb->select('*');
				$otherdb->from('ed_promos');
				$otherdb->like('ed_negocios_id', $value['id']);
				$promos = $otherdb->get()->result_array();
			} else {
				$promos = array();
			}

			$value['promos'] = $promos;


			$array[] = $value;
		}

		return $array;
	}

	public function getNearclients($lat, $long)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		//$otherdb->select('*, ed_mascotas.nombre AS mascota, ed_clientes.nombre AS nombre, (ACOS(COS(RADIANS('.$lat.')) * COS(RADIANS(ed_user_location.lat)) * COS(RADIANS(ed_user_location.longitud) - RADIANS('.$long.')) + SIN(RADIANS('.$lat.')) * SIN(RADIANS(ed_user_location.lat)))) AS distance FROM ed_user_location INNER JOIN ed_clientes ON ed_user_location.user_id=ed_clientes.id INNER JOIN ed_mascotas ON ed_user_location.user_id=ed_mascotas.ed_clientes_id HAVING distance <= 1000/6371.0');
		$otherdb->select('*, (ACOS(COS(RADIANS(' . $lat . ')) * COS(RADIANS(ed_user_location.lat)) * COS(RADIANS(ed_user_location.longitud) - RADIANS(' . $long . ')) + SIN(RADIANS(' . $lat . ')) * SIN(RADIANS(ed_user_location.lat)))) / 0.000156961230576 AS distance FROM ed_user_location INNER JOIN ed_clientes ON ed_user_location.user_id=ed_clientes.id');
		$return = $otherdb->get()->result_array();

		$returnArray = array();
		$x = 0;
		foreach ($return as $value) {
			unset($value['password_hash']);
			$otherdb->select('*');
			$otherdb->from('ed_mascotas');
			$otherdb->where('ed_clientes_id', $value['user_id']);
			$mascotas = $otherdb->get()->result_array();


			$otherdb->select('*');
			$otherdb->from('ed_cliente_image');
			$otherdb->where('ed_cliente_id', $value['user_id']);
			$photo = $otherdb->get()->result_array();

			if (count($photo) > 1) $photo = array_reverse($photo);
			if (isset($photo[0]['url'])) $photo = $photo[0]['url'];
			else $photo = 'http://easydog.pet/images/default-profile.png';
			$value['imagen'] = $photo;

			$returnArray[$x]['usuario'] = $value;

			foreach ($mascotas as $value2) {
				$otherdb->select('*');
				$otherdb->from('ed_razas');
				$otherdb->where('id', $value2['raza']);
				$raza = $otherdb->get()->result_array();

				if ($raza) {
					$value2['raza'] = $raza[0]['nombre'];
					//$value2['raza_icon'] = 'http://easydog.pet/admin/web/uploads/'.$raza[0]['image'];
				}

				$otherdb->select('url');
				$otherdb->from('ed_perrito_image');
				$otherdb->where('ed_mascotas_id', $value2['id']);
				$otherdb->order_by("id", "desc");
				$otherdb->limit(5);
				$fotos = $otherdb->get()->result_array();
				if ($fotos) $value2['raza_icon'] =  $fotos[0]['url'];
				else $value2['raza_icon'] = 'http://easydog.pet/api/uploads/no-image.png';


				$returnArray[$x]['mascotas'][] = $value2;
			}
			$x++;
		}

		return $returnArray;
	}

	public function getSearch($lat, $lng, $search, $type, $zone)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		//error_log("tellega ".$lat ." ". $lng ." ". $search ." ". $type ." ". $zone);
		if (strlen($search) >= 3 && !empty($type) && !empty($zone)) {
			$otherdb->select('tl_negocios.id, tl_negocios.name, tl_negocios.description, tl_negocios.image, tl_negocios.phone, tl_negocios.email, tl_negocios.address, tl_categorias_negocios.name AS categorias_negocios, tl_negocios.tl_tipos_pagos AS formas_pago,
			tl_negocios.deliver_time, tl_negocios.deliver_cost,
			ROUND((ACOS(COS(RADIANS(\'' . $lat . '\')) * COS(RADIANS(tl_negocios.latitude)) * COS(RADIANS(tl_negocios.longitude) - RADIANS(\'' . $lng . '\')) + SIN(RADIANS(\'' . $lat . '\')) * SIN(RADIANS(tl_negocios.latitude)))) / 0.000156961230576, 2) AS distance
			FROM tl_negocios
			INNER JOIN tl_categorias_negocios ON tl_negocios.tl_categorias_negocios_id = tl_categorias_negocios.id
			WHERE tl_negocios.status = 1
			AND tl_negocios.name LIKE \'%' . $search . '%\'
			AND tl_negocios.tl_categorias_negocios_id = \'' . $type . '\' ');
			//HAVING distance <= 1000');
			$negocios = $otherdb->get()->result_array();

			if (count($negocios) > 0) {
				$x = 0;
				foreach ($negocios as $value) {
					$otherdb->select('tl_productos.id, tl_productos.name, image, description, price, tl_categorias_productos_id AS categoria_id, tl_categorias_productos.name AS categoria');
					$otherdb->from('tl_productos');
					$otherdb->join('tl_categorias_productos', 'tl_productos.tl_categorias_productos_id = tl_categorias_productos.id');
					$otherdb->where('status', 1);
					$otherdb->where('tl_negocios_id', $value['id']);
					$products = $otherdb->get()->result_array();

					foreach ($products as $product) {
						$negocios[$x]['products'][$product['categoria']][] = $product;
					}

					$formas_pago = explode(',', $value['formas_pago']);
					$otherdb->select('id, name');
					$otherdb->from('tl_tipos_pago');
					$otherdb->where_in('id', $formas_pago);
					$pagos = $otherdb->get()->result_array();
					$negocios[$x]['formas_pago'] = $pagos;

					$x++;
				}
			}
		} else if (strlen($search) >= 3 && !empty($zone)) {
			$otherdb->select('tl_negocios.id, tl_negocios.name, tl_negocios.description, tl_negocios.image, tl_negocios.phone, tl_negocios.email, tl_negocios.address, tl_categorias_negocios.name AS categorias_negocios, tl_negocios.tl_tipos_pagos AS formas_pago,
			tl_negocios.deliver_time, tl_negocios.deliver_cost,
			ROUND((ACOS(COS(RADIANS(\'' . $lat . '\')) * COS(RADIANS(tl_negocios.latitude)) * COS(RADIANS(tl_negocios.longitude) - RADIANS(\'' . $lng . '\')) + SIN(RADIANS(\'' . $lat . '\')) * SIN(RADIANS(tl_negocios.latitude)))) / 0.000156961230576, 2) AS distance
			FROM tl_negocios
			INNER JOIN tl_categorias_negocios ON tl_negocios.tl_categorias_negocios_id = tl_categorias_negocios.id
			WHERE tl_negocios.status = 1
			AND tl_negocios.name LIKE \'%' . $search . '%\'');
			$negocios = $otherdb->get()->result_array();

			if (count($negocios) > 0) {
				$x = 0;
				foreach ($negocios as $value) {
					$otherdb->select('tl_productos.id, tl_productos.name, image, description, price, tl_categorias_productos_id AS categoria_id, tl_categorias_productos.name AS categoria');
					$otherdb->from('tl_productos');
					$otherdb->join('tl_categorias_productos', 'tl_productos.tl_categorias_productos_id = tl_categorias_productos.id');
					$otherdb->where('status', 1);
					$otherdb->where('tl_negocios_id', $value['id']);
					$products = $otherdb->get()->result_array();

					foreach ($products as $product) {
						$negocios[$x]['products'][$product['categoria']][] = $product;
					}

					$formas_pago = explode(',', $value['formas_pago']);
					$otherdb->select('id, name');
					$otherdb->from('tl_tipos_pago');
					$otherdb->where_in('id', $formas_pago);
					$pagos = $otherdb->get()->result_array();
					$negocios[$x]['formas_pago'] = $pagos;

					$x++;
				}
			}
		} else if (!empty($type) && !empty($zone)) {
			$otherdb->select('tl_negocios.id, tl_negocios.name, tl_negocios.description, tl_negocios.image, tl_negocios.phone, tl_negocios.email, tl_negocios.address, tl_categorias_negocios.name AS categorias_negocios, tl_negocios.tl_tipos_pagos AS formas_pago,
			tl_negocios.deliver_time, tl_negocios.deliver_cost,
			ROUND((ACOS(COS(RADIANS(\'' . $lat . '\')) * COS(RADIANS(tl_negocios.latitude)) * COS(RADIANS(tl_negocios.longitude) - RADIANS(\'' . $lng . '\')) + SIN(RADIANS(\'' . $lat . '\')) * SIN(RADIANS(tl_negocios.latitude)))) / 0.000156961230576, 2) AS distance
			FROM tl_negocios
			INNER JOIN tl_categorias_negocios ON tl_negocios.tl_categorias_negocios_id = tl_categorias_negocios.id
			WHERE tl_negocios.status = 1
			AND tl_negocios.tl_categorias_negocios_id = \'' . $type . '\'');

			error_log('tl_negocios.id, tl_negocios.name, tl_negocios.description, tl_negocios.image, tl_negocios.phone, tl_negocios.email, tl_negocios.address, tl_categorias_negocios.name AS categorias_negocios, tl_negocios.tl_tipos_pagos AS formas_pago,
			tl_negocios.deliver_time, tl_negocios.deliver_cost,
			ROUND((ACOS(COS(RADIANS(\'' . $lat . '\')) * COS(RADIANS(tl_negocios.latitude)) * COS(RADIANS(tl_negocios.longitude) - RADIANS(\'' . $lng . '\')) + SIN(RADIANS(\'' . $lat . '\')) * SIN(RADIANS(tl_negocios.latitude)))) / 0.000156961230576, 2) AS distance
			FROM tl_negocios
			INNER JOIN tl_categorias_negocios ON tl_negocios.tl_categorias_negocios_id = tl_categorias_negocios.id
			WHERE tl_negocios.status = 1
			AND tl_negocios.tl_categorias_negocios_id = \'' . $type . '\'');
			$negocios = $otherdb->get()->result_array();

			if (count($negocios) > 0) {
				$x = 0;
				foreach ($negocios as $value) {
					$otherdb->select('tl_productos.id, tl_productos.name, image, description, price, tl_categorias_productos_id AS categoria_id, tl_categorias_productos.name AS categoria');
					$otherdb->from('tl_productos');
					$otherdb->join('tl_categorias_productos', 'tl_productos.tl_categorias_productos_id = tl_categorias_productos.id');
					$otherdb->where('tl_productos.status', 1);
					$otherdb->where('tl_negocios_id', $value['id']);
					$products = $otherdb->get()->result_array();
					
					foreach ($products as $product) {
						$negocios[$x]['products'][$product['categoria']][] = $product;
					}

					$formas_pago = explode(',', $value['formas_pago']);
					$otherdb->select('id, name');
					$otherdb->from('tl_tipos_pago');
					$otherdb->where_in('id', $formas_pago);
					$pagos = $otherdb->get()->result_array();
					$negocios[$x]['formas_pago'] = $pagos;

					$x++;
				}
			}
		} else {
			$otherdb->select('tl_negocios.id, tl_negocios.name, tl_negocios.description, tl_negocios.image, tl_negocios.phone, tl_negocios.email, tl_negocios.address, tl_categorias_negocios.name AS categorias_negocios, tl_negocios.tl_tipos_pagos AS formas_pago,
			tl_negocios.deliver_time, tl_negocios.deliver_cost,
			ROUND((ACOS(COS(RADIANS(\'' . $lat . '\')) * COS(RADIANS(tl_negocios.latitude)) * COS(RADIANS(tl_negocios.longitude) - RADIANS(\'' . $lng . '\')) + SIN(RADIANS(\'' . $lat . '\')) * SIN(RADIANS(tl_negocios.latitude)))) / 0.000156961230576, 2) AS distance
			FROM tl_negocios
			INNER JOIN tl_categorias_negocios ON tl_negocios.tl_categorias_negocios_id = tl_categorias_negocios.id
			WHERE tl_negocios.status = 1');
			$negocios = $otherdb->get()->result_array();

			if (count($negocios) > 0) {
				$x = 0;
				foreach ($negocios as $value) {
					$otherdb->select('tl_productos.id, tl_productos.name, image, description, price, tl_categorias_productos_id AS categoria_id, tl_categorias_productos.name AS categoria');
					$otherdb->from('tl_productos');
					$otherdb->join('tl_categorias_productos', 'tl_productos.tl_categorias_productos_id = tl_categorias_productos.id');
					$otherdb->where('tl_productos.status', 1);
					$otherdb->where('tl_negocios_id', $value['id']);
					$products = $otherdb->get()->result_array();

					foreach ($products as $product) {
						$negocios[$x]['products'][$product['categoria']][] = $product;
					}

					$formas_pago = explode(',', $value['formas_pago']);
					$otherdb->select('id, name');
					$otherdb->from('tl_tipos_pago');
					$otherdb->where_in('id', $formas_pago);
					$pagos = $otherdb->get()->result_array();
					$negocios[$x]['formas_pago'] = $pagos;

					$x++;
				}
			}
		}

		return $negocios;
	}


	public function getDatosBack()
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('tl_categorias_negocios.id, tl_categorias_negocios.name, color, icon, (SELECT COUNT(*) FROM tl_negocios WHERE tl_negocios.tl_categorias_negocios_id = tl_categorias_negocios.id AND tl_negocios.status = 1) AS negocios_qty');
		$otherdb->from('tl_categorias_negocios');

		$otherdb->join('tl_negocios', 'tl_categorias_negocios.id = tl_negocios.tl_categorias_negocios_id');
	//$otherdb->where('(SELECT COUNT(*) FROM tl_negocios WHERE tl_negocios.tl_categorias_negocios_id = tl_categorias_negocios.id AND tl_negocios.status = 1) >', '1');
		$otherdb->group_by('tl_categorias_negocios.name');
		$return = $otherdb->get()->result_array();

		$otherdb->select('id, name');
		$otherdb->from('tl_tipos_pago');
		$return3 = $otherdb->get()->result_array();

		$otherdb->select('id, nombre AS name');
		$otherdb->from('tl_zonas');
		$return4 = $otherdb->get()->result_array();

		$returnArray = array();

		$returnArray['categorias_negocios'] = $return;
		$returnArray['formas_pago'] = $return3;
		$returnArray['zonas'] = $return4;

		return $returnArray;
	}

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

	public function registerUser($nombre, $apellido, $email, $password, $fechaN, $telefono, $sexo, $nit, $address, $client)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$this->load->library('password');

		$hashed = $this->password->create_hash($password);
		$nombre2 = str_replace(' ', '', $nombre);
		$nombre2 = strtolower($nombre2);
		$data = array(

			'nombre' => $nombre,
			'apellido' => $apellido,
			'correo' => $email,
			'register_date' => date('Y-m-d H:i:s'),
			'fecha_nacimiento' => $fechaN,
			'telefono' => $telefono,
			'sexo' => $sexo,
			'nit' => $nit,
			'address' => $address,
			'status' => 0,
			'password_hash' => $hashed,
			'tl_clientes_id' => $client
		);
		$error = $otherdb->insert('ed_clientes', $data);
		$return = $otherdb->insert_id();
		/*
	$return = $otherdb->insert_id();
	$return = $otherdb->get_where('ed_clientes', array('id' => $return));

	$returnArray = array();
	$returnArray['error'] = $error;
	$returnArray['data'] = $return->row();
*/

		return $error;
	}

	public function registerMascota($post)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $post['token']);
		$return = $otherdb->get()->result_array();

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

			if (isset($post['nombre']) && isset($post['fecha_nacimiento']) && isset($post['genero'])) {

				$data = array(
					'nombre' => $post['nombre'],
					'fecha_nacimiento' => $post['fecha_nacimiento'],
					'genero' => $post['genero'],
					'ed_clientes_id' => $return[0]['user_id'],
				);
				$otherdb->insert('ed_mascotas', $data);
				$return = $otherdb->insert_id();
			} else $return = FALSE;
		} else $return = FALSE;

		return $return;
	}

	public function addFriend($post)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		if (isset($post['ed_cliente_id']) &&  isset($post['amigo'])) {

			$data = array(
				'ed_cliente_id' => $post['ed_cliente_id'],
				'fecha' => date('Y-m-d H:i:s'),
				'amigo' => $post['amigo'],
			);
			$error = $otherdb->insert('ed_mascotas_amigos', $data);
		} else $error = 0;

		return $error;
	}

	public function saveProfile($id, $url)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $id);
		$return = $otherdb->get()->result_array();

		if (isset($return[0]['user_id'])) {
			$data = array(
				'ed_cliente_id' => $return[0]['user_id'],
				'fecha' => date('Y-m-d H:i:s'),
				'url' => $url,
			);
			$error = $otherdb->insert('ed_cliente_image', $data);

			return $error;
		} else {
			return FALSE;
		}

		/*	if( isset($config['upload_data']['file_name']) && isset($post['ed_cliente_id'] )) {

		 $data = array(
			 'ed_cliente_id' => $post['ed_cliente_id'],
			 'fecha' => date('Y-m-d H:i:s'),
			 'url' => 'http://easydog.pet/api/uploads/' . $config['upload_data']['file_name'],
		 );
		$error = $otherdb->insert('ed_cliente_image', $data);

		$data = array(
			'imagen' => $config['upload_data']['file_name'],
		);
		$otherdb->where('id', $post['ed_cliente_id']);
	 	$error = $otherdb->update('ed_clientes', $data);

	} else $error = 0;

		return $error;*/
	}

	public function savePerropic($id, $url)
	{

		$otherdb = $this->load->database('patsy', TRUE);
		$data = array(
			'ed_mascotas_id' => $id,
			'fecha' => date('Y-m-d H:i:s'),
			'url' => $url,
		);
		$error = $otherdb->insert('ed_perrito_image', $data);

		return $error;

		/*	if( isset($config['upload_data']['file_name']) && isset($post['ed_mascotas_id'] )) {

		 $data = array(
			 'ed_mascotas_id' => $post['ed_mascotas_id'],
			 'fecha' => date('Y-m-d H:i:s'),
			 'url' => 'http://easydog.pet/api/uploads/' . $config['upload_data']['file_name'],
		 );
		$error = $otherdb->insert('ed_perrito_image', $data);

		} else $error = 0;

		return $error;*/
	}


	public function getWallet($id)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $id);
		$return = $otherdb->get()->result_array();

		if (isset($return[0]['user_id'])) {
			$id = $return[0]['user_id'];
			$otherdb->select('*');
			$otherdb->from('ed_wallet');
			$otherdb->where('ed_clientes_id', $id);
			$wallet = $otherdb->get()->result_array();

			if ($wallet) {
				$returnArray = array();

				foreach ($wallet as $value) {

					if ($value['type'] == 1) {
						$otherdb->select('*');
						$otherdb->from('ed_eventos');
						$otherdb->where('id', $value['id_content']);
						$return2 = $otherdb->get()->result_array();

						$returnArray['eventos'][] = $return2;
					} else if ($value['type'] == 2) {
						$otherdb->select('ed_promos.tipo, ed_promos.descuento, ed_promos.inicio, ed_promos.final, ed_promos.ubicacion, ed_promos.descripcion, ed_promos.imagen, ed_negocios.registro as negocio');
						$otherdb->from('ed_promos');
						$otherdb->join('ed_negocios', 'ed_promos.ed_negocios_id = ed_negocios.id');
						$otherdb->where('ed_promos.id', $value['id_content']);
						$return2 = $otherdb->get()->result_array();

						$returnArray['promos'][] = $return2;
					}
					// code...
				}

				return $returnArray;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public function putWallet($cleanPost)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('ed_tokens');
		$otherdb->where('token', $cleanPost['token']);
		$return = $otherdb->get()->result_array();

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

			$data2 = array(
				'type' => $cleanPost['type'],
				'id_content' => $cleanPost['id_content'],
				'fecha' => date("Y-m-d H:i:s"),
				'ed_clientes_id' => $return[0]['user_id'],
			);
			$otherdb->insert('ed_wallet', $data2);
			$return = $otherdb->insert_id();
			return TRUE;
		} else return $cleanPost;
	}


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

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

	public function editUser($id, $nombre, $apellido, $email, $password, $fechaN, $sex, $phone)
	{

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

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

			$id = $return[0]['user_id'];

			$otherdb->select('*');
			$otherdb->from('ed_clientes');
			$otherdb->where('id', $id);
			$user = $otherdb->get()->result_array();

			/*	$id = $cleanPost['token'];
			$username = $cleanPost['username'];
			$nombre = $cleanPost['nombre'];
			$apellido = $cleanPost['apellido'];
			$email = $cleanPost['email'];
			$password = $cleanPost['password'];
			$fechaN = $cleanPost['fecha_nacimiento'];*/

			$error['complete'] = 1;

			/*	if( !empty($email) && $user != $user[0]['correo'] ) {
				$otherdb->get_where('ed_clientes', array('correo' => $email), 1);
				$test = $otherdb->affected_rows() > 0 ? TRUE : FALSE;
				if(!$test){
					//$username == $user[0]['username'];
					$data = array(
						'correo' => $email,
					);
					$otherdb->where('id', $id);
			 		$otherdb->update('ed_clientes', $data);
					$error[] = 'Usuario';
					$error['complete'] = 0;
				}
			}*/

			if (!empty($email) && $email != $user[0]['correo']) {
				$otherdb->get_where('ed_clientes', array('correo' => $email), 1);
				$test = $otherdb->affected_rows() > 0 ? TRUE : FALSE;
				if (!$test) {
					//$username == $user[0]['username'];
					$data = array(
						'correo' => $email,
					);
					$otherdb->where('id', $id);
					$otherdb->update('ed_clientes', $data);
					$error['Email'] = 1;
					$error['complete'] = 0;
				}
			}

			if (!empty($nombre) && $nombre != $user[0]['nombre']) {
				$data = array(
					'nombre' => $nombre,
				);
				$otherdb->where('id', $id);
				$otherdb->update('ed_clientes', $data);
				$error['Nombre'] = 1;
				$error['complete'] = 0;
			}

			if (!empty($apellido) && $apellido != $user[0]['apellido']) {
				$data = array(
					'apellido' => $apellido,
				);
				$otherdb->where('id', $id);
				$otherdb->update('ed_clientes', $data);
				$error['Apellido'] = 1;
				$error['complete'] = 0;
			}

			if (!empty($fechaN) && $fechaN != $user[0]['fecha_nacimiento']) {
				$data = array(
					'fecha_nacimiento' => $fechaN,
				);
				$otherdb->where('id', $id);
				$otherdb->update('ed_clientes', $data);
				$error['Fecha'] = 1;
				$error['complete'] = 0;
			}

			if ($sex != $user[0]['sexo']) {
				$data = array(
					'sexo' => $sex,
				);
				$otherdb->where('id', $id);
				$otherdb->update('ed_clientes', $data);
				$error['Sexo'] = 1;
				$error['complete'] = 0;
			}

			if (!empty($phone) && $phone != $user[0]['telefono']) {
				$data = array(
					'telefono' => $phone,
				);
				$otherdb->where('id', $id);
				$otherdb->update('ed_clientes', $data);
				$error['Telefono'] = 1;
				$error['complete'] = 0;
			}

			if (!empty($password) && $password >= 6) {
				$this->load->library('password');
				$hashed = $this->password->create_hash($password);
				$data = array(
					'password_hash' => $hashed
				);
				$otherdb->where('id', $id);
				$otherdb->update('ed_clientes', $data);
				$error['Password'] = 1;
				$error['complete'] = 0;
			}
		} else {
			$error = FALSE;
		}

		return $error;
	}

	public function getNegocio($id)
	{
		//$q = $otherdb->get_where('ed_negocios', array('id' => $id), 1);
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*, ed_negocios.id as id, ed_negocios.imagen as imagen, ed_negocios_tipos.nombre as tipo');
		$otherdb->from('ed_negocios');
		$otherdb->join('ed_negocios_tipos', 'ed_negocios.tipo = ed_negocios_tipos.id');
		$otherdb->where('ed_negocios.id', $id);
		$negocio = $otherdb->get()->result_array();

		if ($negocio) {
			$otherdb->select('*');
			$otherdb->from('ed_promos');
			$otherdb->like('ed_negocios_id', $id);
			$promos = $otherdb->get()->result_array();
		} else {
			$promos = array();
		}

		$negoci = array();

		$negoci['negocio'] = $negocio;
		$negoci['promos'] = $promos;
		return $negoci;
	}
}
