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


class Md_patsy extends CI_Model {

	public function putMessages( $data )
	{
	
		$sendjson = array();
		$sendEncode = "1";
		
		$data = json_decode( $data );
		$timer = true;
		if(isset($data->data->identifier) && isset($data->data->type) && strpos($data->data->identifier, "false") !== false) {

			$sendEncode = "2";
			
			$uid = $data->data->identifier;
			$testUid = $this->testMsg($uid);

			if($data->participants->group->isGroup) {
				$isGroup = TRUE;
				$from = $data->participants->group->identifier;
			} else {
				$isGroup = FALSE;
				$from = $data->participants->source->identifier;
				$from = str_replace('@s.whatsapp.net',"",$from);
				$from = str_replace('@c.us',"",$from);
				$from = str_replace('@lid',"",$from);
			}

			if($testUid && !$isGroup) {
				$sendEncode = "3";
				
				$chatId = FALSE;
				$ticket = FALSE;
				$url = "";
				$key = 0;
				$agent = 0;
				$clientID = 0;
				$botId = "";
				$cycle = 0;
				$botActiveUser = 1;
				$lastActive = FALSE;
				$webhookMsg = "";
				$msgType = $data->data->type;
				if(isset($data->data->body)) $word = $data->data->body;
				else $word =  "";
				$botAnswer = FALSE;
				$type = 0;
				
				$to = $data->participants->destination->identifier;
				$to = str_replace('@s.whatsapp.net',"",$to);
				$to = str_replace('@c.us',"",$to);
				$to = str_replace('@lid',"",$to);
		

		
				if(isset($data->participants->source->nickName)) {
					$name = $data->participants->source->nickName;
				} else {
					if(isset($data->participants->source->displayName)) {
						$name = $data->participants->source->displayName;
					} else {
						$name = $from;
					}
				}
				if(isset($data->participants->source->profilePictureUrl)) $avatar = $data->participants->source->profilePictureUrl;
				else $avatar = "";
				$timestamp = $data->data->timestamp;
				
				if($msgType == "chat") {
					$sendEncode = "4";
					$sendjson['product_id'] = "0bd60524-2b86-4cf6-a3e2-c5f9b78f58bf";
					$sendjson['phone_id'] = "11186";
					$sendjson['message']['type'] = "text";
					$sendjson['message']['text'] = $word;
					$sendjson['message']['id'] = $uid;
					$sendjson['message']['_serialized'] = $uid;
					$sendjson['message']['fromMe'] = false;
					$sendjson['user']['id'] = $from."@c.us";
					$sendjson['user']['name'] = $name;
					$sendjson['user']['phone'] = $from;
					$sendjson['user']['image'] = "https://fogatabot.com/img/small-logo.png";
					$sendjson['conversation'] = $from."@c.us";
					$sendjson['conversation_name'] = $name;
					$sendjson['receiver'] = $to;
					$sendjson['timestamp'] = $timestamp;
					$sendjson['type'] = "message";
					$sendjson['reply'] = "https://api.maytapi.com/api/0bd60524-2b86-4cf6-a3e2-c5f9b78f58bf/11186/sendMessage";
					$sendjson['productId'] = "0bd60524-2b86-4cf6-a3e2-c5f9b78f58bf";
					$sendjson['phoneId'] = "11186";
					$sendjson['ws'] = "1";

					$sendEncode = json_encode($sendjson);
					
					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => 'https://api.fogatabot.com/whatsapp/wapi.php',
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => '',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => true,
					CURLOPT_SSL_VERIFYPEER => false,
					CURLOPT_SSL_VERIFYHOST => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => 'POST',
					CURLOPT_POSTFIELDS =>$sendEncode,
					CURLOPT_HTTPHEADER => array(
						'Content-Type: application/json'
					),
					));
					$response = curl_exec($curl);
					curl_close($curl);
					$sendEncode = $response;
				}
			}

			return $sendEncode;
		} else {
			return $sendEncode;
		}
	}

	public function testJson( $data )
	{
		if(isset($data[0]) && isset($data[0]->status) && isset($data[0]->uid)) {

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

				if(strpos($value->uid, "false") !== false) {
					$testUid = $this->testMsg($value->uid);
					$data[$key]->status = $testUid;
				} else {
					$data[$key]->status = FALSE;
				}

			}
		}

		return $data;
	}

	public function testMsg($uid) {

		$status = TRUE;		
		$this->db->select('id');
		$this->db->from('bots_whatsapp');
		$this->db->where('uindex', $uid);
		$this->db->limit(1);
		$test = $this->db->get()->result_array();

		if (isset($test[0]['id'])) {
			$status = FALSE;
		}
		return $status;
	}

	public function getVentas()
	{
		$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_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->select('tl_compras.autorizacion as autorizacion');
		$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->group_start();
$otherdb->where('tl_compras.status', 1);
$otherdb->or_where('tl_compras.status', 2);
$otherdb->group_end();

		$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;
				if($value2['precio'] == 0) $value2['sku'] = 0;
				$value2['opciones'] = $options;
				
				//$addoptions[] = $value2;
				if($value2['cantidad'] > 0) $addoptions[] = $value2;
			}

			$value['productos'] = $addoptions;

			$return[] = $value;
		}

		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->select('tl_compras.autorizacion as autorizacion');
			$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->select('tl_compras.autorizacion as autorizacion');
			$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;
				if($value2['precio'] == 0) $value2['sku'] = 0;
				$value2['opciones'] = $options;
				
				//$addoptions[] = $value2;
				if($value2['cantidad'] > 0) $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->select('tl_compras.autorizacion as autorizacion');
		$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;
				if($value2['precio'] == 0) $value2['sku'] = 0;
				$value2['opciones'] = $options;
				
				if($value2['cantidad'] > 0) $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');
			} else {
				error_log("patsy error status venta: ". $id ." - status: ". $status);
			}

			error_log("patsy3 venta: ". $id ." - status: ". $status);
			
			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_SSL_VERIFYPEER => false,
				  CURLOPT_SSL_VERIFYHOST => false,
                  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);
                error_log("patsy ". $response);
                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_SSL_VERIFYPEER => false,
					CURLOPT_SSL_VERIFYHOST => false,
                    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("patsy1 ".$response);
                    curl_close($curl);
					

					$response = json_decode($response);
					
        //puede cambiar el tiempo, por lo visto no hay tiempo l[imite] cuando hace visalink .... MAY GOD
		//hacer algo aquí, generar un estado cuando el link no existe y enviar un mensaje
		//cerrar los tickets que tienen 24 horas
		//agregar estado cuando visalink falla
		//enviar mensajes y pasar el cliente a cycle 0 cuando pasan 24 horas
		
                    if(isset($response->link[0])) {
                        $link = $response->link[0];
						$html = $html.'
Utilice el siguiente Visalink para realizar el pago de su orden:
'.$link;         

                    } else {
						$otherdb->set('status', 9, FALSE);
						$otherdb->where('id', $compra);
						$return = $otherdb->update('tl_compras');
					}
                } 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";    
				} else {
				
						$otherdb->set('status', 8, FALSE);
						$otherdb->where('id', $compra);
						$return = $otherdb->update('tl_compras');
					
				}

                if($html) {




					setlocale(LC_CTYPE, 'es_CO.UTF-8');
					$msg = str_replace("\\\n", "\\n", $html);
					$msg = str_replace("\n", "\\n", $msg);
					$msg = str_replace("\t", " ", $msg);
					$msg = str_replace("\\t", " ", $msg);
					$msg = str_replace("\b", " ", $msg);
					$msg = str_replace("\\b", " ", $msg);
			  
					$msg = str_replace("\a", " ", $msg);
					$msg = str_replace("\\a", " ", $msg);
					$msg = str_replace("\r", " ", $msg);
					$msg = str_replace("\\r", " ", $msg);
					$msg = str_replace('"', "*", $msg);
			
				  
					$curl = curl_init();
					
					curl_setopt_array($curl, array(
					CURLOPT_URL => 'https://api.maytapi.com/api/0bd60524-2b86-4cf6-a3e2-c5f9b78f58bf/11186/sendMessage',
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => '',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => true,
					CURLOPT_SSL_VERIFYPEER => false,
					CURLOPT_SSL_VERIFYHOST => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => 'POST',
					CURLOPT_POSTFIELDS =>'{
					"to_number": '.$compras[0]['ed_clientes_id'].',
					"type": "text",
					"message": "'.$msg.'"
					}',
					CURLOPT_HTTPHEADER => array(
						'x-maytapi-key: 76e36da0-e199-42ba-88d2-88c396904d2f',
						'Content-Type: application/json',
						'Cookie: __cfduid=df314b968d3e688844e5610aef92daba81611443255'
					),
					));
					
					$response = curl_exec($curl);
					
					curl_close($curl);



                  /*  $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])) {

			error_log("Patsy MSG:".$msg." id: ".$id);
			setlocale(LC_CTYPE, 'es_CO.UTF-8');
			$msg = str_replace("\\\n", "\\n", $msg);
			$msg = str_replace("\n", "\\n", $msg);
			$msg = str_replace("\t", " ", $msg);
			$msg = str_replace("\\t", " ", $msg);
			$msg = str_replace("\b", " ", $msg);
			$msg = str_replace("\\b", " ", $msg);
	  
			$msg = str_replace("\a", " ", $msg);
			$msg = str_replace("\\a", " ", $msg);
			$msg = str_replace("\r", " ", $msg);
			$msg = str_replace("\\r", " ", $msg);
			$msg = str_replace('"', "*", $msg);
	
		  
			$curl = curl_init();
			
			curl_setopt_array($curl, array(
			CURLOPT_URL => 'https://api.maytapi.com/api/0bd60524-2b86-4cf6-a3e2-c5f9b78f58bf/11186/sendMessage',
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS =>'{
			"to_number": '.$compras[0]['ed_clientes_id'].',
			"type": "text",
			"message": "'.$msg.'"
			}',
			CURLOPT_HTTPHEADER => array(
				'x-maytapi-key: 76e36da0-e199-42ba-88d2-88c396904d2f',
				'Content-Type: application/json',
				'Cookie: __cfduid=df314b968d3e688844e5610aef92daba81611443255'
			),
			));
			
			$response = curl_exec($curl);
			
			curl_close($curl);





		/*	$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 guardarComprasSync($post)
{
    $otherdb = $this->load->database('patsy', TRUE);

	$compras = json_decode($post, true);

    $totales = [
        'compras'     => 0,
        'direcciones' => 0,
        'orders'      => 0,
        'options'     => 0
    ];

    $otherdb->trans_begin();

    foreach ($compras as $compra) {

        if (!is_array($compra) || empty($compra['id'])) {
            $otherdb->trans_rollback();
            return [
                'status'  => false,
                'message' => 'Una compra no tiene formato válido o no trae id',
                'data'    => $totales
            ];
        }

        $direcciones = [];
        $orders      = [];

        if (isset($compra['direccion_compra']) && is_array($compra['direccion_compra'])) {
            $direcciones = $compra['direccion_compra'];
        }

        if (isset($compra['orders']) && is_array($compra['orders'])) {
            $orders = $compra['orders'];
        }

        unset($compra['direccion_compra'], $compra['orders']);

        // Insertar compra
        $ok = $otherdb->insert('tl_compras', $compra);
        if (!$ok) {
            $otherdb->trans_rollback();
            return [
                'status'  => false,
                'message' => 'Error insertando en tl_compras',
                'error'   => $otherdb->error(),
                'data'    => $totales
            ];
        }

        $totales['compras']++;

        // Insertar direcciones
        foreach ($direcciones as $direccion) {
            if (!is_array($direccion)) {
                continue;
            }

            $ok = $otherdb->insert('tl_direccion_compra', $direccion);
            if (!$ok) {
                $otherdb->trans_rollback();
                return [
                    'status'  => false,
                    'message' => 'Error insertando en tl_direccion_compra',
                    'error'   => $otherdb->error(),
                    'data'    => $totales
                ];
            }

            $totales['direcciones']++;
        }

        // Insertar orders
        foreach ($orders as $order) {
            if (!is_array($order) || empty($order['id'])) {
                $otherdb->trans_rollback();
                return [
                    'status'  => false,
                    'message' => 'Una order no tiene formato válido o no trae id',
                    'data'    => $totales
                ];
            }

            $options = [];
            if (isset($order['order_options']) && is_array($order['order_options'])) {
                $options = $order['order_options'];
            }

            unset($order['order_options']);

            $ok = $otherdb->insert('tl_orders', $order);
            if (!$ok) {
                $otherdb->trans_rollback();
                return [
                    'status'  => false,
                    'message' => 'Error insertando en tl_orders',
                    'error'   => $otherdb->error(),
                    'data'    => $totales
                ];
            }

            $totales['orders']++;

            // Insertar options
            foreach ($options as $option) {
                if (!is_array($option)) {
                    continue;
                }

                $ok = $otherdb->insert('tl_order_option', $option);
                if (!$ok) {
                    $otherdb->trans_rollback();
                    return [
                        'status'  => false,
                        'message' => 'Error insertando en tl_order_option',
                        'error'   => $otherdb->error(),
                        'data'    => $totales
                    ];
                }

                $totales['options']++;
            }
        }
    }

    if ($otherdb->trans_status() === false) {
        $otherdb->trans_rollback();
        return [
            'status'  => false,
            'message' => 'La transacción falló',
            'data'    => $totales
        ];
    }

    $otherdb->trans_commit();

    return [
        'status'  => true,
        'message' => 'Sincronización completada',
        'data'    => $totales
    ];
}

}
