<?php

defined('BASEPATH') or exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

/**
 * This is an example of a few basic user interaction methods you could use
 * all done with a hardcoded array
 *
 * @package         CodeIgniter
 * @subpackage      Rest Server
 * @category        Controller
 * @author          Hector Luna
 * @license         MIT
 * @link            https://github.com/chriskacerguis/codeigniter-restserver
 */
class Patsyapp extends REST_Controller
{

	function __construct()
	{
		header('Access-Control-Allow-Origin: *');
		header("Access-Control-Allow-Headers: Content-Type, Cache-Control");
		header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT");

		parent::__construct();
		$this->load->model('Md_patsyapp');
		$this->load->model('User_model', 'user_model', TRUE);
		$this->load->library('form_validation');
		$this->load->helper(array('form', 'url'));
	}

	public function live_put()
	{
		$lat = $this->put('lat');
		$long = $this->put('long');
		$user = $this->put('token');
		if (!empty($lat) && !empty($long) && !empty($user)) {
			$return = $this->Md_patsyapp->putPosition($user, $lat, $long);
		} else {
			$return = 0;
		}

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Data actualizada correctamente', 'data' => array()], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error al ingresar la data', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function live_get()
	{
		$user = $this->get('user');

		if (!empty($user)) {
			$return = $this->Md_patsyapp->getPosition($user);
		} else {
			$return = 0;
		}

		if (isset($return[0])) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Data del usuario', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'El usuario no existe', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function negocio_get()
	{
		$user = $this->get('id');

		if (!empty($user)) {
			$return = $this->Md_patsyapp->getNegocio($user);
		} else {
			$return = false;
		}

		if (isset($return['negocio'][0]['registro'])) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Data del negocio', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Negocio no exite', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function deletetdc_post()
	{
		$post = $this->post();

		$cleanPost = $this->security->xss_clean($post);

		if (isset($cleanPost['token']) && isset($cleanPost['tdc_id'])) {
			$return = $this->Md_patsyapp->deleteTdc($cleanPost);
		} else {
			$return = FALSE;
		}

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'TDC eliminada', 'data' => array()], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'El usuario no existe', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function wallet_post()
	{
		$post = $this->post();

		$cleanPost = $this->security->xss_clean($post);

		if (isset($cleanPost['token']) && isset($cleanPost['id_content']) && isset($cleanPost['type'])) {
			$return = $this->Md_patsyapp->putWallet($cleanPost);
		} else {
			$return = FALSE;
		}

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Guardado en el Wallet', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'El usuario no existe', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function wallet_get()
	{
		$user = $this->get('token');

		if (!empty($user)) {
			$return = $this->Md_patsyapp->getWallet($user);
		} else {
			$return = FALSE;
		}

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Data del usuario', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No hay nada que mostrar', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function nearby_get()
	{
		$lat = $this->get('lat');
		$long = $this->get('long');

		if (!empty($lat) && !empty($long)) {
			$return = $this->Md_patsyapp->getNearby($lat, $long);
		} else {
			$return = 0;
		}

		if (isset($return[0])) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Resultados de la búsqueda', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No hay resultados', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function search_get()
	{
		$lat = $this->get('lat');
		$lng = $this->get('lng');
		$search = $this->get('keyword');
		$type = $this->get('type');
		$zone = $this->get('zone');

		if ($lng == 'undefined' || $lat == 'undefined' || empty($lat) || empty($lng)) {
			$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No podemos activar el GPS en tu dispositivo', 'data' => array()], REST_Controller::HTTP_OK);
		} else if (!empty($lat) && !empty($lng)) {
			$return = $this->Md_patsyapp->getSearch($lat, $lng, $search, $type, $zone);

			if (isset($return[0])) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Resultados cerca de su zona', 'data' => $return], REST_Controller::HTTP_OK);
			} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Lo sentimos, no encontramos negocios que lleguen a su zona', 'data' => array()], REST_Controller::HTTP_OK);
		} else {
			$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No podemos activar el GPS en tu dispositivo', 'data' => array()], REST_Controller::HTTP_OK);
		}
	}

	public function staticinfo_get()
	{

		$return = $this->Md_patsyapp->getDatosBack();

		if (isset($return)) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Resultados de la búsqueda', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'No hay resultados', 'data' => array()], REST_Controller::HTTP_OK);
	}


	public function registerUser_put()
	{

		$post = $this->put();

		$cleanPost = $this->security->xss_clean($post);

		if(isset($cleanPost['nombre']))$nombre = $cleanPost['nombre'];
		else $nombre = "";
		if(isset($cleanPost['apellido']))$apellido = $cleanPost['apellido'];
		else $apellido = "";
		if(isset($cleanPost['email']))$email = $cleanPost['email'];
		else $email = "";
		if(isset($cleanPost['password']))$password = $cleanPost['password'];
		else $password = "";
		if(isset($cleanPost['telefono']))$telefono = $cleanPost['telefono'];
		else $telefono = "";
		if(isset($cleanPost['nit']))$nit = $cleanPost['nit'];
		else $nit = "";
		if(isset($cleanPost['address']))$address = $cleanPost['address'];
		else $address = "";
		if(isset($cleanPost['id_client']))$client = $cleanPost['id_client'];
		else $client = 0;

		error_log(json_encode($cleanPost));

		$fechaN = date('Y-m-d');
		$sexo = 1;

		if (!empty($nombre) && !empty($apellido) && !empty($email) && !empty($password) && !empty($telefono)) {

			if (strlen($password) >= 6) {

				if ($this->user_model->isDuplicate($email)) {
					$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'El email ya existe.', 'data' => array()], REST_Controller::HTTP_OK);
				} else {

					$return = $this->Md_patsyapp->registerUser($nombre, $apellido, $email, $password, $fechaN, $telefono, $sexo, $nit, $address, $client);
					if ($return) {
						$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Usuario registrado correctamente.', 'data' => array()], REST_Controller::HTTP_OK);
					} else {
						$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error, vuelva a intentarlo.', 'data' => array()], REST_Controller::HTTP_OK);
					}

					//	}
				}
			} else {
				$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'La contraseña debe tener al menos 6 dígitos.', 'data' => array()], REST_Controller::HTTP_OK);
			}
		} else {
			$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Datos incompletos.', 'data' => array()], REST_Controller::HTTP_OK);
		}
	}

	public function insertClient_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);

		if(isset($cleanPost['key']) && $cleanPost['key'] == "Alemar-20-Olimar*") {
			$return = $this->Md_patsyapp->insertClient($cleanPost);
		} else $return = FALSE;

		

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Nuevo cliente', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error al ingresar los datos', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function getClients_get()
	{
		$token = $this->get();

		if(isset($token['key']) && $token['key'] == "Alemar-20-Olimar*") {
			$return = $this->Md_patsyapp->getClients();
		} else $return = FALSE;


		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Key aceptada', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Key no existe', 'data' => $return], REST_Controller::HTTP_OK);
	}

	public function newToken_put()
	{
		$username = $this->put('email');

		$return = $this->user_model->insertToken($username);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Nuevo Token', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error al ingresar token', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function validToken_get()
	{
		$token = $this->get('token');

		$return = $this->user_model->isTokenValid($token);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Token aceptado', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Token no existe', 'data' => $return], REST_Controller::HTTP_OK);
	}

	public function notifications_get()
	{
		$token = $this->get('token');
		$return = $this->Md_patsyapp->getNotifications($token);

		if (isset($return[0])) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Notificaciones', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'No hay Notificaciones Nuevas', 'data' => $return], REST_Controller::HTTP_OK);
	}

	public function checkLogin_post()
	{
		$post = $this->post();

		$cleanPost = $this->security->xss_clean($post);

		$return = $this->user_model->checkLogin($cleanPost);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Acceso correcto', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Acceso denegado', 'data' => $return], REST_Controller::HTTP_OK);
	}

	public function checkLogin_get()
	{
		$user = $this->get('token');

		//$cleanPost = $this->security->xss_clean($post);

		$return = $this->user_model->userInfo($user);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Acceso correcto', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Acceso denegado', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function updatePassword_post()
	{
		$post = $this->post();

		$cleanPost = $this->security->xss_clean($post);

		$return = $this->Md_patsyapp->updatePassword($cleanPost);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Acceso correcto', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Acceso denegado', 'data' => $return], REST_Controller::HTTP_OK);
	}

	public function recoveryPassword_get()
	{
		$email = $this->get('email');

		// Remove all illegal characters from email
		$email = filter_var($email, FILTER_SANITIZE_EMAIL);

		$return = array();

		// Validate e-mail
		if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Se ha enviado un URL de recuperación de contraseña a su correo electrónico.', 'data' => $return], REST_Controller::HTTP_OK);
		} else {
			$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Debe enviar un correo electrónico válido', 'data' => $return], REST_Controller::HTTP_OK);
		}
	}

	public function updateUser_post()
	{

		$post = $this->post();

		$cleanPost = $this->security->xss_clean($post);

		if (isset($cleanPost['nombre'])) $nombre = $cleanPost['nombre'];
		else $nombre = '';
		if (isset($cleanPost['token'])) $id = $cleanPost['token'];
		else $id = '';
		if (isset($cleanPost['apellido'])) $apellido = $cleanPost['apellido'];
		else $apellido = '';
		if (isset($cleanPost['email'])) $email = $cleanPost['email'];
		else $email = '';
		if (isset($cleanPost['password'])) $password = $cleanPost['password'];
		else $password = '';
		if (isset($cleanPost['fecha_nacimiento'])) $fechaN = $cleanPost['fecha_nacimiento'];
		else $fechaN = '';
		if (isset($cleanPost['sexo'])) $sex = $cleanPost['sexo'];
		else $sex = '';
		if (isset($cleanPost['telefono'])) $phone = $cleanPost['telefono'];
		else $phone = '';


		$return = $this->Md_patsyapp->editUser($id, $nombre, $apellido, $email, $password, $fechaN, $sex, $phone);
		if ($return) {
			if ($return['complete'] == 1) {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Nada que actualizar', 'data' => $return], REST_Controller::HTTP_OK);
			} else {
				$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Usuario actualizado correctamente.', 'data' => $return], REST_Controller::HTTP_OK);
			}
		} else {
			$this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error, vuelva a intentarlo.', 'data' => $return], REST_Controller::HTTP_OK);
		}
	}

	public function newOrder_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);
		$return = $this->Md_patsyapp->insertOrder($cleanPost);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Orden procesada', 'data' => array('order' => $return)], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Error al ingresar orden', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function payment_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);
		$return = $this->Md_patsyapp->insertPayment($cleanPost);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Pago procesado', 'data' => array('order' => $return)], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Pago fallido', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function payment2_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);
		$return = $this->Md_patsyapp->insertPayment2($cleanPost);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Pago procesado', 'data' => array('order' => $return)], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Pago fallido', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function savetdc_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);
		$return = $this->Md_patsyapp->insertPayment3($cleanPost);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Tarjeta Guardada', 'data' => array('order' => $return)], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Faltan datos', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function likeprod_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);
		$return = $this->Md_patsyapp->insertLike($cleanPost);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Like agregado', 'data' => array('like' => $return)], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Like fallido', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function likeneg_post()
	{
		$post = $this->post();
		$cleanPost = $this->security->xss_clean($post);
		$return = $this->Md_patsyapp->insertLiken($cleanPost);

		if ($return) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Like agregado', 'data' => array('like' => $return)], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => FALSE, 'codigo' => 1, 'message' => 'Like fallido', 'data' => array()], REST_Controller::HTTP_OK);
	}

	public function orders_get()
	{
		$token = $this->get('token');
		$return = $this->Md_patsyapp->getOrders($token);

		if (isset($return[0])) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Pedidos', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'No hay pedidos', 'data' => $return], REST_Controller::HTTP_OK);
	}

	public function deliveries_get()
	{
		$token = $this->get('token');
		$return = $this->Md_patsyapp->getDelivery($token);


		/*$coord1 = rand(13982, 93982);
		$coord2 = rand(13982, 93982);
		$return = '[{
					"negocio": "CEMACO TJ07 JUGUETON PERO ZONA 7",
					"latNegocio": "14.620435",
					"lngNegocio": "-90.493982",
					"latRepartidor": "14.6'.$coord1.'",
					"lngRepartidor": "-90.4'.$coord2.'",
					"latEntrega": "14.625684",
					"lngEntrega": "-90.498955",
					"repartidorName": "Héctor Luna",
					"repartidorPhone": "50760816607",
					"status": "EN CAMINO",
					"statusId": "1",
					"date_updated": "2019-09-13 00:00:00"
				}]';

		$return = json_decode($return);*/

		if (isset($return[0])) {
			$this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'Pedidos', 'data' => $return], REST_Controller::HTTP_OK);
		} else $this->set_response(['status' => TRUE, 'codigo' => 0, 'message' => 'No hay pedidos', 'data' => $return], REST_Controller::HTTP_OK);
	}
}
