<?php



// if (date_default_timezone_get()) {

//     echo 'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';

//     echo 'time: ' . time() . '<br />';

// }



header('Access-Control-Allow-Origin: *');



require "conexion.php";

require "crud.php";



if (isset($_GET['op'])) {

  $op = $_GET['op'];



  $id = getId();



  if ($op == 'POST') {

  }

  if ($op == 'PUT') {

    $price = $_GET['price'];



    updatePrice($id, $price);

  }

  if ($op == 'GET') {

    getDataProduct($id);

  }

}



if (isset($_GET['option'])) {

  $op = $_GET['option'];



  if ($op == 'GETMayoreo') {

    $sku = $_GET['sku'];



    getMayoreo($sku);

  }

  if ($op == 'updateProduct') {

    $id = $_GET['id'];

    updateProduct($id);

  }

}



function updateProduct($id) {

  $model = new Crud;



  $almacenes = '';

  $model->select = "LOWER(REPLACE(almacen, ' ', '_')) almacen";

	$model->from = "almacenes";

	$model->condition = "NOT almacen = 'TODOS'";

	$model->Read();

	$filas = $model->rows;

	$array = array();

  $i = 0;

	if (!empty($filas)) {

		foreach ($filas as $fila) {

      $alm = $fila['almacen'];

      if ($i == 0) {

			  $almacenes = $alm;

      }

      else {

        $almacenes .= ' + ' . $alm;

      }

      $i++;

		}

	}



  $clave = '';

  $desc = '';

  $pre = '';

  $existencia = '';

  $img = '';

  $cat = '';

  $subF = '';

	$model->select = "clave, descripcion, ROUND((precio1 * .08) + precio1, 2) AS precio1, ($almacenes) AS existencia, imagen, CONCAT(categoria, '>', familia, '>', subfamilia) AS cat, subfamilias.subfamilia";

	$model->from = "articulos INNER JOIN familias ON articulos.id_familia = familias.id INNER JOIN subfamilias ON subfamilias.id = articulos.id_subfamilia INNER JOIN categorias ON categorias.id = familias.id_categoria";

	$model->condition = "articulos.id = '$id'";

	$model->Read();

	$filas = $model->rows;

	$array = array();

	if (!empty($filas)) {

		foreach ($filas as $fila) {

      $clave = $fila['clave'];

      $desc = $fila['descripcion'];

      $pre = $fila['precio1'];

      $existencia = $fila['existencia'];

      $img = $fila['imagen'];

      $cat = $fila['cat'];

      $subF = $fila['subfamilia'];

		}

	}



  ////////// Obtener ID categoria /////////////////////////////

  $url = 'http://elcampeon.mx/wp-json/wc/v3/products/categories';



  $oauth = generateOauth('GET', $url);



  $url .= $oauth;

  // echo '<br />' . $url;

  // $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $firebase);

  $headers = array("Content-Type:" . "application/json");

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);

  // curl_setopt($ch, CURLOPT_POST, true);

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  // curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($oauth));

  $result = curl_exec($ch);

  if ($result === false) {

    die('Curl failed: ' . curl_error($ch));

  }

  curl_close($ch);

  echo $result;



  ////////// Actualizar pagina /////////////////////////////



  $url = 'http://elcampeon.mx/wp-json/wc/v3/products/'. $id;

  $oauth = generateOauth('PUT', $url);



  $url .= $oauth;



  $headers = array("Content-Type:" . "application/json");

  $data = array("regular_price" => $price, "name" => $desc, "sku" => $clave, "categories" => $cat, "stock_quantity" => $existencia,);

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);

  // curl_setopt($ch, CURLOPT_POST, true);

  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

  $result = curl_exec($ch);

  if ($result === false) {

    die('Curl failed: ' . curl_error($ch));

  }

  curl_close($ch);

  echo $result;



}



function getMayoreo($sku) {

	$model = new Crud;

	$model->select = "cantidad, precio";

	$model->from = "articulos INNER JOIN mayoreo ON articulos.id = mayoreo.id_articulo";

	$model->condition = "articulos.clave = '$sku'";

	$model->Read();

	$filas = $model->rows;

	$array = array();

	if (!empty($filas)) {

		foreach ($filas as $fila) {

			$array[] = array(

				'cantidad' => $fila['cantidad'], 'precio' => $fila['precio']);

		}

	}

  $array = utf8_converter($array);

	echo json_encode($array);

}



function getId() {



  $sku = $_GET['sku'];



  $url = 'http://elcampeon.mx/woocommerceTest.php?sku=' . $sku;

  $headers = array("Content-Type:" . "text/html");

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);

  // curl_setopt($ch, CURLOPT_POST, true);

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

  $result = curl_exec($ch);

  if ($result === false) {

    die('Curl failed: ' . curl_error($ch));

  }

  curl_close($ch);



  return $result;



  // getDataProduct($result);



}



function updatePrice($id, $price) {

  $url = 'http://elcampeon.mx/wp-json/wc/v3/products/'. $id;

  $oauth = generateOauth('PUT', $url);



  $url .= $oauth;



  $headers = array("Content-Type:" . "application/json");

  $data = array("regular_price" => $price);

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);

  // curl_setopt($ch, CURLOPT_POST, true);

  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

  $result = curl_exec($ch);

  if ($result === false) {

    die('Curl failed: ' . curl_error($ch));

  }

  curl_close($ch);

  echo $result;

}



function getDataProduct($id) {

  $url = 'http://elcampeon.mx/wp-json/wc/v3/products/'. $id;



  $oauth = generateOauth('GET', $url);



  $url .= $oauth;

  // echo '<br />' . $url;

  // $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $firebase);

  $headers = array("Content-Type:" . "application/json");

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);

  // curl_setopt($ch, CURLOPT_POST, true);

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

  // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  // curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($oauth));

  $result = curl_exec($ch);

  if ($result === false) {

    die('Curl failed: ' . curl_error($ch));

  }

  curl_close($ch);

  echo $result;

}



function getNonce($length = 5)

{

  $nonce_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  $result = '';

  $cLength = strlen($nonce_chars);

  for ($i = 0; $i < $length; $i++) {

    $rnum = rand(0, $cLength - 1);

    $result .= substr($nonce_chars, $rnum, 1);

  }



  return $result;

}



function generateSignature($method, $url, $timestamp, $nonce, $signatureMethod, $version, $consumerKey, $consumerSecret)

{

    $base = $method . "&" . rawurlencode($url) . "&"

        . rawurlencode("oauth_consumer_key=" . rawurlencode($consumerKey)

        . "&oauth_nonce=" . rawurlencode($nonce)

        . "&oauth_signature_method=" . rawurlencode($signatureMethod)

        . "&oauth_timestamp=" . $timestamp

        . "&oauth_version=" . $version);



    $key = rawurlencode($consumerSecret) . '&';

    $signature = base64_encode(hash_hmac('sha1', $base, $key, true));





    return $signature;

}



function generateOauth($method, $url) {

  $consumerKey = 'ck_ddb18b061402ce6bfda048e15f5f700f00f65b3b';

  $consumerSecret = 'cs_d3f2c7834e78ca696abc2fdf0e78efe9f9451231';



  // $method = 'GET';

  $timestamp = time();

  $timestamp = strval($timestamp);

  $nonce = getNonce(11);

  $version = "1.0";

  $signatureMethod = "HMAC-SHA1";

  $signature = generateSignature($method, $url, $timestamp, $nonce, $signatureMethod, $version, $consumerKey, $consumerSecret);



  $oauth = '?oauth_consumer_key=' . $consumerKey . '&oauth_nonce=' . $nonce . '&oauth_signature='. $signature .'&oauth_signature_method=HMAC-SHA1&oauth_timestamp='.$timestamp.'&oauth_version=1.0';

  return $oauth;

}



function utf8_converter($array)

{

	array_walk_recursive($array, function (&$item, $key) {

		if (!mb_detect_encoding($item, 'utf-8', true)) {

			$item = utf8_encode($item);

		}

	});

	return $array;

}



?>

