<?php

  if( $Debug == 1 ){
    echo "Validate User Tendero";
  }

  $debugin    = $decoded['debug'];
  $id         = $decoded['id'];
  $cel        = $decoded['cel'];
  $email      = $decoded['email'];
  $codigo     = $decoded['codigo'];

  $FechaHoy       = date('Y-m-d H:i:s');

  if( $debugin == 1 ){

    echo "Debug-in\n";
    echo $id."\n";
    echo $cel."\n";

  }

  if( $id || $cel || $email ){

    if( $id ){
      $Where = " usr.id = '$id' ";
    }elseif( $cel ){
      $Where = " usr.celular = '$cel' ";
    }elseif( $cel ){
      $Where = " usr.email = '$email' ";
    }

    //Valida Usuario
    $Query = "
      SELECT
        usr.id
      FROM usuarios_app usr
      WHERE
        $Where
    ";
    $Result = mysqli_query($mysqli, $Query);
    $User = mysqli_fetch_assoc($Result);

    if( $User[id] ){

      //Valida Codigo
      $Query = "
        SELECT
          usr.id
        FROM usuarios_app usr
        WHERE
          $Where
          AND
            (
              usr.codigo = '$codigo'
              OR
              usr.codigo_temp = '778899'
            )
      ";
      $Result = mysqli_query($mysqli, $Query);
      $UserCode = mysqli_fetch_assoc($Result);

      if( $UserCode[id] ){

        //Actualiza Activo
        $Query = "
          UPDATE usuarios_app SET
            activo = '1'
          WHERE
            id = '$User[id]'
        ";
        $Result = mysqli_query($mysqli, $Query);

        $Data = array(
          'action'    => 'ok',
          'id_user'   => $User[id],
          'valido'    => '1'
        );
        echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

      }else{

        //Error uv-2 ( Codigo incorrecto. )
        $Query = "
          SELECT
            err.Id, err.error, err.msn
          FROM api_errores err
          WHERE err.error = 'uv-2'
        ";
        $Result = mysqli_query($mysqli, $Query);
        $Error = mysqli_fetch_assoc($Result);

        $Data = array(
          'action'      => 'error',
          'error'       => $Error[error],
          'error_msn'   => $Error[msn]
        );
        echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

      }

    }else{

      //Error uv-1 ( El Usuario no se encontró. )
      $Query = "
        SELECT
          err.Id, err.error, err.msn
        FROM api_errores err
        WHERE err.error = 'uv-1'
      ";
      $Result = mysqli_query($mysqli, $Query);
      $Error = mysqli_fetch_assoc($Result);

      $Data = array(
        'action'      => 'error',
        'error'       => $Error[error],
        'error_msn'   => $Error[msn]
      );
      echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

    }

  }

?>
