<?php

  if( $Debug == 1 ){
    echo "Edit View";
  }

  $id_user        = $decoded['id_user'];
  $codigo         = $decoded['codigo'];

  if( $id_user || $codigo ){

    $WHERE = "
      WHERE usr.Id != '0'
    ";

    //Id
    if( $id_user ){
      $WHERE .= "
        AND usr.id = '$id_user'
      ";
    }
    //End Id

    //Email
    if( $email ){
      $WHERE .= "
        AND usr.email = '$email'
      ";
    }
    //End Email

    //Cel
    if( $cel ){
      $WHERE .= "
        AND usr.celular = '$cel'
      ";
    }
    //End Cel

    //Valida Usuario
    $Query = "
      SELECT
        usr.id,
        usr.fk_usuario_tipo,
        usr.nombre, usr.apellido_paterno, usr.apellido_materno,
        usr.celular, usr.email, usr.fecha_alta, usr.clave,
        usr.activo
      FROM usuarios_app usr
      $WHERE
    ";
    $Result = mysqli_query($mysqli, $Query);
	  $Usr = mysqli_fetch_assoc($Result);

    if( $Usr[id] ){

      //Valida Codigo
      $Query = "
        SELECT
          cod.id,
          cod.fk_tipo_codigo, cod.codigo
        FROM codigos cod
        WHERE cod.codigo = '$codigo'
      ";
      $Result = mysqli_query($mysqli, $Query);
  	  $CodVal = mysqli_fetch_assoc($Result);
      if( $CodVal[id] ){

        //Cambia estatus de Usuario a Tendero
        if( $CodVal[fk_tipo_codigo] == '1' ){

          //Update
          $Query = "
            UPDATE usuarios_app
            SET
              fk_usuario_tipo = '2'
            WHERE
              id = '$Usr[id]'
          ";
          $Result = mysqli_query($mysqli, $Query);

          $Data = array(
            'action'           => 'ok',
            'id_user'          => "$Usr[id]",
            'msn'              => "Tu usurio ha sido validado correctamente.",
          );
          echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);


        }else{

          $Data = array(
            'action'      => 'error',
            'error'       => 'E-01',
            'error_msn'   => 'Error'
          );
          echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

        }
        //End Cambia estatus de Usuario a Tendero


      }else{

        $Data = array(
          'action'      => 'error',
          'error'       => 'E-01',
          'error_msn'   => 'Error'
        );
        echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

      }
      //End Valida Codigo


    }else{

      $Data = array(
        'action'      => 'error',
        'error'       => 'E-01',
        'error_msn'   => 'Error'
      );
      echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

    }
    //End Valida Usuario

  }else{

    $Data = array(
      'action'      => 'error',
      'error'       => 'E-01',
      'error_msn'   => 'Error'
    );
    echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

  }


?>
