<script language='JavaScript'>
function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;   
    if((tecla>47 && tecla<58)) return true;
    else{
    	if (tecla==8 || tecla==0) return true;
	else  return false;
    }
}
</script>

<?php
if (isset($this->Dados[0])):
    $catArtigos = $this->Dados[0];
    //var_dump($catArtigos);
endif;
if (isset($this->Dados[1][0])):
    $valorForm = $this->Dados[1][0];
    //var_dump($valorForm);
elseif (isset($this->Dados[1])):
    $valorForm = $this->Dados[1];
    //var_dump($valorForm);
endif;

?>
<div class="well">
    <div class="pull-right">
        <a href="<?php echo URL; ?>controle-artigo/index"><button type="button" class="btn btn-sm btn-success">Listar</button></a>
        <a href="<?php echo URL; ?>controle-artigo/visualizar/<?php echo $valorForm['../../Conteúdo FTP Prod/eed/adm/views/artigo/id']; ?>"><button type="button" class="btn btn-sm btn-primary">Visualizar</button></a>
        <!--<a href="<?php echo URL; ?>controle-artigo/apagar/<?php echo $valorForm['id']; ?>"><button type="button" class="btn btn-sm btn-danger">Apagar</button></a>-->
    </div>
    <div class="page-header">
        <h1>Fechar e Enviar Chamada de Encalhe</h1>
    </div>
    <?php
    if (isset($_SESSION['msg'])):
        echo $_SESSION['msg'];
        unset($_SESSION['msg']);
    endif;
    if (isset($_SESSION['msgcad'])):
        echo $_SESSION['msgcad'];
        unset($_SESSION['msgcad']);
    endif;
    ?>
    
    <form name="CadArtigo"  class="form-horizontal" action="" method="post" enctype="multipart/form-data">
        
        <input type="hidden" name="id" value="<?php
        if (isset($valorForm['id'])):
            echo $valorForm['id'];
        endif;
        ?>">
        
        
        <div class="form-group">
            <label class="col-sm-2 control-label">Nº da CE:</label>
            <div class="col-sm-10">
                <input type="text"  class="form-control" name="cde_number" placeholder="Nº da CE" value="<?php
                if (isset($valorForm['cde_number'])): echo $valorForm['cde_number'];
                endif;
                ?> "readonly>
            </div>
        </div>
        
        
        <?php
        if ($valorForm['recall_type'] == "PARCIAL"):?>
        
        <div class="form-group">
            <label class="col-sm-2 control-label">Venda:</label>
            <div class="col-sm-10">
                <input type="text"  class="form-control" name="sales" onkeypress="return SomenteNumero(event)" placeholder="Venda" value="<?php
                if (isset($valorForm['sales'])): echo $valorForm['sales'];
                endif;
                ?>">
            </div>
        </div>
                       
            <?php
        
                    endif;
                    
            ?>
                
        <input type="hidden" name="modified" value="<?php echo date("Y-m-d H:i:s"); ?>">
        
        
        <?php
        
        // ********************************************************************************************************************
        // INICIAR ROTINA
        // ********************************************************************************************************************
                   
          $ce = $_SESSION['ce'];
        
          echo $ce;        
          echo "";
          $customercode = $_SESSION['customercode'];
          $cnpj = $_SESSION['cnpj'];
          
          echo $customercode; 
          echo "   ";
          
          // ***************************************************************************
          // selecionar registros
          // ****************************************************************************
      
           selecionar_registros($ce,$customercode,$cnpj);
           
          //****************************************************************************
          // Alterar o status da chamada de encalhe
          // ***************************************************************************
           alterar_status($ce,$customercode,$cnpj); 
  
          // ***************************************************************************
          
           
        
          
           
           
           
           
// **************************************************************************** 
function selecionar_registros($ce,$customercode,$cnpj){
// ****************************************************************************
    
         $host1    = $_SESSION['HOST'];
         $user1    = $_SESSION['USER'];
         $pass1    = $_SESSION['PASS'];
         $dbname1  = $_SESSION['DBNAME'];
         
         $mysqli = new mysqli($host1, $user1, $pass1, $dbname1);
         

        /* check connection */
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
        }
        
        $ce = trim($ce);
        $customercode = trim($customercode);
        
        $query =   "select"
                 . " customercode,"
                 . " cnpj ,"
                 . " cde_number, "
                 . " id_product, "
                 . " id_edition, "
                 . " edition_number, "
                 . " id_prod_Planeta, "
                 . " recall_type, "
                 . " recall_date, "
                 . " line_number, "
                 . " total_distributed, "
                 . " return2, "
                 . " sales, "
                 . " send, "
                 . " discount, "
                 . " nota_ponto, "
                 . " invoice_number, "
                 . " id_ce, "
                 . " id_ponto "
                 . "from artigos"
                . " where cde_number = "
                . $ce . " and customercode = " . $customercode . " and cnpj = " . $cnpj . "  and status = 'A'"; 
     
         //$rce_id_product_joao       = "99999";
         
        if ($result = $mysqli->query($query)) {

        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
          
          $rce_id                    = $row["id"];
          $rce_customercode          = $row["customercode"];
          $rce_cnpj                  = $row["cnpj"];
          $rce_cde_number            = $row["cde_number"];
          $rce_id_product            = $row["id_product"];
          $rce_id_edition            = $row["id_edition"];
          $rce_edition_number        = $row["edition_number"];
          $rce_id_prod_Planeta       = $row["id_prod_Planeta"];
          $rce_recall_type           = $row["recall_type"];
          $rce_recall_date           = $row["recall_date"];
          $rce_line_number           = $row["line_number"];
          $rce_total_distributed     = $row["total_distributed"];
          $rce_return2               = $row["return2"];
          $rce_sales                 = $row["sales"];
          $rce_send                  = $row["send"];
          $rce_discount              = $row["discount"];
          $rce_nota_ponto            = $row["nota_ponto"];
          $rce_invoice_number        = $row["invoice_number"];
          $rce_id_ce                 = $row["id_ce"];
          $rce_id_ponto              = $row["id_ponto"];

          
          
          gravar_RCE($rce_id,
                     $rce_customercode,
                     $rce_cnpj,
                     $rce_cde_number,
                     $rce_id_product,
                     $rce_id_edition,
                     $rce_edition_number,
                     $rce_id_prod_Planeta,
                     $rce_recall_type, 
                     $rce_recall_date,
                     $rce_line_number,
                     $rce_total_distributed,
                     $rce_return2, $rce_sales,
                     $rce_send,
                     $rce_discount,
                     $rce_nota_ponto,
                     $rce_invoice_number,
                     $rce_id_ce,
                     $rce_id_ponto);
          
          
          
        }
            
        /* free result set */
        $result->close();
    }
        /* close connection */
         $mysqli->commit();
         $mysqli->close();
        
        
     } 
    
// ************************************************************************      
function alterar_status($ce,$customercode,$cnpj){
    // ************************************************************************
    $host1    = $_SESSION['HOST'];
    $user1    = $_SESSION['USER'];
    $pass1    = $_SESSION['PASS'];
    $dbname1  = $_SESSION['DBNAME'];  
    
    $servername = $host1;
    $username   = $user1;
    $password   = $pass1;
    $dbname     = $dbname1;
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    date_default_timezone_set('America/Sao_Paulo');
    $date = date('Y-m-d H:i:s');
    
    
    $sql = "update artigos set status ='F' where cde_number = " . $ce . " and customercode = " . $customercode . " and cnpj = " . $cnpj  ;
    $sql = "update artigos set status ='F' , modified = '" . $date . "' where cde_number = " . $ce . " and customercode = " . $customercode . " and cnpj = " . $cnpj   ;
    
    
    if ($conn->query($sql) === TRUE) {
        echo "   record atualizados  successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    /* commit transaction */
    $conn->commit();
    
    $conn->close();
  }      
// ************************************************************************      
function incluir_rce($rce_id_product,
                     $rce_id_collection, 
                     $rce_id_edition ,
                     $rce_edition_number,
                     $rce_id_prod_Planeta,
                     $rce_customercode,
                     $rce_cnpj,
                     $rce_cde_number,
                     $rce_uid,
                     $rce_return_quantity,
                     $rce_sales_quantity,
                     $rce_calculated_value,
                     $rce_discount_calculated_value,
                     $rce_id_order,
                     $rce_order_date,
                     $rce_nota_ponto,
                     $rce_recall_type,
                     $rce_discount,
                     $rce_price,
                     $rce_total_distributed,
                     $rce_id_ce,
                     $rce_id_ponto
        
         ){
    // ************************************************************************
    $host1    = $_SESSION['HOST'];
    $user1    = $_SESSION['USER'];
    $pass1    = $_SESSION['PASS'];
    $dbname1  = $_SESSION['DBNAME'];  
    
    $servername = $host1;
    $username   = $user1;
    $password   = $pass1;
    $dbname     = $dbname1;
    
    // Create connection
    $conn_rce = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn_rce->connect_error) {
        die("Connection failed: " . $conn_rce->connect_error);
    }
  
    $sql = "insert into carousels (id_product,id_collection,id_edition,
        edition_number,id_prod_Planeta,customercode,cnpj,cde_number,uid,
        return_quantity,sales_quantity,calculated_value,discount_calculated_value,
        id_order,order_date,nota_ponto,recall_type,discount,price,total_distributed,id_ce,id_ponto)
  

    VALUES ('" 
               .  $rce_id_product . "','"
               .  $rce_id_collection . "','"
               .  $rce_id_edition . "','"
               .  $rce_edition_number . "','"
               .  $rce_id_prod_Planeta . "','"
               .  $rce_customercode . "','"
               .  $rce_cnpj . "','"
               .  $rce_cde_number . "','"
               .  $rce_uid . "','"
               .  $rce_return_quantity . "','" 
               .  $rce_sales_quantity . "','" 
               .  $rce_calculated_value . "','"
               .  $rce_discount_calculated_value . "','" 
               .  $rce_id_order . "','"
               .  $rce_order_date . "','"
               .  $rce_nota_ponto . "','"
               .  $rce_recall_type . "','"
               .  $rce_discount . "','"
               .  $rce_price . "','"
               .  $rce_total_distributed  . "','"
               .  $rce_id_ce  . "','"
               .  $rce_id_ponto  
            
            .  "')";
    
    
    
    
    if ($conn_rce->query($sql) === TRUE) {
        echo "   record atualizados  successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn_rce->error;
    }
    
    /* commit transaction */
    $conn_rce->commit();
    
    $conn_rce->close();
    
    
  }       
          
                                                       
// **************************************************************************       
function gravar_RCE(   $rce_id,
                       $rce_customercode,
                       $rce_cnpj ,
                       $rce_cde_number, 
                       $rce_id_product, 
                       $rce_id_edition, 
                       $rce_edition_number, 
                       $rce_id_prod_Planeta, 
                       $rce_recall_type, 
                       $rce_recall_date, 
                       $rce_line_number, 
                       $rce_total_distributed, 
                       $rce_return2, 
                       $rce_sales, 
                       $rce_send, 
                       $rce_discount, 
                       $rce_nota_ponto, 
                       $rce_invoice_number,
                       $rce_id_ce,
                       $rce_id_ponto
         
         ){    
    $host1    = $_SESSION['HOST'];
    $user1    = $_SESSION['USER'];
    $pass1    = $_SESSION['PASS'];
    $dbname1  = $_SESSION['DBNAME'];  
    
    $servername = $host1;
    $username   = $user1;
    $password   = $pass1;
    $dbname     = $dbname1;

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // pesquisar tabela de produtos

               $servername = $host1;
               $username   = $user1;
               $password   = $pass1;
               $dbname     = $dbname1;
 
               // Create connection
               $conn2 = new mysqli($servername, $username, $password, $dbname);
               // Check connection
               if ($conn2->connect_error) {
                  die("Connection failed: " . $conn2->connect_error);
               }
               
               $sql     =  "select"
                         . " id_product,"
                         . " id_collection ,"
                         . " id_edition, "
                         . " edition_number, "
                         . " id_edition, "
                         . " edition_number, "
                         . " id_prod_Planeta, "
                         . " description, "
                         . " price, "
                         . " reordable, "
                         . " returnable, "
                         . " packet "
                         . "from categorias_artigos"
                         . " where id_prod_Planeta = '" . $rce_id_prod_Planeta . "' and edition_number = '" . $rce_edition_number . "'"; 
						 
						 //MMC . " where id_prod_Planeta = '" . $rce_id_prod_Planeta . "'"; 
               
               // echo $sql; 
               
               if ($result = $conn2->query($sql)) {

               /* fetch associative array */
               while ($row = $result->fetch_assoc()) {
        
              
              $descricao      =  $row["description"];
              $precocapa      =  $row["price"];
              $packet         =  $row["packet"];
              $id_collection  = $row["id_collection"];
               } 
               }
               /* commit transaction */
               $conn2->commit();
    
               $conn2->close(); 
     
                // ***********************************************************
    
                // vem da tabela de produtos
                $rce_id_collection=$id_collection; 
                // vem da tabela de produtos 
                $rce_uid=$rce_customercode;
                $rce_return_quantity=$rce_return2;
     
                IF ($rce_recall_type == "NORMAL") {
                    $rce_sales_quantity = $rce_total_distributed-$rce_return2; 
                } else {
     
                IF ($rce_recall_type == "NORMAL                                            ") {
                    $rce_sales_quantity = $rce_total_distributed-$rce_return2; 
                } else {
                  $rce_sales_quantity = $rce_sales - $rce_return2; 
                }                   
                }
         
                $precovenda = $precocapa * $rce_sales_quantity;
                $valor_venda=$valor_venda+$precovenda;
     
                $precodesconto = ($precovenda * $rce_discount) / 100;
                $valor_desconto= $precodesconto;
                $desconto= $desconto+$valor_desconto;
     
          
                 $rce_calculated_value=$precovenda;
     
                 $rce_discount_calculated_value=$precodesconto;
     
                 $rce_id_order=0;
     
                 $rce_order_date=$rce_recall_date;
     
                 $rce_price=$precocapa;
     
                 trim($rce_id_product);
                 trim($rce_id_collection);
                 trim($rce_id_edition);
                 trim($rce_edition_number);
                 trim($rce_id_prod_Planeta);
                 trim($rce_customercode);
                 trim($rce_cnpj);
                 trim($rce_cde_number);
                 trim($rce_uid);
                 trim($rce_return_quantity); 
                 trim($rce_sales_quantity); 
                 trim($rce_calculated_value);
                 trim($rce_discount_calculated_value); 
                 trim($rce_id_order);
                 trim($rce_order_date);
                 trim($rce_nota_ponto); 
                 trim($rce_recall_type);
                 trim($rce_discount);
                 trim($rce_price);
                 trim($rce_id_ce);
                 trim($rce_id_ponto);
     
     
    $sql = "insert into carousels (id_product,id_collection,id_edition,
        edition_number,id_prod_Planeta,customercode,cnpj,cde_number,uid,
        return_quantity,sales_quantity,calculated_value,discount_calculated_value,
        id_order,order_date,nota_ponto,recall_type,discount,price,total_distributed,id_ce,id_ponto)
  

    VALUES ('" 
               .  $rce_id_product . "','"
               .  $rce_id_collection . "','"
               .  $rce_id_edition . "','"
               .  $rce_edition_number . "','"
               .  $rce_id_prod_Planeta . "','"
               .  $rce_customercode . "','"
               .  $rce_cnpj . "','"
               .  $rce_cde_number . "','"
               .  $rce_uid . "','"
               .  $rce_return_quantity . "','" 
               .  $rce_sales_quantity . "','" 
               .  $rce_calculated_value . "','"
               .  $rce_discount_calculated_value . "','" 
               .  $rce_id_order . "','"
               .  $rce_order_date . "','"
               .  $rce_nota_ponto . "','"
               .  $rce_recall_type . "','"
               .  $rce_discount . "','"
               .  $rce_price . "','"
               .  $rce_total_distributed . "','"
               .  $rce_id_ce . "','"
               .  $$rce_id_ponto 
            
            
            .  "')";
    
            // $sql= "insert into carousels (id_product) values (10)";
    
            if ($conn->query($sql) === TRUE) {
                echo "   New record created successfully";
                
                 $texto = $rce_id_product . ";"
               .  $rce_id_collection . ";"
               .  $rce_id_edition . ";"
               .  $rce_edition_number . ";"
               .  $rce_id_prod_Planeta . ";"
               .  $rce_customercode . ";"
               .  $rce_cnpj . ";"
               .  $rce_cde_number . ";"
               .  $rce_uid . ";"
               .  $rce_return_quantity . ";" 
               .  $rce_sales_quantity . ";" 
               .  $rce_calculated_value . ";"
               .  $rce_discount_calculated_value . ";" 
               .  $rce_id_order . ";"
               .  $rce_order_date . ";"
               .  $rce_nota_ponto . ";"
               .  $rce_recall_type . ";"
               .  $rce_discount . ";"
               .  $rce_price . ";"
               .  $rce_total_distributed . ";"
               .  $rce_id_ce . ";"
               .  $rce_id_ponto . " \r\n"; 
     
                // *************************** 
                   gravar_rce_txt($texto);
                // ****************************     
                
                
                
                
                
                
           } else {
             echo "Error: " . $sql . "<br>" . $conn->error;
          }
    
            
  
          
          $conn->commit();
          $conn->close();

    
  }   

function gravar_rce_txt($texto){
    //Variável arquivo armazena o nome e extensão do arquivo.
    
    
     
    $arquivo = "../adm/ftp/retorno/rce.txt";
    
   
    $caminho = "../adm/ftp/retorno/";
    
    
    $arquivo = $caminho . "RCE_" . trim($_SESSION['ce']) . "_" .trim($_SESSION['customercode']) .  ".txt" ;
    
    echo $arquivo; 
    
    //Variável $fp armazena a conexão com o arquivo e o tipo de ação.
    $fp = fopen($arquivo, "a+");
 
    //Escreve no arquivo aberto.
    fwrite($fp, $texto);
     
    //Fecha o arquivo.
    fclose($fp);
}
    
function carregar(){    
  // ler carregar arquivo txt tabulado

$handle = fopen("ftp/remessa/201816_clientes.txt", "r"); //abrir apenas para leitura
if ($handle) {
    while (($linha = fgets($handle)) !== false) {
        $partes = explode(';',$linha); // separa o que tiver antes e depois do ponto e vírgula
        echo $partes[0]; // imprimindo as partes para ver o que tem dentro 
        echo $partes[1]; // imprimindo as partes para ver o que tem dentro 
        echo $partes[2]; // imprimindo as partes para ver o que tem dentro 
        echo $partes[3]; // imprimindo as partes para ver o que tem dentro 
        echo $partes[4]; // imprimindo as partes para ver o que tem dentro 
        
       
        /* AQUI você insere suas QUERYs MySQL usando as partes coletadas */
       
    }
} else {
    // caso de erro insira algo aqui
} 
fclose($handle);
    
}    
 
function pesquisar_produtos(){    
  
    $host1    = $_SESSION['HOST'];
    $user1    = $_SESSION['USER'];
    $pass1    = $_SESSION['PASS'];
    $dbname1  = $_SESSION['DBNAME']; 
    
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "pdd";
    
    $servername = "mysql.planetadeadistribuidor.com.br";
    $username = "planetadeadist";
    $password = "Planeta2018";
    $dbname = "planetadeadist";
    
    $servername = $host1;
    $username   = $user1;
    $password   = $pass1;
    $dbname     = $dbname1;
    
    

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    /* check connection */
        if (mysqli_connect_error()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
        }
    $rce_id_prod_Planeta = '273E101';
    
     $query     =   "select"
                 . " id_product,"
                 . " id_collection ,"
                 . " id_edition, "
                 . " edition_number, "
                 . " id_edition, "
                 . " edition_number, "
                 . " id_prod_Planeta, "
                 . " description, "
                 . " price, "
                 . " reordable, "
                 . " returnable, "
                 . " packet "
                 . "from categorias_artigos"
                . " where id_prod_Planeta = " . $rce_id_prod_Planeta; 
     
      echo $query; 
        
        if ($result = $mysqli->query($query)) {

        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
        
          // printf ("%s (%s)\n", $row["id_prod_planeta"], $row["id_prod_planeta"]);
          echo "<br />" ; 
          echo $row["id_collection"];
          echo "<br />" ; 
          echo $row["description"];
        }

    /* free result set */
        $result->close();
        }    

        /* close connection */
         $mysqli->close();
    

}








?>
    

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" class="btn btn-warning" value="Alterar" name="SendEditArtigo">
            </div>
        </div>
    </form>
</div>
