<?php

  $debugin        = $decoded['debug'];
  $usr_id         = $decoded['usr_id'];
  $tienda_id      = $decoded['tienda_id'];
  $articulo_id    = $decoded['articulo_id'];
  $cantidad       = $decoded['cantidad'];
  $fechahoy       = date('Y-m-d H:i:s');

  if( $usr_id ){

    //User
    $Query = "
      SELECT
        usr.id
      FROM usuarios_app usr
      WHERE
        usr.id = '$usr_id'
        AND usr.activo = '1'
    ";
    $Result = mysqli_query($mysqli, $Query);
    $Usr = mysqli_fetch_assoc($Result);
    if( $Usr[id] ){

      if( $tienda_id && $articulo_id && $cantidad ){

        //Verifica si Exsite carrito activo
        $Query = "
          SELECT
            cart.id
          FROM articulos_pedidos cart
          WHERE
            cart.id != '0'
            ANd cart.fk_usuario = '$Usr[id]'
            AND cart.fk_estatus = '1'
            ORDER BY cart.id DESC
            LIMIT 1
        ";
        $Result = mysqli_query($mysqli, $Query);
        $Cart = mysqli_fetch_assoc($Result);
        if( $Cart[id] ){
          $cart_id = $Cart[id];
        }else{

          //Insert Cart
          $Query = "
            INSERT INTO articulos_pedidos
            (
              fk_usuario, fk_tienda,
              fecha, fk_estatus
            )
            VALUES (
              '$Usr[id]', '$tienda_id',
              '$fechahoy', '1'
            )
          ";
          $Result = mysqli_query($mysqli, $Query);
          $cart_id = mysqli_insert_id($mysqli);

        }

        //Articulo
        $Query = "
          SELECT
            art.id, art.nombre, art.codigo
          FROM articulos art
          WHERE
            art.id != '0'
            ANd art.id = '$articulo_id'
            AND art.activo = '1'
        ";
        $Result = mysqli_query($mysqli, $Query);
        $Art = mysqli_fetch_assoc($Result);
        if( $Art[id] ){

          //Si ya se había seleccionado algun articulo anterior igual
          $Query = "
            SELECT
              art.id, art.cantidad
            FROM articulos_pedidos_articulos art
            WHERE
              art.id != '0'
              ANd art.fk_pedido = '$cart_id'
              AND art.fk_articulo = '$Art[id]'
          ";
          $Result = mysqli_query($mysqli, $Query);
          $ArtExist = mysqli_fetch_assoc($Result);
          if( $ArtExist[id] ){
            $cantidad = $cantidad + $ArtExist[cantidad];
          }

          //Precio en rango
          $Query = "
            SELECT
              pre.id, pre.precio
            FROM articulos_precios pre
            WHERE
              pre.id != '0'
              ANd pre.fk_articulo = '$Art[id]'
              AND ( '$cantidad' BETWEEN pre.rango_a AND pre.rango_b )
          ";
          $Result = mysqli_query($mysqli, $Query);
          $Precio = mysqli_fetch_assoc($Result);
          if( $Precio[id] ){

            $Total = $cantidad * $Precio[precio];

            if( $ArtExist[id] ){

              $cart_art_id = $ArtExist[id];

              //Actualiza Articulo en Pedido
              $Query = "
                UPDATE articulos_pedidos_articulos
                SET
                  cantidad  = '$cantidad',
                  precio    = '$Precio[precio]',
                  total     = '$Total'
                WHERE id = '$ArtExist[id]'
              ";
              $Result = mysqli_query($mysqli, $Query);

            }else{

              //Insert Articulo - Cart
              $Query = "
                INSERT INTO articulos_pedidos_articulos
                (
                  fk_pedido, fk_articulo, codigo,
                  nombre, cantidad,
                  precio, total
                )
                VALUES (
                  '$cart_id', '$Art[id]', '$Art[codigo]',
                  '$Art[nombre]', '$cantidad',
                  '$Precio[precio]', '$Total'
                )
              ";
              $Result = mysqli_query($mysqli, $Query);
              $cart_art_id = mysqli_insert_id($mysqli);

            }

            if( $cart_art_id ){

              //Suma Total
              $Query = "
                SELECT
                  SUM(ped.total) AS Total
                FROM articulos_pedidos_articulos ped
                WHERE
                  ped.id != '0'
                  AND ped.fk_pedido = '$cart_id'
              ";
              $Result = mysqli_query($mysqli, $Query);
              $Total = mysqli_fetch_assoc($Result);

              //Actualiza Total en Pedido
              $Query = "
                UPDATE articulos_pedidos
                SET
                  fk_tienda = '$tienda_id',
                  total     = '$Total[Total]',
                  fecha     = '$fechahoy'
                WHERE id = '$cart_id'
              ";
              $Result = mysqli_query($mysqli, $Query);

              $Data = array(
                'action'        => 'ok',
                'pedido_id'     => "$cart_id"
              );
              echo json_encode($Data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

            }else{

              //Error
              $Query = "
                SELECT
                  err.Id, err.error, err.msn
                FROM api_errores err
                WHERE err.error = 'er-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{

            //Error
            $Query = "
              SELECT
                err.Id, err.error, err.msn
              FROM api_errores err
              WHERE err.error = 'er-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{

          //Error
          $Query = "
            SELECT
              err.Id, err.error, err.msn
            FROM api_errores err
            WHERE err.error = 'er-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{

        //Error
        $Query = "
          SELECT
            err.Id, err.error, err.msn
          FROM api_errores err
          WHERE err.error = 'er-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{

      //Error
      $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);

    }

  }

?>
