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


class Md_cava2 extends CI_Model {

	public function putData( $data, $token )
	{

		$test = strlen($token);

		if($test>=24) {

		$id = substr($token, 24, 11);

		$otherdb = $this->load->database('cava2', TRUE);
		$otherdb->select('*');
		$otherdb->from('colaboradores');
		$otherdb->where('id', $id);
		$otherdb->where('status', 0);
		$usuario = $otherdb->get()->result_array();

		$return = array();
		$return['code'] = 0;

		if(isset($usuario[0])) {

			$return['code'] = 1;
	
		} else {
			$return['code'] = 2;
		}
		
		} else {
			$return['code'] = 3;
		}
		
		//error_log($data);

		//$actual = file_get_contents("/var/www/html/webhook/cava.txt");
		// Escribe el contenido al fichero

		$myfile = fopen("/var/www/html/webhook/cava2.txt", "a") or die("Unable to open file!");
		/*$txt = "TEST\n";
		fwrite($myfile, $txt);*/
		//$txt = $myfile."\n";
		fwrite($myfile, $data."\n");
		fclose($myfile);
		include('/var/www/html/webhook/cava2.php');

		//file_put_contents("/var/www/html/webhook/cava.txt", $data);
		return $return;

	}
	public function getLogin( $username, $password )
	{
		$otherdb = $this->load->database('cava2', TRUE);
		$otherdb->select('*');
		$otherdb->from('colaboradores');
		$otherdb->where('username', $username);
		$otherdb->where('status', 0);
		$usuario = $otherdb->get()->result_array();

		$return = array();
		$return['code'] = 0;
		$return['data'] = array();

		if(isset($usuario[0])) {

			$test = password_verify( $password, $usuario[0]['password']);

			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('*');
			$otherdb->from('clients');
			$otherdb->where('status', 1);
			$otherdb->where('colaborador_id', $usuario[0]['id']);
			$clients = $otherdb->get()->result_array();
			
			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('inventory.id, inventory.name, inventory.barcode, inventory.price, 
			inventory.dateCreated, inventory.dateUpdated, inventory.status, inventory.bodegasId, inventory.quantity AS quantity, inventory.category_id AS category, category.imei AS usaImei');
			$otherdb->from('inventory');
			$otherdb->join('category', 'inventory.category_id = category.id');
			$otherdb->where('bodegasId', $usuario[0]['id']);
			$inventory = $otherdb->get()->result_array();
			
			$inventario = array();

			foreach ($inventory as $key => $value) {
				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('rangoA AS min, rangoB AS max, precio AS price, type AS paymentMethod, comision');
				$otherdb->from('comisiones');
				$otherdb->join('inventory', 'comisiones.inventory_id = inventory.category_id');
				$otherdb->where('inventory.barcode', $value['barcode']);
				$otherdb->where('inventory.bodegasId', 1);
				$priceRange = $otherdb->get()->result_array();


				$query = $otherdb->last_query();

//				error_log($query);

				$otherdb->select('*');
				$otherdb->from('inventory');
				$otherdb->where('bodegasId', 1);
				$otherdb->where('barcode', $value['barcode']);
				$otherdb->limit(1);
				$testIn = $otherdb->get()->result_array();
				$imeis = array();
				if(isset($testIn[0]['id'])){
					$otherdb->select('imei');
					$otherdb->from('imei');
					$otherdb->where('bodegas_id', $usuario[0]['id']);
					$otherdb->where('inventory_id', $testIn[0]['id']);
					$otherdb->where('invoice_id IS NULL');
	
					$imeistest = $otherdb->get()->result_array();

					foreach ($imeistest as $valueimei) {
						$imeis[] = $valueimei['imei'];
					}
				}



				$inventario[$key] = $value;
				$inventario[$key]['priceRange'] = $priceRange;
				$inventario[$key]['imeis'] = $imeis;
			}

			/*$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('inventory.id, inventory.name, inventory.barcode, inventory.price, inventory.quantity, 
			inventory.dateCreated, inventory.dateUpdated, inventory.status, inventory.bodegasId, count(inventory.id) AS quantity');
			$otherdb->from('inventory');
			$otherdb->join('imei', 'inventory.id = imei.inventory_id');
			$otherdb->where('imei.imei IS NOT NULL');
			$otherdb->where('imei.bodegas_id IS NULL');
			$otherdb->where('inventory.bodegasId', 1);
			$otherdb->where('inventory.status', 1);
			$otherdb->group_by('inventory.id'); 
			$bodega = $otherdb->get()->result_array();*/


			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('inventory.id, inventory.name, inventory.barcode, inventory.price, inventory.quantity, 
			inventory.dateCreated, inventory.dateUpdated, inventory.status, inventory.bodegasId, inventory.quantity AS quantity, inventory.category_id AS category');
			$otherdb->from('inventory');
			$otherdb->where('inventory.bodegasId', 1);
			$otherdb->where('inventory.status', 1);
			$otherdb->group_by('inventory.id'); 
			$bodega = $otherdb->get()->result_array();

			/*print_r($otherdb->last_query());    
				exit;*/

			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('*');
			$otherdb->from('invoices');
			$otherdb->where('colaboradores_id', $usuario[0]['id']);
			$otherdb->order_by('id', 'DESC');
			$facturas = $otherdb->get()->result_array();

			$invoices = array();

			foreach ($facturas as $key => $value) {

				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('*');
				$otherdb->from('clients');
				$otherdb->where('id', $value['guidClient']);
				$client = $otherdb->get()->result_array();

				$invoices[$key]['id'] = $value['id'];
				$invoices[$key]['type'] = ($value['invoiceType'] == '1') ? 'fcf' : 'ccf';
				if($client) {
					$invoices[$key]['client']['id'] = $value['guidClient'];
					$invoices[$key]['client']['identifier'] = $client[0]['identifier'];
					$invoices[$key]['client']['name'] = $value['name'];
					$invoices[$key]['client']['phone'] = $client[0]['phone'];
					$invoices[$key]['client']['contact'] = $value['contact'];
					$invoices[$key]['client']['address'] = $value['address'];
					$invoices[$key]['client']['city'] = $value['city'];
					$invoices[$key]['client']['state'] = $value['state'];
					$invoices[$key]['client']['email'] = $value['email'];
					$invoices[$key]['client']['creditLimit'] = $client[0]['creditLimit'];
					$invoices[$key]['client']['dateCreated'] = $client[0]['dateCreated'];
					$invoices[$key]['client']['dateUpdated'] = $client[0]['dateUpdated'];
					$invoices[$key]['client']['status'] = $client[0]['status'];
				} else {
					$invoices[$key]['client'] = array();
				}

				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('*');
				$otherdb->from('items');
				$otherdb->where('invoicesId', $value['id']);
				$products = $otherdb->get()->result_array();

				if($products) {

					foreach ($products as $product) {
						$invoices[$key]['products'][] = $product;
					}

				} else {
					$invoices[$key]['products'] = array();
				}

				//$invoices[$key]['discounts'][] = array('net' => '5', 'percentage' => "12", "comment" => "Nada aún");
				$invoices[$key]['dateCreated'] = $value['dateCreated'];
				$invoices[$key]['code'] = $value['uid'];
				# code...
			}

			//2 es ccf 1 fcf

			$returns = array();

			/*            id: "8D2E2593-EF5B-4604-9AF9-40E371DC7254",
            //colaboradoresId: 22, //este será el ID único de el usuario del app sólo para uso en envío al API
            invoicesId: 55,
            barcode: 5456148149,
            oldSerialNumber: "5456148149",
            newSerialNumber: "5456148149",
            dateCreated: "2020-09-01 10:20:43"*/
			
			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('*');
			$otherdb->from('returns');
			$otherdb->where('userId', $usuario[0]['id']);
			$returns = $otherdb->get()->result_array();

			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('*,  requests.status AS status,  requests.id AS id, requests.quantity AS quantity');
			$otherdb->from('requests');
			$otherdb->join('inventory', 'inventory.id = requests.guidItem');
			$otherdb->where('guidClient', $usuario[0]['id']);
			$requests = $otherdb->get()->result_array();

			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('rangoA AS min, rangoB AS max, precio AS price, type AS paymentMethod, inventory_id AS category, comision');
			$otherdb->from('comisiones');
			$priceRanges = $otherdb->get()->result_array();

			if($test) {
				unset($usuario[0]['password']);
				$usuario[0]['token'] = 'g87q4TuEvQvTS49tR5fekuWJ'.$usuario[0]['id'];
				$return['code'] = 1;
				$return['data']['version'] = 2; 
				$return['data']['user'] = $usuario; 
				$return['data']['clients'] = $clients; 
				$return['data']['inventory'] = $inventario; 
				$return['data']['bodega'] = $bodega; 
				$return['data']['requests'] = $requests; 
				$return['data']['returns'] = $returns; 
				$return['data']['invoices'] = $invoices; 
				$return['data']['pricerange'] = $priceRanges; 
				$return['data']['html'] = '<div style="margin: 20px;">Aquí podrás ver tus comisiones e información importante</div>'; 
			} else {
				$return['code'] = 2;
			}
		} 
		
		return $return;
	}

	public function getdata( $token )
	{

		$test = strlen($token);

		if($test>=24) {

			$id = substr($token, 24, 11);
			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('*');
			$otherdb->from('colaboradores');
			$otherdb->where('id', $id);
			$otherdb->where('status', 0);
			$usuario = $otherdb->get()->result_array();
	
			$return = array();
			$return['code'] = 0;
			$return['data'] = array();
	
			if(isset($usuario[0])) {
	
				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('*');
				$otherdb->from('clients');
				$otherdb->where('status', 1);
				$otherdb->where('colaborador_id', $usuario[0]['id']);
				$clients = $otherdb->get()->result_array();

				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('*');
				$otherdb->from('invoices');
				$otherdb->where('colaboradores_id', $usuario[0]['id']);
				$otherdb->order_by('id', 'DESC');
				$facturas = $otherdb->get()->result_array();
	
				$invoices = array();
	
				foreach ($facturas as $key => $value) {

					$otherdb = $this->load->database('cava2', TRUE);
					$otherdb->select('*');
					$otherdb->from('clients');
					$otherdb->where('id', $value['guidClient']);
					$client = $otherdb->get()->result_array();
	
					$invoices[$key]['id'] = $value['id'];
					$invoices[$key]['type'] = ($value['invoiceType'] == '1') ? 'fcf' : 'ccf';
					if($client) {
						$invoices[$key]['client']['id'] = $value['guidClient'];
						$invoices[$key]['client']['identifier'] = $client[0]['identifier'];
						$invoices[$key]['client']['name'] = $value['name'];
						$invoices[$key]['client']['phone'] = $client[0]['phone'];
						$invoices[$key]['client']['contact'] = $value['contact'];
						$invoices[$key]['client']['address'] = $value['address'];
						$invoices[$key]['client']['city'] = $value['city'];
						$invoices[$key]['client']['state'] = $value['state'];
						$invoices[$key]['client']['email'] = $value['email'];
						$invoices[$key]['client']['creditLimit'] = $client[0]['creditLimit'];
						$invoices[$key]['client']['dateCreated'] = $client[0]['dateCreated'];
						$invoices[$key]['client']['dateUpdated'] = $client[0]['dateUpdated'];
						$invoices[$key]['client']['status'] = $client[0]['status'];
					} else {
						$invoices[$key]['client'] = array();
					}
	
					$otherdb = $this->load->database('cava2', TRUE);
					$otherdb->select('*');
					$otherdb->from('items');
					$otherdb->where('invoicesId', $value['id']);
					$products = $otherdb->get()->result_array();
	
					if($products) {
	
						foreach ($products as $product) {
							$invoices[$key]['products'][] = $product;
						}
	
					} else {
						$invoices[$key]['products'] = array();
					}
	
					//$invoices[$key]['discounts'][] = array('net' => '5', 'percentage' => "12", "comment" => "Nada aún");
					$invoices[$key]['dateCreated'] = $value['dateCreated'];
					$invoices[$key]['code'] = $value['uid'];
					# code...
				}
				
				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('inventory.id, inventory.name, inventory.barcode, inventory.price, 
				inventory.dateCreated, inventory.dateUpdated, inventory.status, inventory.bodegasId, inventory.quantity AS quantity, inventory.category_id AS category, category.imei AS usaImei');
				$otherdb->from('inventory');
				$otherdb->join('category', 'inventory.category_id = category.id');
				$otherdb->where('bodegasId', $usuario[0]['id']);
				$inventory = $otherdb->get()->result_array();

				$inventario = array();

				foreach ($inventory as $key => $value) {
					$otherdb = $this->load->database('cava2', TRUE);
					$otherdb->select('rangoA AS min, rangoB AS max, precio AS price, type AS paymentMethod, comision');
					$otherdb->from('comisiones');
					$otherdb->join('inventory', 'comisiones.inventory_id = inventory.category_id');
					$otherdb->where('inventory.barcode', $value['barcode']);
					$otherdb->where('inventory.bodegasId', 1);
					$priceRange = $otherdb->get()->result_array();

					$query = $otherdb->last_query();

				//	error_log($query);

					$otherdb->select('*');
					$otherdb->from('inventory');
					$otherdb->where('bodegasId', 1);
					$otherdb->where('barcode', $value['barcode']);
					$otherdb->limit(1);
					$testIn = $otherdb->get()->result_array();
					$imeis = array();
					if(isset($testIn[0]['id'])){
						$otherdb->select('imei');
						$otherdb->from('imei');
						$otherdb->where('bodegas_id', $usuario[0]['id']);
						$otherdb->where('inventory_id', $testIn[0]['id']);
						$otherdb->where('invoice_id IS NULL');
		
						$imeistest = $otherdb->get()->result_array();
	
						foreach ($imeistest as $valueimei) {
							$imeis[] = $valueimei['imei'];
						}
					}
	
	
	
					$inventario[$key] = $value;
					$inventario[$key]['priceRange'] = $priceRange;
					$inventario[$key]['imeis'] = $imeis;
				}

				/*$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('inventory.id, inventory.name, inventory.barcode, inventory.price, inventory.quantity, 
				inventory.dateCreated, inventory.dateUpdated, inventory.status, inventory.bodegasId, count(inventory.id) AS quantity');
				$otherdb->from('inventory');
				$otherdb->join('imei', 'inventory.id = imei.inventory_id');
				$otherdb->where('imei.imei IS NOT NULL');
				$otherdb->where('imei.bodegas_id IS NULL');
				$otherdb->where('inventory.bodegasId', 1);
				$otherdb->where('inventory.status', 1);
				$otherdb->group_by('inventory.id'); 
				$bodega = $otherdb->get()->result_array();*/

				
				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('inventory.id, inventory.name, inventory.barcode, inventory.price, 
				inventory.dateCreated, inventory.dateUpdated, inventory.status, inventory.bodegasId, inventory.quantity AS quantity, inventory.category_id AS category');
				$otherdb->from('inventory');
				$otherdb->where('inventory.bodegasId', 1);
				$otherdb->where('inventory.status', 1);
				$otherdb->group_by('inventory.id'); 
				$bodega = $otherdb->get()->result_array();

				/*print_r($otherdb->last_query());    
				exit;*/

				$returns = array();

				/*            id: "8D2E2593-EF5B-4604-9AF9-40E371DC7254",
				//colaboradoresId: 22, //este será el ID único de el usuario del app sólo para uso en envío al API
				invoicesId: 55,
				barcode: 5456148149,
				oldSerialNumber: "5456148149",
				newSerialNumber: "5456148149",
				dateCreated: "2020-09-01 10:20:43"*/
	
				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('*');
				$otherdb->from('returns');
				$otherdb->where('userId', $usuario[0]['id']);
				$returns = $otherdb->get()->result_array();


				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('*,  requests.status AS status,  requests.id AS id, requests.quantity AS quantity');
				$otherdb->from('requests');
				$otherdb->join('inventory', 'inventory.id = requests.guidItem');
				$otherdb->where('guidClient', $usuario[0]['id']);
				$requests = $otherdb->get()->result_array();
	
				$otherdb = $this->load->database('cava2', TRUE);
				$otherdb->select('rangoA AS min, rangoB AS max, precio AS price, type AS paymentMethod, inventory_id AS category, comision');
				$otherdb->from('comisiones');
				$priceRanges = $otherdb->get()->result_array();
			
					unset($usuario[0]['password']);
					$usuario[0]['token'] = 'g87q4TuEvQvTS49tR5fekuWJ'.$usuario[0]['id'];
					$return['code'] = 1;
					$return['data']['version'] = 2; 
					$return['data']['user'] = $usuario; 
					$return['data']['clients'] = $clients; 
					$return['data']['inventory'] = $inventario; 
					$return['data']['bodega'] = $bodega; 
					$return['data']['requests'] = $requests; 
					$return['data']['returns'] = $returns; 
					$return['data']['invoices'] = $invoices; 
					$return['data']['pricerange'] = $priceRanges; 
					$return['data']['html'] = '<div style="margin: 20px;">Aquí podrás ver tus comisiones e información importante</div>'; 
				
			} else {
				$return['code'] = 2;
			}
		} else {
			$return['code'] = 3;
		}

		
		return $return;
	}

	public function getVentaslog($first_date, $second_date, $status)
	{
		if($status) {
			$otherdb = $this->load->database('patsy', TRUE);
			$otherdb->select('tl_compras.id as id');
			$otherdb->select('tl_compras.nombre as nombre');
			$otherdb->select('tl_compras.ed_clientes_id as telefono');
			$otherdb->select('tl_compras.nit as nit');
			$otherdb->select('tl_compras.address as datos_compra');
			$otherdb->select('tl_direccion_compra.id_region');
			$otherdb->select('tl_direccion_compra.id_region_2');
			$otherdb->select('tl_direccion_compra.col_id');
			$otherdb->select('tl_direccion_compra.inv_bod_id');
			$otherdb->select('tl_direccion_compra.zona');
			$otherdb->select('tl_compras.status as status');
			$otherdb->select('tl_direccion_compra.id_region');
			$otherdb->select('tl_compras.information as informacion');
			$otherdb->select('tl_tipos_pago.name as tipo_pago');
			$otherdb->select('tl_compras.date_created as fecha');
			$otherdb->from('tl_compras');
			$otherdb->join('tl_direccion_compra', 'tl_direccion_compra.id = tl_compras.tl_negocios_id');
			$otherdb->join('tl_tipos_pago', 'tl_tipos_pago.id = tl_compras.tl_tipos_pago_id');
			$otherdb->where('tl_compras.status', $status);
			$otherdb->where('tl_compras.date_created >=', $first_date);
			$otherdb->where('tl_compras.date_created <=', $second_date);
			$otherdb->order_by('tl_compras.id', 'DESC');
			$compras = $otherdb->get()->result_array();
		} else {
			$otherdb = $this->load->database('patsy', TRUE);
			$otherdb->select('tl_compras.id as id');
			$otherdb->select('tl_compras.nombre as nombre');
			$otherdb->select('tl_compras.ed_clientes_id as telefono');
			$otherdb->select('tl_compras.nit as nit');
			$otherdb->select('tl_compras.address as datos_compra');
			$otherdb->select('tl_direccion_compra.id_region');
			$otherdb->select('tl_direccion_compra.id_region_2');
			$otherdb->select('tl_direccion_compra.col_id');
			$otherdb->select('tl_direccion_compra.inv_bod_id');
			$otherdb->select('tl_direccion_compra.zona');
			$otherdb->select('tl_compras.status as status');
			$otherdb->select('tl_direccion_compra.id_region');
			$otherdb->select('tl_compras.information as informacion');
			$otherdb->select('tl_tipos_pago.name as tipo_pago');
			$otherdb->select('tl_compras.date_created as fecha');
			$otherdb->from('tl_compras');
			$otherdb->join('tl_direccion_compra', 'tl_direccion_compra.id = tl_compras.tl_negocios_id');
			$otherdb->join('tl_tipos_pago', 'tl_tipos_pago.id = tl_compras.tl_tipos_pago_id');
			$otherdb->where('tl_compras.date_created >=', $first_date);
			$otherdb->where('tl_compras.date_created <=', $second_date);
			$otherdb->order_by('tl_compras.id', 'DESC');
			$compras = $otherdb->get()->result_array();
		}


		$return = array();

		foreach ($compras as $value) {

			if($value['zona'] == "") $value['zona'] = 0;
			
			$id = $value['id'];
			$products = $otherdb->query("SELECT tl_orders.id AS id,tl_productos.name AS producto, tl_orders.quantity AS cantidad, tl_productos.price AS precio, tl_productos.sku AS sku FROM tl_orders LEFT JOIN tl_productos ON tl_orders.tl_productos_id = tl_productos.id WHERE tl_orders.tl_compras_id = $id"); 
			$products = $products->result_array();

			
			$addoptions = array();

			foreach ($products as $value2) {
				$id2 = $value2['id'];
				$options = $otherdb->query("SELECT  tl_options.id AS id, tl_options.name AS opcion, tl_options.precio AS precio, tl_order_option.quantity AS cantidad, tl_options.codigo AS sku  FROM tl_order_option LEFT JOIN tl_options ON tl_order_option.tl_options_id = tl_options.id WHERE tl_order_option.tl_orders_id = $id2"); 
				$options = $options->result_array();

				if($value2['sku'] == "") $value2['sku'] = 0;
				$value2['opciones'] = $options;
				
				$addoptions[] = $value2;
			}

			$value['productos'] = $addoptions;

			$return[] = $value;
		}

		return $return;
	}

	
	public function getVenta($id)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('tl_compras.id as id');
		$otherdb->select('tl_compras.nombre as nombre');
		$otherdb->select('tl_compras.ed_clientes_id as telefono');
		$otherdb->select('tl_compras.nit as nit');
		$otherdb->select('tl_compras.status as status');
		$otherdb->select('tl_compras.address as datos_compra');
		$otherdb->select('tl_direccion_compra.id_region');
		$otherdb->select('tl_direccion_compra.id_region_2');
		$otherdb->select('tl_direccion_compra.col_id');
		$otherdb->select('tl_direccion_compra.inv_bod_id');
		$otherdb->select('tl_direccion_compra.zona');
		$otherdb->select('tl_direccion_compra.id_region');
		$otherdb->select('tl_compras.information as informacion');
		$otherdb->select('tl_tipos_pago.name as tipo_pago');
		$otherdb->select('tl_compras.date_created as fecha');
		$otherdb->from('tl_compras');
		$otherdb->join('tl_direccion_compra', 'tl_direccion_compra.id = tl_compras.tl_negocios_id');
		$otherdb->join('tl_tipos_pago', 'tl_tipos_pago.id = tl_compras.tl_tipos_pago_id');
		$otherdb->where('tl_compras.id', $id);
		$otherdb->order_by('tl_compras.id', 'DESC');
		$compras = $otherdb->get()->result_array();

		$return = array();

		foreach ($compras as $value) {

			if($value['zona'] == "") $value['zona'] = 0;
			
			$id = $value['id'];
			$products = $otherdb->query("SELECT tl_orders.id AS id,tl_productos.name AS producto, tl_orders.quantity AS cantidad, tl_productos.price AS precio, tl_productos.sku AS sku FROM tl_orders LEFT JOIN tl_productos ON tl_orders.tl_productos_id = tl_productos.id WHERE tl_orders.tl_compras_id = $id"); 
			$products = $products->result_array();

			$addoptions = array();

			foreach ($products as $value2) {
				$id2 = $value2['id'];
				$options = $otherdb->query("SELECT  tl_options.id AS id, tl_options.name AS opcion, tl_options.precio AS precio, tl_order_option.quantity AS cantidad, tl_options.codigo AS sku  FROM tl_order_option LEFT JOIN tl_options ON tl_order_option.tl_options_id = tl_options.id WHERE tl_order_option.tl_orders_id = $id2"); 
				$options = $options->result_array();

				if($value2['sku'] == "") $value2['sku'] = 0;
				$value2['opciones'] = $options;
				
				$addoptions[] = $value2;
			}

			$value['productos'] = $addoptions;

			$return[] = $value;
		}

		return $return;
	}

	public function deleteProduct($id, $product_id)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('tl_compras.id as id');
		$otherdb->select('tl_compras.ed_clientes_id as telefono');
		$otherdb->select('tl_compras.address as datos_compra');
		$otherdb->select('tl_compras.information as informacion');
		$otherdb->select('tl_tipos_pago.name as tipo_pago');
		$otherdb->select('tl_tipos_pago.date_created as fecha');
		$otherdb->from('tl_compras');
		$otherdb->join('tl_tipos_pago', 'tl_tipos_pago.id = tl_compras.tl_tipos_pago_id');
		$otherdb->where('tl_compras.id', $id);
		$otherdb->where('tl_compras.status', 1);
		$otherdb->order_by('tl_compras.id', 'DESC');
		$compras = $otherdb->get()->result_array();



		$return = FALSE;

		if(isset($compras[0])) {

			$otherdb->select('*');
			$otherdb->from('tl_orders');
			$otherdb->where('id', $product_id);

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

			if(isset($order[0])) {
				$otherdb->where('id', $order[0]['id']);
				$return = $otherdb->delete('tl_orders');
	
				$otherdb->where('tl_orders_id', $order[0]['id']);
				$otherdb->delete('tl_order_option');
			}
		}

		return $return;
	}

	public function changeStatus($id, $status)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('tl_compras');
		$otherdb->where('id', $id);
		$otherdb->order_by('id', 'DESC');
		$compras = $otherdb->get()->result_array();

		$return = FALSE;

		if(isset($compras[0])) {

			$compra = $compras[0]['id'];


			if(is_numeric($status) && $status <= 6) {
				$otherdb->set('status', $status, FALSE);
				$otherdb->where('id', $compra);
				$return = $otherdb->update('tl_compras');
			}

			if($status == 6) {

                $curl = curl_init();
		
                curl_setopt_array($curl, array(
                  CURLOPT_URL => "https://www.admin.visaenlink.com.gt/index.php/rest_movil/login",
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => "",
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => "POST",
                  CURLOPT_POSTFIELDS => "key=bbba722f948709955de06b9e2a7e703e3bc15996&usuario=LUIS_ZARATE&clave=visa2020",
                  CURLOPT_HTTPHEADER => array(
                    "Content-Type: application/x-www-form-urlencoded",
                    "Cookie: symfony=b399c42c5cb1d88a5441b94ffcdbcbef"
                  ),
                ));
                
                $response = curl_exec($curl);
                
                curl_close($curl);
                
                $token = json_decode($response);

                $precio = 0;
				
				$products = $otherdb->query("SELECT tl_orders.id AS id,tl_productos.name AS producto, tl_orders.quantity AS cantidad, tl_productos.price AS precio, tl_productos.sku AS sku FROM tl_orders LEFT JOIN tl_productos ON tl_orders.tl_productos_id = tl_productos.id WHERE tl_orders.tl_compras_id = $compra"); 
				$products = $products->result_array();
	
				$html = '';
				$precio = 0;
	
                if($products){
                    $html .= 'Tu pedido 📇:

';
				foreach ($products as $value2) {

					$html .= '*'.$value2['cantidad'].'* '.$value2['producto'].' *Q'.$value2['cantidad'] * $value2['precio'].'*
';

					$precio +=  ($value2['cantidad'] * $value2['precio']);

					$id2 = $value2['id'];
					$options = $otherdb->query("SELECT  tl_options.id AS id, tl_options.name AS opcion, tl_options.precio AS precio, tl_order_option.quantity AS cantidad, tl_options.codigo AS sku  FROM tl_order_option LEFT JOIN tl_options ON tl_order_option.tl_options_id = tl_options.id WHERE tl_order_option.tl_orders_id = $id2"); 
					$options = $options->result_array();

					foreach ($options as $value3) {
						$html .= '*'.$value3['cantidad'].'* '.$value3['opcion'].' *Q'.$value3['cantidad'] * $value3['precio'].'*
';
						$precio +=  ($value3['cantidad'] * $value3['precio']);
					}

				}
	
	

			}
                
                if(isset($token->token) && $compras[0]['tl_tipos_pago_id'] == 5 && $precio > 50) {
                     $token = $token->token;
                    $curl = curl_init();
                    
                    curl_setopt_array($curl, array(
                    CURLOPT_URL => "https://www.admin.visaenlink.com.gt/index.php/rest_movil/link",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => "key=bbba722f948709955de06b9e2a7e703e3bc15996&token=$token&codigo=$compra&nombre=".$compras[0]['nombre']."&cuota=0&nombre_interno=FogataCommerce&precio=$precio&redes=b336fc558722224b7ffe98607055d55f0fe52450",
                    CURLOPT_HTTPHEADER => array(
                        "Content-Type: application/x-www-form-urlencoded"
                    ),
                    ));
                    
                    $response = curl_exec($curl);
                   // error_log($response);
                    curl_close($curl);
					log_message('error', $response);

					$response = json_decode($response);
					
        //puede cambiar el tiempo, por lo visto no hay tiempo l[imite] cuando hace visalink .... MAY GOD
                    if(isset($response->link[0])) {
                        $link = $response->link[0];
						$html = $html.'
Utilice el siguiente Visalink para realizar el pago de su orden:
'.$link;         

                    }
                } else if($precio <= 50) {
					$html = "El mínimo para comprar con Tarjeta de crédito es Q50, por favor escriba *volver al menú* para realizar un nuevo pedido";    
				}

                if($html) {
                    $token = 'a13316d6a35849afffa8fbef4fd00ffd5c7545568340f';
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                    CURLOPT_URL => "https://www.waboxapp.com/api/send/chat",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => "token=" . $token . "&uid=50237606565&to=" . $compras[0]['ed_clientes_id'] . "&text=$html",
                    CURLOPT_HTTPHEADER => array(
                        "cache-control: no-cache",
                        "content-type: application/x-www-form-urlencoded",
                        "postman-token: c7e374a6-be4e-4b01-7e62-c5ddcd80ddae"
                    ),
                    ));
    
                    $response = curl_exec($curl);
                    $err = curl_error($curl);
    
                    curl_close($curl);
                }

            
				
			}

		}

		return $return;
	}

	public function snedMsg($id, $msg)
	{
		$otherdb = $this->load->database('patsy', TRUE);
		$otherdb->select('*');
		$otherdb->from('tl_compras');
		$otherdb->where('id', $id);
		$otherdb->order_by('id', 'DESC');
		$compras = $otherdb->get()->result_array();

		$return = FALSE;

		if(isset($compras[0])) {

			$curl = curl_init();
           
			$token = 'a13316d6a35849afffa8fbef4fd00ffd5c7545568340f';

			curl_setopt_array($curl, array(
			CURLOPT_URL => "https://www.waboxapp.com/api/send/chat",
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => "",
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 30,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => "POST",
			CURLOPT_POSTFIELDS => "token=" . $token . "&uid=50237606565&to=" . $compras[0]['ed_clientes_id'] . "&text=$msg",
			CURLOPT_HTTPHEADER => array(
				"cache-control: no-cache",
				"content-type: application/x-www-form-urlencoded",
				"postman-token: c7e374a6-be4e-4b01-7e62-c5ddcd80ddae"
			),
			));

			$response = curl_exec($curl);
			$err = curl_error($curl);

			curl_close($curl);

			$return = TRUE;

		}

		return $return;
	}

	public function fixdata($id)
	{

		if(!empty($id)) {
			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('invoicesId,COUNT(id) AS number,category');
			$otherdb->from('items');
			$otherdb->where('invoicesId', $id);
			$otherdb->group_by('category'); 
			$items = $otherdb->get()->result_array();
	
			$return = FALSE;
	
			if(isset($items[0])) {

				foreach ($items as $key => $value) {

					$comision = 0;

					$otherdb = $this->load->database('cava2', TRUE);
					$otherdb->select('paymentMethod');
					$otherdb->from('invoices');
					$otherdb->where('id', $id);
					$invoice = $otherdb->get()->result_array();

					$otherdb = $this->load->database('cava2', TRUE);
					$otherdb->select('rangoA AS min, rangoB AS max, comision');
					$otherdb->from('comisiones');
					$otherdb->where('inventory_id', $value['category']);
					$otherdb->where('type', $invoice[0]['paymentMethod']);
					$priceRange = $otherdb->get()->result_array();

					foreach ($priceRange as $key => $value2) {
						if($value['number'] >= $value2['rangoA'] && $value['number'] <= $value2['rangoB']) $comision = $value2['comision'];
					}

					$items[$key]['comision'] = $comision;

				}

				$return = $items;
			}
		} else {
			$otherdb = $this->load->database('cava2', TRUE);
			$otherdb->select('invoicesId,COUNT(id) AS number,category');
			$otherdb->from('items');
			$otherdb->where('discount2 IS NULL');
			$otherdb->group_by('category'); 
			$items = $otherdb->get()->result_array();

	
			$return = FALSE;
	
			if(isset($items[0])) {

				foreach ($items as $key => $value) {

					$comision = 0;

					$otherdb = $this->load->database('cava2', TRUE);
					$otherdb->select('paymentMethod');
					$otherdb->from('invoices');
					$otherdb->where('id', $id);
					$invoice = $otherdb->get()->result_array();

					$otherdb = $this->load->database('cava2', TRUE);
					$otherdb->select('rangoA AS min, rangoB AS max, comision');
					$otherdb->from('comisiones');
					$otherdb->where('inventory_id', $value['category']);
					$otherdb->where('type', $invoice[0]['paymentMethod']);
					$priceRange = $otherdb->get()->result_array();

					foreach ($priceRange as $key => $value2) {
						if($value['number'] >= $value2['rangoA'] && $value['number'] <= $value2['rangoB']) $comision = $value2['comision'];
					}

					$items[$key]['comision'] = $comision;

				}

				$return = $items;
			}
		}


		return $return;
	}


}
