<?php
header('Access-Control-Allow-Origin: *');
require_once("wp-load.php");
require_once("wp-includes/functions.php");

require "admin/process/conexionIpos.php";
require "admin/process/crud.php";

$opt = $_GET['option'];

if ($opt == 'checkAll') {
  checkAll();
}

function checkAll() {

  $almacenes = 'rio_bravo';

  $model = new Crud;
	$model->select = "articulos.id, clave, descripcion, ROUND((precio1 * .08) + precio1, 2) AS precio1, ($almacenes) AS existencia, CASE WHEN imagen = '' OR imagen LIKE '%.' THEN 'https://iposplus.io/pos/assets/img/item.png' ELSE CASE WHEN locate('https', imagen) = 0 THEN CONCAT('https://campeon.iposplus.io', imagen) ELSE imagen END END as image, CONCAT(categoria, '>', familia, '>', subfamilia) AS cat, categorias.categoria, familias.familia, subfamilias.subfamilia, articulos.pagina_activo, articulos.activo";
	$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.activo = '1' AND articulos.isService = '0' LIMIT 1, 3000";
	$model->Read();
	$filas = $model->rows;
	$array = array();
	if (!empty($filas)) {
		foreach ($filas as $fila) {
      $idPOS = $fila['id'];
      $clave = $fila['clave'];
      $desc = $fila['descripcion'];
      $pre = $fila['precio1'];
      $existencia = $fila['existencia'];
      $img = $fila['image'];
      $cat = $fila['cat'];
      $categoria = $fila['categoria'];
      $fam = $fila['familia'];
      $subF = $fila['subfamilia'];
      $activoPag = $fila['pagina_activo'];
      $activoArt = $fila['activo'];

      $idPagina = getIdNoSku($clave);

      if ($idPagina === '0' || $idPagina === 0 || $idPagina === ''  || $idPagina === null)
      {
        $model = new Crud;
        $model->insertInto = "woocommerce_cron";
        $model->insertColumns = "id_art, motivo";
        $model->insertValues = "'$idPOS', 'Crear'";
        $model->Create();

        updateProduct($clave, $desc, $pre, $existencia, $img, $cat, $categoria, $fam, $subF, $activoPag, $activoArt);
      }
      else {

        $product = wc_get_product( $idPagina );

        $clavePag = $product->sku;
        $PrePag = $product->price;
        $stockPag = $product->stock_quantity;

        $motivo = '';
        $actualizar = false;

        if ($clavePag != $clave) {
          $motivo = 'Clave';
          $actualizar = true;
        }
        else if (floatval($PrePag) != floatval($pre)) {
          $motivo = 'Precio';
          $actualizar = true;
        }
        else if ($stockPag != $existencia) {
          $motivo = 'Existencia';
          $actualizar = true;
        }

        if ($actualizar) {
          $model = new Crud;
          $model->insertInto = "woocommerce_cron";
          $model->insertColumns = "id_art, motivo";
          $model->insertValues = "'$idPOS', '$motivo'";
          $model->Create();

          updateProduct($clave, $desc, $pre, $existencia, $img, $cat, $categoria, $fam, $subF, $activoPag, $activoArt);
        }

        // echo 'Clave: ' . $clavePag . ' pre: ' . $PrePag . ' stock: ' . $stockPag . ' motivo: ' . $motivo;
      }
		}
	}
}

function updateProduct($clave, $desc, $pre, $existencia, $img, $cat, $categoria, $fam, $subF, $activoPag, $activoArt) {
  $model = new Crud;

  $almacenes ='rio_bravo';

  $lastImgChar = substr($img, -1);
  if ($lastImgChar == '|') {
    $img = substr($img, 0, -1);
  }

  $imagesArr = array();

  if (strpos($img, '|') !== false) {
    $imagesArrEx = explode("|", $img);

    for ($i = 0; $i < count($imagesArrEx); $i++) {

      $srcImg = $imagesArrEx[$i];
      if (strpos($srcImg, 'http') !== false) {

      }
      else {
        $srcImg =  "https://campeon.iposplus.io" . $srcImg;
      }

      $sirve = checkRemoteFile($srcImg);
      if (!$sirve) {
        $srcImg = 'https://campeon.iposplus.io/pos/assets/img/item.png';
      }
      $imagesArr[] = array("src" => $srcImg);
    }
  }
  else {
    $sirve = checkRemoteFile($img);
    if (!$sirve) {
      $img = 'https://campeon.iposplus.io/pos/assets/img/item.png';
    }
    $imagesArr[] = array("src" => $img);
  }



  $desc = str_replace('"', '', $desc);

  ////////// Obtener ID categoria /////////////////////////////
  $idPadrePadre = '0';

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

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

  $url .= $oauth;
  $data = array("search" => $categoria, "parent" => '0');
  $headers = array("Content-Type:" . "application/json");
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  $result = curl_exec($ch);
  if ($result === false) {
    die('Curl failed: ' . curl_error($ch));
  }
  curl_close($ch);

  if ($result != '[]' && !empty($result) && $result != '') {
    $newResult = str_replace('\/','/', $result);
    $newResult = str_replace('[','', $newResult);
    $newResult = str_replace(']','', $newResult);
    $json = json_decode($result);

    $idPadrePadre = $json->id;

    if ($idPadrePadre == '' || $idPadrePadre == null || $idPadrePadre == '0' || $idPadrePadre == 0) {

      foreach ($json as $data) {
        $slug = $data->slug;
        $nameCompare = $data->name;
        if (strtolower(trim($slug)) == strtolower(trim($categoria)) || strtolower(trim($nameCompare)) == strtolower(trim($categoria))) {
          $idPadrePadre = $data->id;
          break;
        }
      }
    }

    if ($idPadrePadre == '' || $idPadrePadre == null || $idPadrePadre == '0' || $idPadrePadre == 0) {
      $idPadrePadre = get_string_between($newResult, '"id":', ',"');
    }
  }

  if ($idPadrePadre == '' || $idPadrePadre == null || $idPadrePadre == '0' || $idPadrePadre == 0) {

    $url = 'https://elcampeon.mx/wp-json/wc/v3/products/categories';
    $oauth = generateOauth('POST', $url);

    $url .= $oauth;

    $headers = array("Content-Type:" . "application/json");
    $data = array("name" => $categoria);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $result = curl_exec($ch);
    if ($result === false) {
      die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);

    if ($result != '[]' && !empty($result) && $result != '') {
      $json = json_decode($result);

      $idPadrePadre = $json->id;
    }

  }

  $idPadre = '0';

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

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

  $url .= $oauth;
  $data = array("search" => $fam, 'parent' => $idPadrePadre, 'per_page' => '30');
  $headers = array("Content-Type:" . "application/json");
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  $result = curl_exec($ch);
  if ($result === false) {
    die('Curl failed: ' . curl_error($ch));
  }
  curl_close($ch);

  if ($result != '[]' && !empty($result) && $result != '') {
    $newResult = str_replace('\/','/', $result);
    $newResult = str_replace('[','', $newResult);
    $newResult = str_replace(']','', $newResult);
    $json = json_decode($result);

    $idPadre = $json->id;

    if ($idPadre == '' || $idPadre == null || $idPadre == '0' || $idPadre == 0) {

      foreach ($json as $data) {
        $slug = $data->slug;
        $nameCompare = $data->name;
        if (strtolower(trim($slug)) == strtolower(trim($fam)) || strtolower(trim($nameCompare)) == strtolower(trim($fam))) {
          $idPadre = $data->id;
          break;
        }
      }
    }

    if ($idPadre == '' || $idPadre == null || $idPadre == '0' || $idPadre == 0) {
      $idPadre = get_string_between($newResult, '"id":', ',"');
    }
  }

  if ($idPadre == '' || $idPadre == null || $idPadre == '0' || $idPadre == 0) {


    $url = 'https://elcampeon.mx/wp-json/wc/v3/products/categories';
    $oauth = generateOauth('POST', $url);

    $url .= $oauth;

    $headers = array("Content-Type:" . "application/json");
    $data = array("name" => $fam, "parent" => $idPadrePadre);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $result = curl_exec($ch);
    if ($result === false) {
      die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);

    if ($result != '[]' && !empty($result) && $result != '') {
      $json = json_decode($result);

      $idPadre = $json->id;
    }

  }

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

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

  $url .= $oauth;
    $data = array("search" => $subF, 'parent' => $idPadre);
  $headers = array("Content-Type:" . "application/json");
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  $result = curl_exec($ch);
  if ($result === false) {
    die('Curl failed: ' . curl_error($ch));
  }
  curl_close($ch);

  $idCatPagina = '0';

  if ($result != '[]' && !empty($result) && $result != '') {
    $json = json_decode($result);
    $idCatPagina = $json->id;
    if ($idCatPagina == '' || $idCatPagina == null || $idCatPagina == '0' || $idCatPagina == 0) {

      foreach ($json as $data) {
        $slug = $data->slug;
        $nameCompare = $data->name;
        if (strtolower(trim($slug)) == strtolower(trim($subF)) || strtolower(trim($nameCompare)) == strtolower(trim($subF))) {
          $idCatPagina = $data->id;
          break;
        }
      }
    }
  }

  if ($idCatPagina == '' || $idCatPagina == null || $idCatPagina == '0' || $idCatPagina == 0) {

    $url = 'https://elcampeon.mx/wp-json/wc/v3/products/categories';
    $oauth = generateOauth('POST', $url);

    $url .= $oauth;

    $headers = array("Content-Type:" . "application/json");
    $data = array("name" => $subF, "parent" => $idPadre);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $result = curl_exec($ch);
    if ($result === false) {
      die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);

    if ($result != '[]' && !empty($result) && $result != '') {
      $json = json_decode($result);

      $idCatPagina = $json->id;
    }

  }

  $idPagina = getIdNoSku($clave);
  $idPagina = preg_replace("/\s+/", "", $idPagina);

  if ($idPagina === '0' || $idPagina === 0) {
    ////////// Agregar pagina /////////////////////////////

    $url = 'https://elcampeon.mx/wp-json/wc/v3/products/';
    $oauth = generateOauth('POST', $url);

    $url .= $oauth;

    $visible = 'hidden';
    if ($activoPag == '1' && $activoArt == '1') {
      $visible = "visible";
    }

    echo 'ADD idcat ' . $idCatPagina;

    $headers = array("Content-Type:" . "application/json");
    error_log($existencia);
    $data = array("regular_price" => $pre, "name" => $desc, "sku" => $clave, "categories" => array(array("id" => $idCatPagina)), 'manage_stock' => 'true', "stock_quantity" => $existencia, "images" => $imagesArr,
    "catalog_visibility" => $visible);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    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;

  }
  else {
    ////////// Actualizar pagina /////////////////////////////

    $url = 'https://elcampeon.mx/wp-json/wc/v3/products/'. $idPagina;
    $oauth = generateOauth('PUT', $url);

    $url .= $oauth;

    $visible = 'hidden';
    if ($activoPag == '1' && $activoArt == '1') {
      $visible = "visible";
    }

    $headers = array("Content-Type:" . "application/json");
    $data = array("regular_price" => $pre, "name" => $desc, "sku" => $clave, 'manage_stock' => 'true', "stock_quantity" => $existencia, "images" => $imagesArr,
    "catalog_visibility" => $visible);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    $result = curl_exec($ch);

    if ($result === false) {
      die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);
    echo $result;
  }

}

function checkRemoteFile($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    // don't download content
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($ch);
    curl_close($ch);
    if($result !== FALSE)
    {
        return true;
    }
    else
    {
        return false;
    }
}

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 getIdNoSku($clave) {
  $id = wc_get_product_id_by_sku( $clave );
  return $id;
}

?>
