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


class Md_stihl extends CI_Model {

	public function getProduct($sku)
	{
		$otherdb = $this->load->database('stihl', TRUE);
		$otherdb->select('*');
		$otherdb->from('wp_wc_product_meta_lookup');
		$otherdb->where('sku', $sku);
		$product = $otherdb->get()->result_array();

		if(isset($product[0])){
			$count = count($product);
			if($count > 0) return $product[$count - 1];
			else $product[0];
		} else {
			return $product;
		}
		
	}

	public function putDescuentos()
	{
		$otherdb = $this->load->database('stihl', TRUE);
		$result = array();

		$curl = curl_init();

		curl_setopt_array($curl, array(
			CURLOPT_URL => '190.33.142.170/ENX_API/production/',
			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 =>'{"clase":"GET","action":"cliente_categoria_descuento"}',
			//CURLOPT_POSTFIELDS =>'{"clase":"GET","action":"categories"}',
			CURLOPT_HTTPHEADER => array(
			  'Content-Type: application/json',
			  'X-ENX-Token: PRc4ca4238a0b923820dcc509a6f75849b-lcab-qwymkxhm'
			),
		  ));

		$return = curl_exec($curl);

		curl_close($curl);

		$return = json_decode($return);

		if(isset($return->cliente_categoria_descuento)) {
			$return = $return->cliente_categoria_descuento;
			foreach ($return as $key => $value) {

				if(!empty($value->Categoria)){
					$otherdb->select('*');
					$otherdb->from('wp_terms');
					$otherdb->where('name', $value->Categoria);
					$terms = $otherdb->get()->result_array();
				
					if(isset($terms[0]['name'])) {
						$id = $terms[0]['term_id'];
						$result[] = "Gardado: ". $value->Categoria;

						$data = array(
							'cliente' => $value->Cliente,
							'categoria' => $id,
							'descuento' => $value->Descuento,
						);
	
						$otherdb->insert('wp_descuentos_stihl', $data);
						$id = $otherdb->insert_id();


					} else {
	
						$result[] = "Error: ". $value->Categoria;
					}
	
				}
	
			}
		}



		return $result;
	}

	public function putCategories()
	{
		$otherdb = $this->load->database('stihl', TRUE);
		$result = array();

		$curl = curl_init();

		curl_setopt_array($curl, array(
		CURLOPT_URL => '190.33.142.170/ENX_API/production/',
		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 =>'{"clase":"GET","action":"categories"}',
		CURLOPT_HTTPHEADER => array(
			'Content-Type: application/json',
			'X-ENX-Token: PRc4ca4238a0b923820dcc509a6f75849b-lcab-qwymkxhm'
		),
		));

		$return = curl_exec($curl);

		curl_close($curl);

		$return = json_decode($return);

		if(isset($return->categories)) {
			$return = $return->categories;
			foreach ($return as $key => $value) {

				if(!empty($value->Category_L1)){
					$otherdb->select('*');
					$otherdb->from('wp_terms');
					$otherdb->where('name', $value->Category_L1);
					$terms = $otherdb->get()->result_array();
				
					if(isset($terms[0]['name'])) {
						$id = $terms[0]['term_id'];
						$result[] = "Error: ". $value->Category_L1;
					} else {
	
						$slug = strtolower($value->Category_L1);
						$slug = str_replace(" ", "-", $slug);
	
						$data = array(
							'name' => $value->Category_L1,
							'slug' => $slug,
							'term_group' => 0,
						);
	
						$otherdb->insert('wp_terms', $data);
						$id = $otherdb->insert_id();
	
						$data = array(
							'term_id' => $id,
							'taxonomy' => "product_cat",
							'parent' => 0,
							'count' => 0,
						);
	
						$otherdb->insert('wp_term_taxonomy', $data);
						$result[] = $otherdb->insert_id();
						$result[] = $value->Category_L1;
					}
	
					if(!empty($value->Category_L2)) { 
	
						$otherdb->select('*');
						$otherdb->from('wp_terms');
						$otherdb->where('name', $value->Category_L2);
						$terms2 = $otherdb->get()->result_array();
					
						if(isset($terms2[0]['name'])) {
							$id2 = $terms2[0]['term_id'];
						} else {
				
							$slug = strtolower($value->Category_L2);
							$slug = str_replace(" ", "-", $slug);
				
							$data2 = array(
								'name' => $value->Category_L2,
								'slug' => $slug,
								'term_group' => 0,
							);
				
							$otherdb->insert('wp_terms', $data2);
							$id2 = $otherdb->insert_id();
	
							$data = array(
								'term_id' => $id2,
								'taxonomy' => "product_cat",
								'parent' => $id,
								'count' => 0,
							);
				
							$otherdb->insert('wp_term_taxonomy', $data);
							//$result[] = $otherdb->insert_id();
						}
	
					}
	
					/*if(!empty($value->Category_L2) && !empty($value->Category_L3)) { 
	
						$otherdb->select('*');
						$otherdb->from('wp_terms');
						$otherdb->where('name', $value->Category_L3);
						$terms3 = $otherdb->get()->result_array();
					
						if(isset($terms3[0]['name'])) {
							$id3 = $terms3[0]['term_id'];
						} else {
				
							$slug = strtolower($value->Category_L3);
							$slug = str_replace(" ", "-", $slug);
				
							$data3 = array(
								'name' => $value->Category_L3,
								'slug' => $slug,
								'term_group' => 0,
							);
				
							$otherdb->insert('wp_terms', $data3);
							$id3 = $otherdb->insert_id();
	
							$data = array(
								'term_id' => $id3,
								'taxonomy' => "product_cat",
								'parent' => $id2,
								'count' => 0,
							);
				
							$otherdb->insert('wp_term_taxonomy', $data);
							//$result[] = $otherdb->insert_id();
						}
	
					}*/
				}
	
			}
		}



		return $result;
	}

	public function putProducts()
	{
		//user Detalle para descripcion
		$otherdb = $this->load->database('stihl', TRUE);
		$returnTest = array();

		$a = 1;
		$x = 0;
		while ($a <= 10) {
			
		$curl = curl_init();

		curl_setopt_array($curl, array(
		CURLOPT_URL => '190.33.142.170/ENX_API/production/',
		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 =>'{"clase":"GET","action":"products","page":"'.$a.'"}',
		CURLOPT_HTTPHEADER => array(
			'Content-Type: application/json',
			'X-ENX-Token: PRc4ca4238a0b923820dcc509a6f75849b-lcab-qwymkxhm'
		),
		));

		$response = curl_exec($curl);

		curl_close($curl);
		$return = json_decode($response);


		if(isset($return->products)) {



			
			$products = $return->products;

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


				$jsonCats = "";
				$producto = $value->Producto;
				$wareHouse = $value->InStock;


				if(isset($producto->Item_Number)) {


					$curl = curl_init();

					curl_setopt_array($curl, array(
					  CURLOPT_URL => 'https://api.edsapanama.com/stihl/test?sku='.$producto->Item_Number,
					  CURLOPT_RETURNTRANSFER => true,
					  CURLOPT_ENCODING => '',
					  CURLOPT_MAXREDIRS => 10,
					  CURLOPT_TIMEOUT => 0,
					  CURLOPT_FOLLOWLOCATION => true,
					  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					  CURLOPT_CUSTOMREQUEST => 'GET',
					));
					
					$responseEdsa = curl_exec($curl);
					
					curl_close($curl);

					$testProduct = json_decode($responseEdsa);

					if(isset($testProduct->data->product_id)) $testProduct = $testProduct->data->product_id;
					else $testProduct = "";
		
				} else $testProduct = "";
				
				if(!empty($testProduct)) {

					/*if(isset($wareHouse[7]->WareHouse) && isset($wareHouse[7]->WareHouse) == "EDSA01") {

						$numStock = $wareHouse[7]->InStock;

						$stock = '"stock_quantity": '.$numStock.',';
						if($numStock == 0) {
							$stock .= '"purchasable": false,';
							$stock .= '"manage_stock": false,';
						} else {
							$stock .= '"purchasable": true,';
							$stock .= '"manage_stock": true,';
						}
						
					} else {
						$stock = '"stock_quantity": 0,';
						$stock .= '"purchasable": false,';
						$stock .= '"manage_stock": false,';

					}

					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => 'https://edsapanama.com/index.php/wp-json/wc/v3/products/'.$testProduct,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => '',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => true,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => 'PUT',
					CURLOPT_POSTFIELDS =>'{
						"type": "simple",
						"price": "'.$producto->Precio_Venta.'",
						"regular_price": "'.$producto->Precio_Venta_Real.'",
						"description": "'.$producto->Nombre.'",
						"short_description": "'.$producto->Nombre.'",
						"sku": "'.$producto->Item_Number.'",
						"weight": "'.$producto->Peso.'",
						"dimensions": {
							"length": "'.$producto->Largo.'",
							"width": "'.$producto->Ancho.'",
							"height": "'.$producto->Altura.'"
						},
						'.$stock.'
						"name": "'.$producto->Nombre.'"
					}',
					CURLOPT_HTTPHEADER => array(
						'consumer_key: ck_05f33bc6e16cd868c37c1645c19729bddde1d4bc',
						'consumer_secret: cs_c96c6c6876150062d2fa57e603e5a22b3af33dbf',
						'Content-Type: application/json',
						'Authorization: Basic Y2tfMDVmMzNiYzZlMTZjZDg2OGMzN2MxNjQ1YzE5NzI5YmRkZGUxZDRiYzpjc19jOTZjNmM2ODc2MTUwMDYyZDJmYTU3ZTYwM2U1YTIyYjNhZjMzZGJm',
						'Cookie: mailpoet_page_view=%7B%22timestamp%22%3A1683101447%7D'
					),
					));

					$response = curl_exec($curl);

					curl_close($curl);*/

					$returnTest[$producto->Item_Number] = "Actualizado";

				} else if(isset($value->Producto) && isset($value->InStock)) {
					$producto = $value->Producto;
					$wareHouse = $value->InStock;


					if(!empty($producto->Category_L1)) { 
						$otherdb->select('*');
						$otherdb->from('wp_terms');
						$otherdb->where('name', $producto->Category_L1);
						$terms = $otherdb->get()->result_array();
						if(isset($terms[0]['name'])) {
							$cat1 = $terms[0]['term_id'];
							$jsonCats .= '{"id": '.$cat1.'}';
						}
						if(!empty($producto->Category_L2)) {
							$otherdb->select('*');
							$otherdb->from('wp_terms');
							$otherdb->where('name', $producto->Category_L2);
							$terms = $otherdb->get()->result_array();
							if(isset($terms[0]['name'])) {
								$cat2 = $terms[0]['term_id'];
								$jsonCats .= ',{"id": '.$cat2.'}';
							}
						}
						/*if(!empty($producto->Category_L2) && !empty($producto->Category_L3)) {
							$otherdb->select('*');
							$otherdb->from('wp_terms');
							$otherdb->where('name', $producto->Category_L2);
							$terms = $otherdb->get()->result_array();
							if(isset($terms[0]['name'])) {
								$cat3 = $terms[0]['term_id'];
								$jsonCats .= ',{"id": '.$cat3.'}';
							}
						}*/
					}


					

	
					/*EDSA01*/
					if(isset($wareHouse[7]->WareHouse) && isset($wareHouse[7]->WareHouse) == "EDSA01") {

						$numStock = $wareHouse[7]->InStock;

						$stock = '"stock_quantity": '.$numStock.',';
						if($numStock == 0) {
							$stock .= '"purchasable": false,';
							$stock .= '"manage_stock": false,';
						} else {
							$stock .= '"purchasable": true,';
							$stock .= '"manage_stock": true,';
						}
						
					} else {
						$stock = '"stock_quantity": 0,';
						$stock .= '"purchasable": false,';
						$stock .= '"manage_stock": false,';

					}
					
					if(!empty($jsonCats)) {
						$jsonCats = '"categories":['.$jsonCats.'],';
					}

					if(!empty($producto->Nombre)) {
						$curl = curl_init();
				
						curl_setopt_array($curl, array(
						CURLOPT_URL => 'https://edsapanama.com/index.php/wp-json/wc/v3/products',
						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 =>'{
						"name": "'.$producto->Nombre.'",
						"type": "simple",
						"price": "'.$producto->Precio_Venta.'",
						"regular_price": "'.$producto->Precio_Venta_Real.'",
						"description": "'.$producto->Nombre.'",
						"short_description": "'.$producto->Nombre.'",
						"sku": "'.$producto->Item_Number.'",
						"weight": "'.$producto->Peso.'",
						"dimensions": {
							"length": "'.$producto->Largo.'",
							"width": "'.$producto->Ancho.'",
							"height": "'.$producto->Altura.'"
						},
						'.$stock.'
						'.$jsonCats.'
						"images": [
							{
							"src": "https://edsapanama.com/wp-content/uploads/2023/04/no-product.png"
							}
						]
						}',
						CURLOPT_HTTPHEADER => array(
						'consumer_key: ck_05f33bc6e16cd868c37c1645c19729bddde1d4bc',
						'consumer_secret: cs_c96c6c6876150062d2fa57e603e5a22b3af33dbf',
						'Authorization: Basic Y2tfMDVmMzNiYzZlMTZjZDg2OGMzN2MxNjQ1YzE5NzI5YmRkZGUxZDRiYzpjc19jOTZjNmM2ODc2MTUwMDYyZDJmYTU3ZTYwM2U1YTIyYjNhZjMzZGJm',
						'Content-Type: application/json',
						'Cookie: mailpoet_page_view=%7B%22timestamp%22%3A1678861050%7D'
						),
						));
		
						$response = curl_exec($curl);
						curl_close($curl);
						$returnTest[$producto->Item_Number] = "Creado";

					}
					
				}

			}
		}


			$a++;
		}



		return $returnTest;

	}

}
