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

require "conexionIpos.php";
require "crud.php";
require "SED.php";

$postedContent = json_decode(file_get_contents("php://input"));

if (property_exists($postedContent, 'option'))
{
}
else if (isset($_POST["option"])) {
  $option = $_POST["option"];

  // if ($option == 'createSale') {
  //   $id = $_POST['id'];
  //   error_log('Entra a crear venta con id ' . $id);
  //   echo "Bien";
  // }
}
else {
    $option = $_GET["option"];

    if ($option == 'registerUser') {
      $user = $_GET["user"];
      $pass = $_GET["pass"];
      $name = $_GET["name"];
      $last_name = $_GET["last_name"];
      $email = $_GET["email"];
      $tel = $_GET["tel"];
      $cp = $_GET["cp"];
      $estado = $_GET["estado"];
      $municipio = $_GET["municipio"];
      $colonia = $_GET["colonia"];
      $calle = $_GET["calle"];
      $numExt = $_GET["numExt"];
      $numInt = $_GET["numInt"];
    }
}

switch ($option) {
  case 'registerUser':
    registerUser();
    break;
}

function registerUser() {
  global $user;
  global $pass;
  global $name;
  global $last_name;
  global $email;
  global $tel;
  global $cp;
  global $estado;
  global $municipio;
  global $colonia;
  global $calle;
  global $numExt;
  global $numInt;

  $metaUser = array(
    'user_phone' => $tel,
    'user_cp' => $cp,
    'user_estado' => $estado,
    'user_ciudad' => $municipio,
    'user_colonia' => $colonia,
    'user_calle' => $calle,
    'user_num' => $numExt,
    'user_numInt' => $numInt
  );

  $usuarioIdWP = new_user_with_metadata($user, $pass, $email, $metaUser);

  $passHash = md5($pass);

  $model = new Crud;
  // $model->insertInto = "wp_users";
  // $model->insertColumns = "user_login, user_pass, user_nicename, user_email, user_url, user_registered, user_activation_key, user_status, display_name";
  // $model->insertValues = "'$user', '$passHash', '$user', '$email', '', now(), '', 1, '$name $last_name'";
  // $model->CreateId();

  $nombreCli = $name . ' ' . $last_name;

  $model->insertInto = "clientes";
	$model->insertColumns = "seudonimo,nombre,contacto, direccion, ciudad, rfc, cp, telefono1, telefono2, telefono3, estado, municipio, localidad, id_user, lim_credito, email, curp, credito, precio_venta, precio_credito, saldo_actual, saldo_vencido, credito_disp, dias_credito, idCustomerWP";
	$model->insertValues = "'$user','$nombreCli','$nombreCli', '$calle $numExt $numInt', '$municipio', '', '$cp', '$tel', '', '', '$estado', '$municipio', '', '1', '0', '$email', '', 0, '1', '2', '0', '0', '0', '0','$usuarioIdWP'";
	$model->CreateId();
  $idUser = $model->message;

  $mensajeJSON = array(
    'status' => "success",
    'message' => "Registrado correctamente",
    'data' => $idUser,
    'dataWP' => $usuarioIdWP
  );

  $mensajeJSON = utf8_converter($mensajeJSON);
	echo json_encode($mensajeJSON);

}

function new_user_with_metadata( $username, $password, $email, $meta) {
  //this is just an example, in your function you can pass as many fields as you want
  // $meta = array(
  //   'job_title' => 'developer',
  //   'country' => 'United States',
  //   'viaphp' => true
  // );

  //let's create our user
  $user = wp_create_user( $username, $password, $email );

  //check if there are no errors
  if ( ! is_wp_error( $user ) ) {
    foreach( $meta as $key => $val ) {
      update_user_meta( $user, $key, $val );
    }
  }

  return $user;
}

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;
}

?>
