/**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Request $request)
 {
     // DB::transaction(function(){
     try {
         DB::beginTransaction();
         $comprobante_compra = $request->get('comprobante_compra');
         $comprobante_servicio = $request->get('comprobante_servicio');
         // dd($comprobante_servicio);
         foreach ($comprobante_compra as $key1 => $value1) {
             $asociar = new AsociarComprobante();
             $asociar->id_comprobanteVenta = $value1['id_comprobanteVenta'];
             $asociar->id_comprobanteCompra = $value1['id_comprobanteCompra'];
             $asociar->id_producto = $value1['id_producto'];
             $asociar->precio_compra = $value1['precio_compra'];
             $asociar->cantidad_compra = $value1['cantidad_compra'];
             $asociar->precio_venta = $value1['precio_venta'];
             $asociar->cantidad_venta = $value1['cantidad_venta'];
             $asociar->save();
             $id_cabecera = $asociar->id;
             $compra = ComprobanteDetalleCompra::find($value1['id_comprobanteDetalleCompra']);
             $compra->indicador_asociado = 'false';
             $compra->save();
             foreach ($comprobante_servicio as $key2 => $value2) {
                 if ($value1['id_producto'] == $value2['id_producto']) {
                     $AsociarComprobante = AsociarComprobante::find($id_cabecera);
                     $AsociarComprobante->id_comprobanteServicio = $value2['id_comprobanteServicio'];
                     $AsociarComprobante->precio_servicio = $value2['precio_servicio'];
                     $AsociarComprobante->cantidad_servicio = $value2['cantidad_servicio'];
                     $AsociarComprobante->save();
                     $servicio = ComprobanteDetalleServicio::find($value2['id_comprobanteDetalleServicio']);
                     $servicio->indicador_asociado = 'false';
                     $servicio->save();
                 }
             }
         }
         DB::commit();
         return \Response::json(array('datos' => 'correcto'));
     } catch (Exception $e) {
         DB::rollBack();
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Request $request)
 {
     $tipo_cambio_compra_hoy = DB::table('ts_tipocambiomoneda')->where('fecha', date("Y-m-d"))->pluck('valor_venta');
     $id_igv = DB::table('ts_igv')->where('estado', 'true')->pluck('id');
     $incluido_igv_activo = DB::table('ts_igv')->where('estado', 'true')->pluck('valor_igv');
     // DB::transaction(function(){
     try {
         DB::beginTransaction();
         $cabecera = $request->get('cabecera');
         $cabecera_guia = $request->get('cabecera_guia');
         $filtro_existencia = '';
         // FILTRO --- EXISTE OTRO COMPROBANTE CON LA MISMA SERIE, NUMERO, PROVEEDOR Y FECHA
         if (DB::table('ts_comprobantecompra')->where('serie_comprobante', $cabecera['serie'])->where('numero_comprobante', $cabecera['numero'])->where('id_proveedor', $cabecera['cliente']['id'])->where('fecha', $cabecera['fecha'])->pluck('id') != null) {
             $filtro_existencia = 'EXISTE';
         }
         // FIN FILTRO --- EXISTE OTRO COMPROBANTE CON LA MISMA SERIE, NUMERO, PROVEEDOR Y FECHA
         if ($filtro_existencia == 'EXISTE') {
             // EXISTE COMPROBANTE DE COMPRA, NO GUARDAMOS NADA
             return \Response::json(array('datos' => 'duplicidad'));
         } else {
             //SE EJECUTA NORMALMENTE PORQUE NO EXISTE COMPROBANTE DE COMPRA
             $boolean_incluido_igv;
             if ($cabecera['incluido_igv'] === 'undefined' || $cabecera['incluido_igv'] === null) {
                 $boolean_incluido_igv = false;
             } else {
                 $boolean_incluido_igv = $cabecera['incluido_igv'];
             }
             $nuevaCabecera = new ComprobanteCompra();
             $nuevaCabecera->id_tipoComprobante = 1;
             $nuevaCabecera->serie_comprobante = $cabecera['serie'];
             $nuevaCabecera->numero_comprobante = $cabecera['numero'];
             $nuevaCabecera->fecha = $cabecera['fecha'];
             $nuevaCabecera->id_moneda = $cabecera['moneda']['id'];
             $nuevaCabecera->id_proveedor = $cabecera['cliente']['id'];
             $nuevaCabecera->id_igv = $id_igv;
             // $nuevaCabecera->indicador_asociado = 'true';
             $nuevaCabecera->estado_igv = json_encode($boolean_incluido_igv);
             $nuevaCabecera->total_comprobante = $cabecera['total'];
             $nuevaCabecera->save();
             $id_cabecera = $nuevaCabecera->id;
             // dd($cabecera_guia);
             foreach ($cabecera_guia as $key => $value) {
                 if ($cabecera_guia[$key]['generar_guia'] == true) {
                     // REGISTRAR CABECERA GUIAREMISION
                     $nuevaCabecera_guia = new GuiaRemision();
                     $nuevaCabecera_guia->id_tipoComprobante = 3;
                     $nuevaCabecera_guia->serie_guiaRemision = $cabecera_guia[$key]['serie'];
                     $nuevaCabecera_guia->numero_guiaRemision = $cabecera_guia[$key]['numero'];
                     $nuevaCabecera_guia->fecha_traslado = $cabecera_guia[$key]['fecha'];
                     $nuevaCabecera_guia->punto_partida = $cabecera_guia[$key]['punto_partida'];
                     $nuevaCabecera_guia->id_proveedor = $cabecera['cliente']['id'];
                     $nuevaCabecera_guia->id_motivoTraslado = $cabecera_guia[$key]['motivo']['id'];
                     $nuevaCabecera_guia->id_personalTransporte = $cabecera_guia[$key]['personal_transporte']['id'];
                     $nuevaCabecera_guia->id_unidad_Transporte = $cabecera_guia[$key]['unidad_transporte']['id'];
                     $nuevaCabecera_guia->id_comprobanteCompra = $id_cabecera;
                     $nuevaCabecera_guia->save();
                     $id_cabecera_guia = $nuevaCabecera_guia->id;
                     foreach ($cabecera_guia[$key]['detalle_guia'] as $key_guia => $value_guia) {
                         // REGISTRAR DETALLE DE GUIA
                         $nuevaDetalle_guia = new GuiaRemisionDetalle();
                         $nuevaDetalle_guia->id_guiaRemision = $id_cabecera_guia;
                         $nuevaDetalle_guia->id_producto = $value_guia['id_producto'];
                         if ($value_guia['producto'] != $value_guia['nombre_producto']) {
                             $nuevaDetalle_guia->nombre_producto = $value_guia['nombre_producto'];
                         }
                         $nuevaDetalle_guia->unidades = $value_guia['cantidad'];
                         $nuevaDetalle_guia->peso = $value_guia['peso'];
                         $nuevaDetalle_guia->save();
                     }
                 }
             }
             $detalle = $request->get('detalle');
             foreach ($detalle as $key => $value) {
                 $nuevaDetalle = new ComprobanteDetalleCompra();
                 $nuevaDetalle->id_comprobante = $id_cabecera;
                 $nuevaDetalle->id_producto = $value['id_producto'];
                 if (DB::table('ts_producto')->where('id', $value['id_producto'])->pluck('nombre_producto') != $value['nombre_producto']) {
                     $nuevaDetalle->nombre_producto = $value['nombre_producto'];
                 }
                 $nuevaDetalle->unidades = $value['cantidad'];
                 $nuevaDetalle->precio_unitario = $value['precio'];
                 $nuevaDetalle->save();
                 $producto = Producto::find($value['id_producto']);
                 // APLICANDO IGV INCLUIDO A PRECIO UNITARIO DE PRODUCTO
                 if ($cabecera['incluido_igv'] == true) {
                     $valor_dividir = $incluido_igv_activo + 1;
                     $value['precio'] = $value['precio'] / $valor_dividir;
                 }
                 // TRANSFORMANDO PRECIO UNITARIO - DE DOLARES A SOLES
                 if ($cabecera['moneda']['id'] == 2) {
                     $value['precio'] = $value['precio'] * $tipo_cambio_compra_hoy;
                 }
                 if ($producto->stock == null) {
                     $producto->stock = $value['cantidad'];
                     $producto->precio_unitario = $value['precio'];
                 } else {
                     // dd($value);
                     $producto->precio_unitario = ($producto->precio_unitario * $producto->stock + $value['precio'] * $value['cantidad']) / ($producto->stock + $value['cantidad']);
                     $producto->stock = $producto->stock + $value['cantidad'];
                 }
                 $producto->save();
             }
             // GUARDANDO DETALLE DE NOTA
             $nota = $request->get('nota');
             if ($nota['tipo_nota']['id'] != null) {
                 $total_final = $nota['total_nota'];
                 $nuevaNota = new DetalleNota();
                 $nuevaNota->id_tipoNota = $nota['tipo_nota']['id'];
                 $nuevaNota->id_comprobanteCompra = $id_cabecera;
                 $nuevaNota->id_moneda = $cabecera['moneda']['id'];
                 $nuevaNota->serie_nota = $nota['serie_comprobante'];
                 $nuevaNota->numero_nota = $nota['numero_comprobante'];
                 $nuevaNota->fecha = $cabecera['fecha'];
                 $nuevaNota->descripcion = $nota['descripcion_nota'];
                 $nuevaNota->precio = $nota['precio_nota'];
                 $nuevaNota->total_nota = $nota['total_nota'];
                 $nuevaNota->save();
             }
             // dd($request->get('finanzas'));
             // GUARDANDO DETALLE DE FINANZAS
             $finanzas = $request->get('finanzas');
             if ($finanzas['condicion']['id'] == 2) {
                 //EN LETRAS
                 // dd($finanzas);
                 // INICIALIZANDO LA FECHA DE INICIO LA DEL COMPROBANTE
                 $fecha = date($cabecera['fecha']);
                 foreach ($finanzas['detalles_letra'] as $key => $value) {
                     // CALCULANDO LA FECHA DE VENCIMIENTO PARA CADA LETRA
                     $fecha = date($cabecera['fecha']);
                     $fecha = strtotime('+' . round($value['numero_dias']) . ' day', strtotime($fecha));
                     $fecha = date('Y-m-j', $fecha);
                     $detallePago = new DetallePago();
                     // $detallePago->id_comprobanteCompra = $id_cabecera;
                     $detallePago->id_condicion_pago = $finanzas['condicion']['id'];
                     $detallePago->id_medio_pago = $finanzas['medio']['id'];
                     $detallePago->id_estado_letra = 4;
                     $detallePago->numero_dias = $value['numero_dias'];
                     $detallePago->numero_letra = $value['numero_letra'];
                     $detallePago->monto_letra = $value['monto_letra'];
                     $detallePago->fecha_vencimiento = $fecha;
                     $detallePago->detalle_estado = "";
                     $detallePago->save();
                     $RelacionLetras = new RelacionLetras();
                     $RelacionLetras->id_comprobanteCompra = $id_cabecera;
                     $RelacionLetras->id_detalle_pago = $detallePago->id;
                     $RelacionLetras->total_facturas = $total_final;
                     $RelacionLetras->save();
                 }
             }
             if ($finanzas['condicion']['id'] == 1) {
                 // AL CONTADO
                 $detallePago = new DetallePago();
                 $detallePago->id_comprobanteCompra = $id_cabecera;
                 $detallePago->id_condicion_pago = $finanzas['condicion']['id'];
                 $detallePago->id_medio_pago = $finanzas['medio']['id'];
                 $detallePago->id_estado_letra = 6;
                 $detallePago->numero_dias = null;
                 $detallePago->numero_letra = null;
                 $detallePago->monto_letra = null;
                 $detallePago->fecha_vencimiento = null;
                 $detallePago->detalle_estado = null;
                 $detallePago->save();
             }
             DB::commit();
             return \Response::json(array('datos' => 'correcto'));
         }
     } catch (Exception $e) {
         DB::rollBack();
     }
     // });
 }