<?php
session_start();

$geral_initial_time = microtime(true);
require_once './constantes.php';

$conn = mysqli_connect(DB_MATRIZ_HOST, DB_MATRIZ_USER, DB_MATRIZ_PASS, DB_MATRIZ_NAME_SIS);

$row = getPedido();

if(empty($row)){
  die('sem pedidos');
}

########################################################################

$ID_PEDIDO = $row['idpedido'];
echo $ID_PEDIDO .'<br>';
echo date('d-m-Y', strtotime($row['data'])) .'<br>';

$URL = getURL($row);

$response = getResponse($URL);
$response = adjustResponse($response);

$SQL_inserts = getInsertsSQL($response, $ID_PEDIDO);

$result = saveAnalises($SQL_inserts);

if($result) {
  $_SESSION['id_pedido_anterior'] = $ID_PEDIDO;
}

echo '<pre>';
var_dump($result);
echo '</pre>';

$geral_final_time = microtime(true);
$geral_total_time = $geral_final_time - $geral_initial_time;

echo "<br><br>Tempo total de execução: " . number_format($geral_total_time, 2, ',', '.') . "s<br><br>";

echo '<script>
  setTimeout(function() {
    window.location.reload();
  }, 500);
</script>';


########################################################################
// Encontrar a lista de produtos para análise
function getPedido(){
  global $conn;

  $find = false;
  $id_anterior = $_SESSION['id_pedido_anterior'] ?? null;
  $count = 0;

  $row = null;

  do{
    $complemento = '';
    if($id_anterior !== null){
      $complemento = " WHERE idpedido < '$id_anterior'";
    }
  
    $SQL = "SELECT P.*, A.id id_analise FROM (
        SELECT * FROM bkp_pedidos $complemento ORDER BY id DESC LIMIT 1
    ) P LEFT JOIN bkp_analise A ON A.pedido_cod = P.idpedido";
  
    
    $result = mysqli_query($conn, $SQL);

    if(mysqli_errno($conn) != 0){
      echo '<br><pre>';
      var_dump(mysqli_error($conn));
      echo '</pre><br>';
      return null;
    }

    if($result && mysqli_num_rows($result) > 0){
      $row = mysqli_fetch_assoc($result);
      
      $id_anterior = $row['id'];
  
      $find = $row['id_analise'] === null;
    }
    $count++;
  }while(!$find && $count < 100000);

  return $row;
}

function getURL($row){
  $data_fim = date('Y-m-d', strtotime($row['data']));
  $data_inicio = date('Y-m-d', strtotime($data_fim." - 365 days"));

  $buscador = [
    "POST_paramentro" => 'Seleciona_Traslados',
    "Identificador"   => 'Traslados',
    "origem"          => $row['origem'],
    "destino"         => $row['loja'],
    "date_ini"        => $data_inicio,
    "date_fim"        => $data_fim,
    "dias"            => 14,
    "fornecedor"      => '',
    "grupo"           => '',
    "tipo"            => '',
    "deposito"        => '',
    "usuario"         => 0
  ];

  $URL = "http://192.168.0.237:8080/transfer/backend/config/processos/processos2.php?" . http_build_query($buscador);

  return $URL;
}

function getResponse($URL){
  echo "executando: <br>" . $URL . "<br>";
  
  $initial_time = microtime(true);
  // realizar requizição para o backend
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $URL);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  curl_close($ch);

  $final_time = microtime(true);
  $total_time = $final_time - $initial_time;

  echo "tempo de execução da requisição: " . number_format($total_time, 2, ',', '.') . "s<br>";

  if(is_string($response) && !empty($response)){
    $response = json_decode($response, true);
  }

  return $response;
}

function adjustResponse($response){  
  $count = 0;
  $handle_response = [];

  for($count = 0; $count < count($response); $count++){
    $item = $response[$count];

    $SUGESTAO = sugestao($item['MEDIA'], $item['DIAS'], $item['QUANT_ORIGEM'], $item['QUANT_DESTINO']);

    if($SUGESTAO == 0){
      continue;
    }

    $newItem = [ 
      'id' => ($count+1),
      'cod' => $item['PROD_CODIGO'],
      'ref' => $item['PROD_REFERENCIA'],
      'desc' => $item['PROD_DESCRICAO'],
      'dias' => $item['DIASINTERVAL'],
      'saida' => $item['MOV_SAIDAS'],
      'media' => $item['MEDIA'],
      'origem' => $item['QUANT_ORIGEM'],
      'destino' => $item['QUANT_DESTINO'],
      'sugestao' => $SUGESTAO,
      'preco' => $item['PROD_PRECO'],
      'deposito' => $item['PROD_DEPOSITO'],
    ];
    
    array_push($handle_response, $newItem);
  }

  return $handle_response;
}

function sugestao($media, $dias, $est_matriz, $est_filial){
  if($est_matriz >= 3){
    $calculo_n_1 = $media * $dias;
    
    $result = ceil($calculo_n_1) - $est_filial;
    if($result < 0){
      $result = 0;
    }
  }else{
    $result = 0;
  }
  
  return $result;
}

########################################################################

function getInsertsSQL($response, $ID_PEDIDO){
  $sql_open_insert = "INSERT INTO `bkp_analise`(`pedido_cod`, `prod_codigo`, `prod_ref`, `prod_desc`, `dias_consulta`, `ven_period`, `media_dia`, `est_matriz`, `est_filial`, `sugestao`, `separado`, `status`, `preco`, `deposito`) VALUES";

  $values = getInsertValues($response, $ID_PEDIDO);

  $SQLs = [];
  foreach($values as $key => $value_s){
    $SQLs[$key] = $sql_open_insert . implode(',', $value_s) . ";";
  }

  return $SQLs;
}

function getInsertValues($response, $ID_PEDIDO) : array {
  $values = [];

  $count = 0;
  $values_section = 0;
  foreach ($response as $key) {
    $values[$values_section][] = "('$ID_PEDIDO','".$key['cod']."','".$key['ref']."','".$key['desc']."','".$key['dias']."','".$key['saida']."','".$key['media']."','".$key['origem']."','".$key['destino']."','".$key['sugestao']."','0','PENDENTE','".$key['preco']."','".$key['deposito']."')";

    $count++;

    // limite temporário de 5 itens
    if($count == 5){
      break;
    }
    // limite temporário de 10 itens \.

    if($count == 100){
      $values_section++;
      $count = 0;
    }
  }

  return $values;
}

function saveAnalises($SQL_inserts){
  global $conn;

  foreach ($SQL_inserts as $SQL) {
    $result = mysqli_query($conn, $SQL);

    echo '<br><pre>';
    var_dump($result);
    echo '</pre><br>';

    if(mysqli_errno($conn) != 0){
      echo '<br><pre>';
      var_dump(mysqli_error($conn));
      echo '</pre><br>';

      return false;
    }
  }

  return true;
}