<?php
/*################################################
@author: Code Tecnologia
@date: 23/04/2020
@version: 1.00
@purpose: Classe responsavel por cadastrar um cliente

Resposta esperada:
{ 
"erro": false,
"mensagem":"Cadastro realizado com sucesso. Verifique seu email para validar seu cadastro."
}
*/
  
################################################*/

include_once("connect.php");

    mysqli_query($conexao,"SET NAMES 'utf8'");
    mysqli_query($conexao,'SET character_set_connection=utf8');
    mysqli_query($conexao,'SET character_set_client=utf8');
    mysqli_query($conexao,'SET character_set_results=utf8');



//Funcao para exibir o json
function exibir_json($json){
    $echo_json = json_encode($json);
    $json = array_map('utf8_encode', $json);
  echo $echo_json;
}

//Verificando se a mensagem foi transmitida por POST
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){  
    $status = array(
        'erro' => 'true',
        'mensagem' => 'O formato recebido não é um POST');
    
    //$status = array_map('utf8_encode', $status);
    //$json = json_encode(array_map('utf8_encode', $status));
    
  exibir_json($status);
    exit(0);
}

//Verificando se o Content-type eh 'application/json'
/*
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
    $status = array(
        'erro' => 'true',
        'mensagem' => 'O tipo da mensagem est� incorreto.');
    $json = json_encode($status);
  exibir_json($json);
    exit(0);
}
*/



//recebendo a requisicao
$content = file_get_contents("php://input");
//$content = utf8_encode($content); //evita erros


  //obtendo informacoes do Header da mensagem
/*
  $v_customer_id    = isset($_SERVER["v_customer_id"])  ? trim($_SERVER["v_customer_id"]) : 0;
  $v_locale       = isset($_SERVER["v_locale"])   ? trim($_SERVER["v_locale"])    : '';
  $v_firstname      = isset($_SERVER["v_firstname"])  ? trim($_SERVER["v_firstname"])   : '';
  $v_lastname       = isset($_SERVER["v_lastname"])   ? trim($_SERVER["v_lastname"])    : '';
  $v_email        = isset($_SERVER["v_email"])    ? trim($_SERVER["v_email"])     : '';
  $v_telephone    = isset($_SERVER["v_telephone"])  ? trim($_SERVER["v_telephone"])   : '';
  $v_password       = isset($_SERVER["v_password"])   ? trim($_SERVER["v_password"])    : '';
  $v_ip         = isset($_SERVER["v_ip"])         ? trim($_SERVER["v_ip"])        : '';
  $v_address1       = isset($_SERVER["v_address1"])     ? trim($_SERVER["v_address1"])    : '';
  $v_address2       = isset($_SERVER["v_address2"])   ? trim($_SERVER["v_address2"])    : '';
  $v_city       = isset($_SERVER["v_city"])     ? trim($_SERVER["v_city"])        : 0;
  $v_zipcode      = isset($_SERVER["v_zipcode"])    ? trim($_SERVER["v_zipcode"])     : 0;
  $v_zone_id      = isset($_SERVER["v_zone_id"])    ? trim($_SERVER["v_zone_id"])     : 0;

*/  


  $v_customer_id    = isset($_POST["v_customer_id"])  ? trim($_POST["v_customer_id"])    : 0;
  $v_locale         = isset($_POST["v_locale"])       ? trim($_POST["v_locale"])         : '';
  $v_firstname      = isset($_POST["v_firstname"])    ? trim($_POST["v_firstname"])      : '';
  $v_lastname       = isset($_POST["v_lastname"])     ? trim($_POST["v_lastname"])       : '';
  $v_email          = isset($_POST["v_email"])        ? trim($_POST["v_email"])          : '';
  $v_telephone      = isset($_POST["v_telephone"])    ? trim($_POST["v_telephone"])      : '';
  $v_password       = isset($_POST["v_password"])     ? trim($_POST["v_password"])       : '';
  $v_ip             = isset($_POST["v_ip"])           ? trim($_POST["v_ip"])             : '';
  $v_address1       = isset($_POST["v_address1"])     ? trim($_POST["v_address1"])       : '';
  $v_address2       = isset($_POST["v_address2"])     ? trim($_POST["v_address2"])       : '';
  $v_city           = isset($_POST["v_city"])         ? trim($_POST["v_city"])           : 0;
  $v_zipcode        = isset($_POST["v_zipcode"])      ? trim($_POST["v_zipcode"])        : 0;
  $v_zone_id        = isset($_POST["v_zone_id"])      ? trim($_POST["v_zone_id"])        : 0;
  $v_photo          = isset($_POST["v_photo"])        ? trim($_POST["v_photo"])          : '';

  
  
  //Caso o mobile passe a variavel sem valor para atualizacao.
  if (empty($v_customer_id)){
    $v_customer_id = 0;
  }
  
//    echo "v_customer_id: " . $v_customer_id;
  
  //exit(0);
  //TODO: Se o ID estiver preenchido, UPDATE senao Insert. MESMO NO INSERT CHECAR Email.

/*Checando dados obrigatorios*/  
    if(empty($v_firstname)  
     || empty($v_lastname)                //Comentado pois a Apple nos obrigou a colocar como opcional
     // || empty($agencia)              //Comentado pois a Apple nos obrigou a colocar como opcional
     // || empty($conta)                //Comentado pois a Apple nos obrigou a colocar como opcional
     || empty($v_email) 
     || empty($v_password) 
     // || empty($telefone)             //Comentado pois a Apple nos obrigou a colocar como opcional
     // || empty($tipoconta)            //Comentado pois a Apple nos obrigou a colocar como opcional
     // || empty($favorecido)           //Comentado pois a Apple nos obrigou a colocar como opcional 
     // || empty($documento)            //Comentado pois a Apple nos obrigou a colocar como opcional
    ){
 $status = array(
          'erro' => 'true',
          'mensagem' => 'Alguns dos campos obrigatórios não foram preenchidos (Nome, e-mail ou senha ');

      //$json = json_encode($status);
      //enviarCurl($url,$json);
      exibir_json($status);
      
    }else{
          $v_customer_id    = isset($_POST["v_customer_id"])  ? trim($_POST["v_customer_id"])   : 0;
          $v_locale         = isset($_POST["v_locale"])       ? trim($_POST["v_locale"])        : '';
          $v_firstname      = isset($_POST["v_firstname"])    ? trim($_POST["v_firstname"])     : '';
          $v_lastname       = isset($_POST["v_lastname"])     ? trim($_POST["v_lastname"])      : '';
          $v_email          = isset($_POST["v_email"])        ? trim($_POST["v_email"])         : '';
          $v_telephone      = isset($_POST["v_telephone"])    ? trim($_POST["v_telephone"])     : '';
          $v_password       = isset($_POST["v_password"])     ? trim($_POST["v_password"])      : '';
          $v_ip             = isset($_POST["v_ip"])           ? trim($_POST["v_ip"])            : '';
          $v_address1       = isset($_POST["v_address1"])     ? trim($_POST["v_address1"])      : '';
          $v_address2       = isset($_POST["v_address2"])     ? trim($_POST["v_address2"])      : '';
          $v_city           = isset($_POST["v_city"])         ? trim($_POST["v_city"])          : 0;
          $v_zipcode        = isset($_POST["v_zipcode"])      ? trim($_POST["v_zipcode"])       : 0;
          $v_zone_id        = isset($_POST["v_zone_id"])      ? trim($_POST["v_zone_id"])       : 0;
          $v_photo          = isset($_POST["v_photo"])        ? trim($_POST["v_photo"])         : '';
          
      //$json = json_encode($status);
      //enviarCurl($url,$json);
      //exibir_json($status);

    $sql_verifica = "select count(*) as total from oc_customer where email = '$v_email'";    
   
    $resultado = mysqli_query($conexao, $sql_verifica); // or die ($conexao);
   if (mysqli_num_rows($resultado) > 0) {
     $row = mysqli_fetch_assoc($resultado);
     $registrado = $row['total'];
      if($registrado > 0){
         $status = array(
            'erro' => 'true',
            'mensagem' => 'Usuário já cadastrado!'            
                        );
         exibir_json($status);
         exit();
                         }

      //$json = json_encode($status);
      //enviarCurl($url,$json);  
   }
      

        $v_password = md5($v_password);

    $manter_cliente = "call code_cadastrar_cliente ('$v_customer_id',
                                                    '$v_locale',
                                                    '$v_firstname', 
                                                    '$v_lastname',
                                                    '$v_email',
                                                    '$v_telephone',
                                                    '$v_password',
                                                    '$v_ip',
                                                    '$v_address1',
                                                    '$v_address2',
                                                    '$v_city',
                                                    '$v_zipcode',
                                                    '$v_zone_id',
                                                    '$v_photo');";

                                            //echo $manter_cliente;
                                            //exit;

    


      $result = mysqli_query($conexao, $manter_cliente); // or die ($conexao);    


            $status = array( 'erro' => 'false'
                ,'mensagem' => 'Cadastro realizado com sucesso. Em breve enviaremos um e-mail para que você confirme seu cadastro.'
                   );

            //mysqli_stmt_close($result);

            exibir_json($status);
            
            
            
            if(!empty($v_email)){
        
        $id_cliente_email = base64_encode($v_email);
        $to = $v_email;
        $subject = "Confirmação de e-mail para $v_firstname $v_lastname";
        $message = "

         <!DOCTYPE html>
            <html style='padding: 0px; margin: 0px;' lang='pt_br'>
               <head> 
                   <meta charset='UTF-8' />
                    <style>
                       body{margin:
                            0;padding: 0;
                       }
                       @media only screen and (max-width:640px){
                           table, img[class='partial-image']{
                                width:100% !important;
                                height:auto !important;
                                min-width: 200px !important; 
                       }
                  </style>
               </head>
            <body>
            <table style='border-collapse: collapse; border-spacing:
               0; min-height: 418px;' cellpadding='0' cellspacing='0' width='100%' background='https://images.wallpaperscraft.com/image/wood_surface_texture_boards_118443_1920x1080.jpg');'>
               <tbody>
                  <tr>
                     <td align='center' style='border-collapse: collapse;
                        padding-top: 30px; padding-bottom: 30px;'>
                        <table cellpadding='5' cellspacing='5' width='650' height='400' bgcolor='white' style='border-collapse: collapse;
                           border-spacing: 0; border-radius: 15px;'>
                           <tbody>
                              <tr>
                                 <td style='border-collapse: collapse; padding: 0px;
                                    text-align: center; width: 600px;'>
                                    <table style='border-collapse: collapse;
                                       border-spacing: 0; box-sizing: border-box;
                                       min-height: 40px; position: relative; width:
                                       100%;'>
                                       <tbody>
                                          <tr>
                                             <td style='border-collapse:
                                                collapse; font-family: Arial; padding: 10px
                                                15px;'>
                                                <table width='100%' style='border-collapse: collapse; border-spacing:
                                                   0; font-family: Arial;'>
                                                   <tbody>
                                                      <tr>
                                                         <td style='border-collapse: collapse;'>
                                                            <hr style='border-color: rgb(255,255,255);
                                                               border-style:
                                                               dashed;'>
                                                         </td>
                                                      </tr>
                                                   </tbody>
                                                </table>
                                             </td>
                                          </tr>
                                       </tbody>
                                    </table>
                                    <table style='border-collapse: collapse; border-spacing:
                                       0; box-sizing: border-box; min-height: 40px;
                                       position: relative; width: 100%;'>
                                       <tbody>
                                          <tr>
                                             <td style='border-collapse: collapse; font-family:
                                                Arial; padding: 10px 15px; background:
                                                #fff;'>
                                                <table width='100%' style='border-collapse: collapse; border-spacing:
                                                   0; font-family: Arial;'>
                                                   <tbody>
                                                      <tr>
                                                         <td align='center' style='border-collapse:
                                                            collapse; line-height: 0px; padding: 0;
                                                            mso-line-height-rule: exactly;'><a href='http://saudeesabor.jp' target='_blank' style='display: block; text-decoration: none;
                                                            box-sizing: border-box; font-family: arial; width:
                                                            100%;'><img class='partial-image' width='245' style='box-sizing: border-box;
                                                            display: block; max-width: 600px; min-width:
                                                            160px;' dfsrc='https://saudeesabor.jp/image/cache/catalog/site/logo_saude_sabor2017-260x121.png' src='https://saudeesabor.jp/image/cache/catalog/site/logo_saude_sabor2017-260x121.png'></a></td>
                                                      </tr>
                                                   </tbody>
                                                </table>
                                             </td>
                                          </tr>
                                       </tbody>
                                    </table>
                                    
                                    <table style='border-collapse: collapse;
                                       border-spacing: 0; box-sizing: border-box;
                                       min-height: 40px; position: relative; width: 100%;
                                       font-family: Arial; font-size: 25px;
                                       padding-bottom: 20px; padding-top: 20px;
                                       text-align: center; vertical-align:
                                       middle;'>
                                       <tbody>
                                          <tr>
                                             <td style='border-collapse: collapse; font-family:
                                                Arial; padding: 10px 15px;'>
                                                <table width='100%' style='border-collapse: collapse; border-spacing:
                                                   0; font-family: Arial;'>
                                                   <tbody>
                                                      <tr>
                                                         <td style='border-collapse: collapse;'>
                                                            <h2 style='font-weight: normal; margin: 0px; padding:
                                                               0px; color: #666; word-wrap: break-word;'><a style='display: inline-block; text-decoration:
                                                               none; box-sizing: border-box; font-family: arial;
                                                               width: 100%; font-size: 25px; text-align: center;
                                                               word-wrap: break-word; color: rgb(102,102,102);' target='_blank'><span style='font-size: inherit;
                                                               text-align: center; width: 100%; color: #666;'>Confirma&ccedil;&atilde;o de e-mail</span></a>
                                                            </h2>
                                                         </td>
                                                      </tr>
                                                   </tbody>
                                                </table>
                                             </td>
                                          </tr>
                                       </tbody>
                                    </table>
                                    
                                    
                                    <table style='border-collapse: collapse;
                                       border-spacing: 0; box-sizing: border-box;
                                       min-height: 40px; position: relative; width:
                                       100%;'>
                                       <tbody>
                                          <tr>
                                             <td style='border-collapse:
                                                collapse; font-family: Arial; padding: 10px
                                                15px;'>
                                                <table width='100%' style='border-collapse: collapse; border-spacing:
                                                   0; text-align: left; font-family:
                                                   Arial;'>
                                                   <tbody>
                                                      <tr>
                                                         <td style='border-collapse:
                                                            collapse;'>
                                                            <div style='font-family: Arial;
                                                               font-size: 15px; font-weight: normal; line-height:
                                                               170%; text-align: left; color: #666; word-wrap:
                                                               break-word;'>
                                                               <div style='text-align:
                                                                  center;'><br></div>
                                                               <div style='text-align:
                                                                  center;'>Clique no link abaixo para prosseguir com a confirma&ccedil;&atilde;o do e-mail:<span style='line-height: 0; display:
                                                                     none;'></span><span style='line-height: 0;
                                                                     display:
                                                                     none;'></span>
                                                               </div>
                                                            </div>
                                                         </td>
                                                      </tr>
                                                   </tbody>
                                                </table>
                                             </td>
                                          </tr>
                                       </tbody>
                                    </table>
                                    <table style='border-collapse: collapse;
                                       border-spacing: 0; box-sizing: border-box;
                                       min-height: 40px; position: relative; width: 100%;
                                       padding-bottom: 10px; padding-top:
                                       10px;'>
                                       <tbody>
                                          <tr>
                                             <td style='border-collapse:
                                                collapse; font-family: Arial; padding: 10px 15px;
                                                padding-top: 20px; padding-bottom: 20px;'>
                                                <div style='font-family: Arial; text-align:
                                                   center;'>
                                                   <table style='border-collapse:
                                                      collapse; border-spacing: 0; background-color:
                                                      #63B8FF; border-radius: 10px; color:
                                                      rgb(255,255,255); display: inline-block;
                                                      font-family: Arial; font-size: 15px; font-weight:
                                                      bold; text-align: center;'>
                                                      <tbody style='display:
                                                         inline-block;'>
                                                         <tr style='display:
                                                            inline-block;'>
                                                            <td align='center' style='border-collapse: collapse; display:
                                                               inline-block; padding: 15px 20px;'><a href='http://saudeesabor.codecrm.com.br/confirmar_email.php?id=$id_cliente_email' style='display: inline-block;
                                                               text-decoration: none; box-sizing: border-box;
                                                               font-family: arial; color: #fff; font-size: 15px;
                                                               font-weight: bold; margin: 0px; padding: 0px;
                                                               text-align: center; word-wrap: break-word; width:
                                                               100%;'>Confirmar e-mail</a>
                                                            </td>
                                                         </tr>
                                                      </tbody>
                                                   </table>
                                                </div>
                                             </td>
                                          </tr>
                                       </tbody>
                                    </table>
                                    <table style='border-collapse: collapse;
                                       border-spacing: 0; box-sizing: border-box;
                                       min-height: 40px; position: relative; width: 100%;
                                       display: table;'>
                                       <tbody>
                                          <tr>
                                             <td style='border-collapse:
                                                collapse;'>
                                                <div style='font-family: Arial;
                                                   font-size: 13px; font-weight: normal; line-height:
                                                   170%; text-align: left; color: #666; word-wrap:
                                                   break-word;'>
                                                   <div style='text-align:
                                                      center;'><br></div>
                                                   <div style='text-align:
                                                      center;'><span style='line-height: 0; display:
                                                         none;'></span><span style='line-height: 0;
                                                         display:
                                                         none;'></span>
                                                   </div>
                                                </div>
                                             </td>
                                          </tr>
                                       </tbody>
                                    </table>
                                  </td>
                              </tr>
                           </tbody>
                        </table>
                     </td>
                  </tr>
               </tbody>
            </table>
                    
                                 
            </body>
            </html>
        
        ";
        
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $headers .= 'From: CODE Tecnologia <codecrm@codecrm.com.br>' . "\r\n";

        $sentmail = mail($to,$subject,$message,$headers);
}
     
    //}
                
                //$status = array_map('utf8_encode', $status);
                //$json = json_encode($status);
        
        //Preparando o token
        $token = base64_encode($usuario['id']);
        header("token: $token");
        
             // exibir_json($status);
                exit(0);
       
            }
        
     


?>