<?php

  if( $Debug == 1 ){
    echo "Add Tienda";
  }

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

  $debugin        = $decoded['debug'];
  $usr_id         = $decoded['usr_id'];
  $tie_id         = $decoded['tienda_id'];
  $usr_clave      = $decoded['usr_clave'];
  $nombre         = $decoded['nombre'];
  $calle          = $decoded['calle'];
  $num_ext        = $decoded['num_ext'];
  $num_int        = $decoded['num_int'];
  $colonia        = $decoded['colonia'];
  $municipio      = $decoded['municipio'];
  $estado         = $decoded['estado'];
  $pais           = $decoded['pais'];
  $codigopostal   = $decoded['codigopostal'];
  $lat            = $decoded['latitud'];
  $lng            = $decoded['longitud'];

  if( $debugin == 1 ){

    echo "Debug-in\n";
    echo $usr_id."\n";
    echo $tie_id."\n";
    echo $nombre."\n";
    echo $calle."\n";
    echo $num_ext."\n";
    echo $num_int."\n";
    echo $colonia."\n";
    echo $municipio."\n";
    echo $estado."\n";
    echo $pais."\n";
    echo $codigopostal."\n";
    echo $lat."\n";
    echo $lng."\n";

  }

  if( $usr_id && $tie_id){

    //Valida Tienda
    $Query = "
      SELECT
        a.Id,
        tie.id AS id_tienda
      FROM usuarios_tiendas a
      LEFT JOIN tiendas tie ON tie.Id = a.fk_tienda
      WHERE
        a.fk_usuario = '$usr_id'
        AND a.fk_tienda = '$tie_id'
    ";
    $Result = mysqli_query($mysqli, $Query);
	  $ValidarTienda = mysqli_fetch_assoc($Result);

    if( $ValidarTienda[id_tienda] ){

      //Actualiza Tienda
      $Query = "
        UPDATE tiendas
        SET
          nombre = '$nombre',
          fk_pais = '$pais',
          fk_estado = '$estado', fk_municipio = '$municipio',
          codigo_postal = '$codigopostal', colonia = '$colonia',
          calle = '$calle', no_exterior = '$num_ext', no_interior = '$num_int',
          lat = '$lat', lng = '$lng'
        WHERE Id = '$ValidarTienda[id_tienda]'
      ";
      $Result = mysqli_query($mysqli, $Query);
      //End Actualiza Tienda

      if( $Result ){ $Done = '1'; }

      if( $Done == '1' ){

        $Data = array(
          'action'    => 'ok',
          'id_tienda'   => "$ValidarTienda[id_tienda]"
        );
        echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

      }else{

        //Error ua-1 ( No se guardo en la BD )
        $Query = "
          SELECT
            err.Id, err.error, err.msn
          FROM api_errores err
          WHERE err.error = 'ta-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);

      }

    }

  }else{

    $Data = array(
      'action' => 'error'
    );
    echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

  }

?>
