public function create(Request $request)
 {
     // var_dump($request->all());die();
     \DB::beginTransaction();
     $saldoTemp = 0;
     $codigoHeadIS = 0;
     $purchase = $this->purchaseRepo->getModel();
     $payment = $this->paymentRepo->getModel();
     $pendientAccount = $this->pendientAccountRepo->getModel();
     $var = $request->detailOrderPurchases;
     $almacen_id = $request->input("warehouses_id");
     if (!empty($request->input("compraDirecta"))) {
         foreach ($var as $object) {
             $stockmodel = new StockRepo();
             $object['warehouse_id'] = $almacen_id;
             $object["variant_id"] = $object["Codigovar"];
             $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
             if (!empty($stockac)) {
                 $object["stockActual"] = floatval($stockac->stockActual) + floatval($object["cantidad"]);
                 //var_dump($object["stockActual"]);die();
                 $manager = new StockManager($stockac, $object);
                 $manager->save();
                 $stock = null;
             } else {
                 $object["stockActual"] = $object["cantidad"];
                 //var_dump($object["stockActual"]);die();
                 $manager = new StockManager($stockRepo->getModel, $object);
             }
             $stockac = null;
         }
     }
     //==================================Cancelar Factura
     if ($request->input('estado') == 2) {
         //var_dump("hola");die();
         foreach ($var as $object) {
             $stockmodel = new StockRepo();
             $object['warehouse_id'] = $almacen_id;
             $object["variant_id"] = $object["Codigovar"];
             $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
             //var_dump($stockac);die();
             if (!empty($stockac)) {
                 $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($object["cantidad"]);
                 $manager = new StockManager($stockac, $object);
                 $manager->save();
                 $stock = null;
             }
             //}
             $stockac = null;
         }
         $orderPurchase = $this->orderPurchaseRepo->find($request->id);
         $ordercompra = new OrderPurchaseManager($orderPurchase, $request->except('fechaPedido', 'fechaPrevista', 'montoBruto', 'montoTotal', 'descuento'));
         $ordercompra->save();
         if ($this->orderPurchaseRepo->validateDate(substr($request->input('fechaPedido'), 0, 10)) and $this->orderPurchaseRepo->validateDate(substr($request->input('fechaPrevista'), 0, 10))) {
             $orderPurchase->fechaPedido = substr($request->input('fechaPedido'), 0, 10);
             $orderPurchase->fechaPrevista = substr($request->input('fechaPrevista'), 0, 10);
         } else {
             $orderPurchase->fechaPedido = null;
             $orderPurchase->fechaPrevista = null;
         }
         $orderPurchase->save();
         $payment1 = $this->paymentRepo->paymentById($request->input('id'));
         $pendientAccount = $this->pendientAccountRepo->getModel();
         //$pendientAcc=$this->pendientAccountRepo->verSaldos($payment1->id);
         if (!empty($payment1)) {
             $detPayment = $this->detPaymentRepo->verPagosAdelantados($payment1->id);
             if (!empty($detPayment)) {
                 foreach ($detPayment as $detPayment) {
                     $request->merge(["estado" => 0]);
                     $SaldosTemporales = $this->pendientAccountRepo->find2($detPayment['Saldo_F']);
                     if ($SaldosTemporales != null) {
                         $request->merge(['Saldo' => $SaldosTemporales->Saldo + $detPayment['montoPagado']]);
                         $request->merge(['orderPurchase_id' => $SaldosTemporales->orderPurchase_id]);
                         $request->merge(['supplier_id' => $SaldosTemporales->supplier_id]);
                         $insercount = new PendientAccountManager($SaldosTemporales, $request->all());
                         $insercount->save();
                     } else {
                         $request->merge(['orderPurchase_id' => $request->input('id')]);
                         $request->merge(['Saldo' => $payment1->Acuenta]);
                         $insercount = new PendientAccountManager($pendientAccount, $request->all());
                         $insercount->save();
                     }
                 }
                 ///================solucion Errores==================================
             } else {
                 $request->merge(['orderPurchase_id' => $request->input('id')]);
                 $request->merge(['Saldo' => $payment1->Acuenta]);
                 $insercount = new PendientAccountManager($pendientAccount, $request->all());
                 $insercount->save();
                 $provicional = $request->idpayment;
             }
             //==========================fin
         }
     } else {
         //===================================UpdateOrderPurchase===========================================
         if ($request->input('estado') == 1) {
             $request->merge(["Estado" => 1]);
             // var_dump($request->input("Estado"));die();
             $orderPurchase = $this->orderPurchaseRepo->find($request->id);
             //var_dump($orderPurchase->Estado);die();
             $ordercompra = new OrderPurchaseManager($orderPurchase, $request->except('fechaPedido', 'fechaPrevista', 'montoBruto', 'montoTotal', 'descuento'));
             $ordercompra->save();
             if ($this->orderPurchaseRepo->validateDate(substr($request->input('fechaPedido'), 0, 10)) and $this->orderPurchaseRepo->validateDate(substr($request->input('fechaPrevista'), 0, 10))) {
                 $orderPurchase->fechaPedido = substr($request->input('fechaPedido'), 0, 10);
                 $orderPurchase->fechaPrevista = substr($request->input('fechaPrevista'), 0, 10);
             } else {
                 $orderPurchase->fechaPedido = null;
                 $orderPurchase->fechaPrevista = null;
             }
             $orderPurchase->save();
             $verSiExiste = $this->detailOrderPurchaseRepo->Comprobar($request->id);
             //***************************************************************
             if (!empty($verSiExiste[0])) {
                 //var_dump("no deve entrar");die();
                 $orderPurchase->detPres()->detach();
                 foreach ($var as $object1) {
                     //$hola=$var[$n];
                     //$object[]
                     $object1["Cantidad_Ll"] = $object1["cantidad1"];
                     $object1["pendiente"] = floatval($object1["cantidad"]) - floatval($object1["cantidad1"]);
                     /*if(!empty($object1["cantidad1"])){
                           //var_dump("holay".$object1["cantidad1"]);die();
                           //$object1["cantidad"]=$object1["Cantidad_Ll"];
                           //$object1["pendiente"]=$object1["pendiente"];
                           $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                           $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                       }else{
                           //var_dump("dos".$object1["cantidad1"]);die();
                         
                           if($object1["Cantidad_Ll"]=='0' && $object1["montoBruto"]=='0'){
                             $object1["Cantidad_Ll"]=0;
                             $object1["pendiente"]=$object1["cantidad"];
                             $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                             $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                           }else{
                               if($object1["Cantidad_Ll"]>0){
                                    $object1["Cantidad_Ll"]=$object1["cantidad"];
                                    $object1["pendiente"]=0;
                                    $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                                    $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                               }else{  
                                    $object1["Cantidad_Ll"]=$object1["cantidad"];
                                    $object1["pendiente"]=0;
                                    $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                                    $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                           }
                         }
                       
                       }*/
                     ////if($hola->cantidad1!=null){
                     ////    $object1["Cantidad_Ll"]=$hola->Cantidad_Ll;
                     ////    $object1["pendiente"]=$hola->pendiente;
                     ////
                     ////}else{
                     ////    $object1["Cantidad_Ll"]=$object1["cantidad"];
                     ////    $object1["pendiente"]=0;
                     ////}
                     //var_dump($hola['Cantidad_Ll']);die();
                     if (floatval($object1["preCompra"]) > 0) {
                         $detailOrderPurchaseRepox = new DetailOrderPurchaseRepo();
                         $insertar = new DetailOrderPurchaseManager($detailOrderPurchaseRepox->getModel(), $object1);
                         $insertar->save();
                         $detailOrderPurchaseRepox = null;
                         //$n++;
                     }
                 }
                 //   var_dump($var);die();
             }
         }
         //==============================================================================
         $codOrder = $request->input("orderPurchase_id");
         $fechaActual = $request->input("fecha");
         //var_dump($fechaActual);die();
         //=============================Creando compra =============================
         //var_dump($var); die();
         $manager = new PurchaseManager($purchase, $request->except('fechaEntrega'));
         $manager->save();
         if ($this->purchaseRepo->validateDate(substr($request->input('fechaEntrega'), 0, 10))) {
             $purchase->fechaEntrega = substr($request->input('fechaEntrega'), 0, 10);
         } else {
             $purchase->fechaEntrega = null;
         }
         $purchase->save();
         $temporal = $purchase->id;
         // return $temporal;
         $request->merge(["purchase_id" => $temporal]);
         $detailPurchaseRepox;
         $consulPayment = null;
         //$almacen_id=$request->input("warehouses_id");
         //========================================================================
         $total = 0;
         foreach ($var as $object) {
             //========================insertDEtalles=========================
             $object['orderPurchase_id'] = $codOrder;
             $object['purchases_id'] = $temporal;
             $object['purchase_id'] = $temporal;
             $object['Fecha'] = $fechaActual;
             $object['warehouse_id'] = $almacen_id;
             $object["variant_id"] = $object["Codigovar"];
             $stockmodel = new StockRepo();
             $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
             if ($request->input('estado') == 1) {
                 // var_dump($object1["cantidad1"]);
                 $cantidadReal = $object["cantidad"];
                 $object["cantidad"] = $object["cantidad1"];
                 if ($request->input("tCambio") == "sol") {
                     //var_dump("hola este es soles");die();
                     $object["montoBruto"] = floatval($object["cantidad1"]) * floatval($object["preProducto"]);
                     $object["montoBrutoDolar"] = floatval($object["montoBruto"]) / floatval($request->input("tasaDolar"));
                     $object["montoTotal"] = floatval($object["cantidad1"]) * floatval($object["preCompra"]);
                     $object["montoTotalDolar"] = floatval($object["montoTotal"]) / floatval($request->input("tasaDolar"));
                     $total = $total + $object["montoTotal"];
                 } else {
                     $object["montoBrutoDolar"] = floatval($object["cantidad1"]) * floatval($object["preProductoDolar"]);
                     $object["montoBruto"] = floatval($object["montoBrutoDolar"]) * floatval($request->input("tasaDolar"));
                     $object["montoTotalDolar"] = floatval($object["cantidad1"]) * floatval($object["preCompraDolar"]);
                     $object["montoTotal"] = floatval($object["montoTotalDolar"]) * floatval($request->input("tasaDolar"));
                     $total = $total + $object["montoTotalDolar"];
                 }
                 //  var_dump($object["cantidad"]);
                 /*if(!empty($object["cantidad1"])){
                           $object["cantidad"]=$object["Cantidad_Ll"];
                        }else{
                          if($object["preCompra"]==0){
                                  $object["cantidad"]=$object["cantidad"];
                            }else{
                                  if($object["Cantidad_Ll"]==0 && $object["montoBruto"]==0)
                                  {
                                     $object["cantidad"]=$object["Cantidad_Ll"];
                                  }else{
                                   //if(floatval($object["Cantidad_Ll"])>0){
                                   //   $object["cantidad"]=$object["Cantidad_Ll"]; 
                                   //}else{
                                     $object["cantidad"]=$object["cantidad"];
                                   //}
                              }
                        }
                   }**/
                 //***************************************************
                 // $stockmodel = new StockRepo;
                 //$object['warehouse_id']=$almacen_id;
                 //$object["variant_id"]=$object["Codigovar"];
                 //$stockac=$stockmodel->encontrar($object["variant_id"],$almacen_id);
                 $cantidaCalculada = floatval($object["cantidad1"]) - floatval($object["Cantidad_Ll"]);
                 if ($cantidaCalculada < 0) {
                     $cantidaCalculada = floatval($cantidaCalculada * -1);
                 }
                 /*
                                   if(!empty($object["cantidad1"])){
                                       $cantidaCalculada=floatval($object["cantidad1"])-floatval($object["Cantidad_Ll"]);
                                   }else{ 
                                     if($object["preCompra"]==0){
                                           $cantidaCalculada=floatval($object["cantidad"]);
                                     }else{
                                          if($object["Cantidad_Ll"]==0 && $object["montoBruto"]==0){
                                                $cantidaCalculada=0;
                                           }else{
                                          $cantidaCalculada=floatval($object["cantidad"])-floatval($object["Cantidad_Ll"]);
                                           }
                                     }
                                   }*/
                 //*****************ssss*************************
             } else {
                 $stockmodel = new StockRepo();
                 $object['warehouse_id'] = $almacen_id;
                 $object["variant_id"] = $object["Codigovar"];
                 $cantidaCalculada = $object["cantidad"];
             }
             //$object["cantidad"]=$cantidaCalculada;
             if (intval($object["cantidad"] > 0)) {
                 //var_dump($object);die();
                 $detailPurchaseRepox = new DetailPurchaseRepo();
                 $insertar = new DetailPurchaseManager($detailPurchaseRepox->getModel(), $object);
                 $insertar->save();
                 $detailPurchaseRepox = null;
             }
             if ($request->input('estado') == 1) {
                 $purchase1 = $this->purchaseRepo->find($temporal);
                 if ($request->input("tCambio") == "sol") {
                     $request->merge(['montoBruto' => floatval($total)]);
                     $request->merge(['montoBrutoDolar' => floatval($total) / floatval($request->input("tasaDolar"))]);
                 } else {
                     $request->merge(['montoBrutoDolar' => floatval($total)]);
                     $request->merge(['montoBruto' => floatval($total) * floatval($request->input("tasaDolar"))]);
                 }
                 if (!empty($purchase1->descuento)) {
                     if ($request->input("tCambio") == "sol") {
                         $request->merge(['montoTotal' => floatval($total) - floatval($total) * floatval($purchase1->descuento) / 100]);
                         $request->merge(['montoTotalDolar' => floatval($total) / floatval($request->input("tasaDolar"))]);
                     } else {
                         $request->merge(['montoTotalDolar' => floatval($total) - floatval($total) * floatval($purchase1->descuento) / 100]);
                         $request->merge(['montoTotal' => floatval($total) * floatval($request->input("tasaDolar"))]);
                     }
                 } else {
                     if ($request->input("tCambio") == "sol") {
                         $request->merge(['montoTotal' => floatval($total)]);
                         $request->merge(['montoTotalDolar' => floatval($total) / floatval($request->input("tasaDolar"))]);
                     } else {
                         $request->merge(['montoTotalDolar' => floatval($total)]);
                         $request->merge(['montoTotal' => floatval($total) * floatval($request->input("tasaDolar"))]);
                     }
                 }
                 $manager = new PurchaseManager($purchase1, $request->except('fechaEntrega'));
                 $manager->save();
             }
             //======================Si Existe Stock Pendiente Por Agregar===============================
             $inputStock = $this->inputStockRepo->getModel();
             $object["warehouses_id"] = $request->input("warehouses_id");
             $object["cantidad_llegado"] = $cantidaCalculada;
             $object['descripcion'] = 'Entrada por compra';
             $object['tipo'] = 'Compra';
             if (!empty($cantidadReal)) {
                 if (floatval($cantidadReal) > 0) {
                     if (!empty($stockac)) {
                         $object["stockActual"] = $stockac->stockActual + $cantidaCalculada;
                         if ($object["Cantidad_Ll"] > 0) {
                             $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($cantidaCalculada);
                         } else {
                             $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($cantidadReal);
                         }
                         //======================Actualizando stock si es que variante existe===============================
                         $manager = new StockManager($stockac, $object);
                         $manager->save();
                         $stock = null;
                     } else {
                         if (!empty($stockac->porLlegar)) {
                             $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($object["cantidad"]);
                         } else {
                             $object["porLlegar"] = 0;
                         }
                         //======================Registrando estock si es que variante no existe===============================
                         $manager = new StockManager($stockmodel->getModel(), $object);
                         $manager->save();
                         $stockmodel = null;
                     }
                     $stockac = null;
                 }
             }
             if ($cantidaCalculada > 0) {
                 ////======================Registrando en notas de cabecera===============================
                 if ($codigoHeadIS === 0 && $cantidaCalculada > 0) {
                     $headInputStock = $this->headInputStockRepo->getModel();
                     //var_dump($object);die();
                     $object["user_id"] = auth()->user()->id;
                     $inserHeadInputStock = new HeadInputStockManager($headInputStock, $object);
                     $inserHeadInputStock->save();
                     $codigoHeadIS = $headInputStock->id;
                 }
                 ////======================Registrando en notas de detalles===============================cantidad_llegado
                 //if(!empty($object["equivalencia"])){
                 //  if($object["equivalencia"]>0){
                 //    $object["cantidad_llegado"]=$object["cantidad_llegado"]*$object["equivalencia"];
                 //  }
                 //}
                 $object['headInputStock_id'] = $codigoHeadIS;
                 $inserInputStock = new inputStockManager($inputStock, $object);
                 $inserInputStock->save();
             }
         }
         //======================Creando reporte por cada linea de detalle de compra===============================
         //====================Creando y actualizando pagos si que existe adelantos====================================
         if ($request->input('compraDirecta') == 1) {
             $request->merge(["Acuenta" => 0]);
             $inserPay = new PaymentManager($payment, $request->all());
             $inserPay->save();
         } else {
             // var_dump($request->orderPurchase_id);die();
             $consulPayment = $this->paymentRepo->paymentById($request->orderPurchase_id);
             if (!empty($consulPayment)) {
                 // var_dump("entrando XD");die();
                 $request->merge(["Acuenta" => $consulPayment->Acuenta]);
                 $request->merge(["Saldo" => floatval($request->input("montoTotal")) - floatval($request->input("Acuenta"))]);
                 //$request->merge(["Acuenta"=>0]);
                 $inserPay = new PaymentManager($consulPayment, $request->all());
                 $inserPay->save();
                 //------------------------------------
                 if (floatval($request->Saldo) < 0) {
                     $request->merge(['Saldo' => floatval($request->Saldo * -1)]);
                     //$request->merge(["estado"=>0]);
                     $insercount = new PendientAccountManager($pendientAccount, $request->except("estado"));
                     $insercount->save();
                 }
             } else {
                 $request->merge(["Acuenta" => 0]);
                 $request->merge(["Saldo" => floatval($request->input("montoTotal")) - floatval($request->input("Acuenta"))]);
                 $inserPay = new PaymentManager($payment, $request->all());
                 $inserPay->save();
                 //$saldoTemp=$inserPay->Saldo;
             }
         }
         //var_dump("recolectando verdadero salfdo".$consulPayment->Saldo);die();
         // if(!empty($consulPayment)){
         // }
         if (!empty($consulPayment)) {
             $detPayment = $this->detPaymentRepo->verPagosAdelantados($consulPayment->id);
             if ($detPayment != null) {
                 foreach ($detPayment as $detPayment) {
                     if ($detPayment->Saldo_F != null) {
                         $saldos = $this->pendientAccountRepo->find2($detPayment['Saldo_F']);
                         if ($saldos != null) {
                             if ($saldos->Saldo == 0) {
                                 $request->merge(['Saldo' => 0]);
                                 $request->merge(['estado' => 1]);
                                 $request->merge(['orderPurchase_id' => $saldos->orderPurchase_id]);
                                 $request->merge(['supplier_id' => $saldos->supplier_id]);
                                 $insercount = new PendientAccountManager($saldos, $request->all());
                                 $insercount->save();
                             }
                         }
                     }
                 }
             }
         }
         ///==========================Registrando saldo Afavor ========================================
     }
     \DB::commit();
     return response()->json(['estado' => true, 'nombres' => $purchase->nombres]);
 }
 public function create(Request $request)
 {
     \DB::beginTransaction();
     if ($request->warehouDestino_id == "") {
         $request->merge(["warehouDestino_id" => null]);
     }
     $var = $request->detailOrderPurchases;
     $request->merge(["Fecha" => $request->fecha]);
     // var_dump($request->input("generareport"));die();
     $codigoHeadIS;
     $almacen_id = $request->input("warehouses_id");
     $almacen_Destino = $request->input("warehouDestino_id");
     //if($almacen_Destino==null){
     //       $almacen_Destino=null;
     //}
     $queHacer = $request->input("eliminar");
     $tipo = $request->input("tipo");
     $tipo2 = "Salida";
     $request->merge(['user_id' => auth()->user()->id]);
     //var_dump();die();
     if ($queHacer === 0) {
         $request->merge(["orderPurchase_id" => $request->input('id')]);
         $headInputStock = $this->headInputStockRepo->getModel();
         if (!empty($request->input('warehouDestino_id'))) {
             $inserHeadInputStock = new HeadInputStockManager($headInputStock, $request->all());
         } else {
             $inserHeadInputStock = new HeadInputStockManager($headInputStock, $request->except('warehouDestino_id'));
         }
         $inserHeadInputStock->save();
         $codigoHeadIS = $headInputStock->id;
         $orderPurchase = $this->orderPurchaseRepo->find($request->input('id'));
         $orderPurchase->detPres()->detach();
         foreach ($var as $object) {
             //  if($queHacer===0){
             //var_dump("hola");die();
             $detPres = $this->detPresRepo->listarVariantes($object['detPres_id']);
             $object["variant_id"] = $detPres->variant_id;
             $object["warehouses_id"] = $request->input("warehouses_id");
             $object["descripcion"] = "Ingreso por pedido";
             $detailOrderPurchaseRepox = new DetailOrderPurchaseRepo();
             $insertar = new DetailOrderPurchaseManager($detailOrderPurchaseRepox->getModel(), $object);
             $insertar->save();
             $detailOrderPurchaseRepox = null;
             // }
             $inputStock = $this->inputStockRepo->getModel();
             // var_dump($object);die();
             if (!empty($object["cantidad_llegado"])) {
                 //if($object["cantidad_llegado"]>0){
                 //  if(!empty($object["equivalencia"])){
                 //      if($object["equivalencia"]>0){
                 //        $object["cantidad_llegado"]=$object["cantidad_llegado"]*$object["equivalencia"];
                 //      }
                 //   }
                 $object['headInputStock_id'] = $codigoHeadIS;
                 $inserInputStock = new inputStockManager($inputStock, $object);
                 $inserInputStock->save();
                 $stockmodel = new StockRepo();
                 $object['warehouse_id'] = $almacen_id;
                 $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
                 //var_dump($object["tipo"]);die();
                 if (!empty($stockac)) {
                     /* if($object["esbase"]==0){
                            if($object["tipo"]=="Salida"){
                                $object["stockActual"]=$stockac->stockActual-($object["cantidad_llegado"]*$object["equivalencia"]);
                                var_dump("entre");
                            }else{
                                $object["stockActual"]=$stockac->stockActual+($object["cantidad_llegado"]*$object["equivalencia"]);
                             }
                        }else{
                            if($object["tipo"]=="Salida"){
                              $object["stockActual"]=$stockac->stockActual-$object["cantidad_llegado"];
                              var_dump("entre");
                            }else{
                               $object["stockActual"]=$stockac->stockActual+$object["cantidad_llegado"]; 
                            }
                        }*/
                     //if($object["esbase"]==0){
                     //  $object["stockActual"]=$stockac->stockActual+($object["cantidad_llegado"]*$object["equivalencia"]);
                     // }else{
                     $object["stockActual"] = $stockac->stockActual + $object["cantidad_llegado"];
                     $object["porLlegar"] = $stockac->porLlegar - $object["cantidad_llegado"];
                     //}
                     $manager = new StockManager($stockac, $object);
                     $manager->save();
                     $stock = null;
                 } else {
                     if ($tipo != $tipo2) {
                         if ($object["esbase"] == 0) {
                             $object["stockActual"] = $object["cantidad_llegado"] * $object["equivalencia"];
                         } else {
                             $object["stockActual"] = $object["cantidad_llegado"];
                         }
                         $manager = new StockManager($stockmodel->getModel(), $object);
                         $manager->save();
                         $stockmodel = null;
                     }
                 }
                 $stockac = null;
             }
         }
         // }
     } else {
         //==========================================================0
         //$inputStock = $this->inputStockRepo->getModel();
         $headInputStock = $this->headInputStockRepo->getModel();
         //var_dump($var);die();
         //if(!empty($var["cantidad_llegado"])){
         //var_dump($request->all());die();
         $inserHeadInputStock = new HeadInputStockManager($headInputStock, $request->all());
         $inserHeadInputStock->save();
         $codigoHeadIS = $headInputStock->id;
         foreach ($var as $object) {
             $inputStock = $this->inputStockRepo->getModel();
             //$inputStock = $this->inputStockRepo->getModel();
             if (!empty($object["cantidad_llegado"])) {
                 if ($object["cantidad_llegado"] > 0) {
                     $object['warehouse_id'] = $almacen_id;
                     $object['headInputStock_id'] = $codigoHeadIS;
                     $inserInputStock = new InputStockManager($inputStock, $object);
                     $inserInputStock->save();
                     //var_dump($object);die();
                     $stockmodel = new StockRepo();
                     //$var['warehouse_id']=$almacen_id;
                     $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
                     if ($tipo == "Transferencia") {
                         $tockacDestino = $stockmodel->encontrar($object["variant_id"], $almacen_Destino);
                         if (!empty($tockacDestino)) {
                             if ($object["esbase"] == 0) {
                                 $object["stockActual"] = $tockacDestino->stockActual + $object["cantidad_llegado"] * $object["equivalencia"];
                             } else {
                                 $object["stockActual"] = $tockacDestino->stockActual + $object["cantidad_llegado"];
                             }
                             $object['warehouse_id'] = $almacen_Destino;
                             $manager = new StockManager($tockacDestino, $object);
                             $manager->save();
                             $stock = null;
                         } else {
                             if ($object["esbase"] == 0) {
                                 $object["stockActual"] = $object["cantidad_llegado"] * $object["equivalencia"];
                             } else {
                                 $object["stockActual"] = $object["cantidad_llegado"];
                             }
                             $object['warehouse_id'] = $almacen_Destino;
                             $manager = new StockManager($stockmodel->getModel(), $object);
                             $manager->save();
                             $stockmodel = null;
                         }
                         $tockacDestino = null;
                         if (!empty($stockac)) {
                             $object['warehouse_id'] = $almacen_id;
                             $object["stockActual"] = $stockac->stockActual - $object["cantidad_llegado"];
                             $manager = new StockManager($stockac, $object);
                             $manager->save();
                             $stock = null;
                         }
                     } else {
                         //Actualiza Stock---------------------------------------------
                         if (!empty($stockac)) {
                             if ($object["esbase"] == 0) {
                                 if ($tipo == $tipo2) {
                                     $object["stockActual"] = $stockac->stockActual - $object["cantidad_llegado"] * $object["equivalencia"];
                                     //var_dump("entre");
                                 } else {
                                     $object["stockActual"] = $stockac->stockActual + $object["cantidad_llegado"] * $object["equivalencia"];
                                 }
                             } else {
                                 if ($tipo == $tipo2) {
                                     $object["stockActual"] = $stockac->stockActual - $object["cantidad_llegado"];
                                     //var_dump("entre");
                                 } else {
                                     // var_dump("hola ");die();
                                     $object["stockActual"] = $stockac->stockActual + $object["cantidad_llegado"];
                                 }
                             }
                             $manager = new StockManager($stockac, $object);
                             $manager->save();
                             $stock = null;
                         } else {
                             if ($tipo != $tipo2) {
                                 if ($object["esbase"] == 0) {
                                     $object["stockActual"] = $object["cantidad_llegado"] * $object["equivalencia"];
                                 } else {
                                     $object["stockActual"] = $object["cantidad_llegado"];
                                 }
                                 $manager = new StockManager($stockmodel->getModel(), $object);
                                 $manager->save();
                                 $stockmodel = null;
                             }
                         }
                     }
                     //fin actualiza Stock---------------------------------------------------
                     $stockac = null;
                 }
             }
         }
     }
     // var_dump($request->generareport);die();
     //$idOrder=intval($request->input("id"));
     //var_dump($idOrder);die();
     \DB::commit();
     ////======================================================00
     return response()->json(['estado' => true]);
 }
 public function edit(Request $request)
 {
     \DB::beginTransaction();
     $var = $request->detailOrderPurchases;
     //->except($request->detailOrderPurchases["id"]);
     $orderPurchase = $this->orderPurchaseRepo->find($request->input('id'));
     $orderPurchase = $this->orderPurchaseRepo->find($request->id);
     $almacen_id = $request->input("warehouses_id");
     $manager = new OrderPurchaseManager($orderPurchase, $request->except('fechaPedido', 'fechaPrevista'));
     $manager->save();
     if ($this->orderPurchaseRepo->validateDate(substr($request->input('fechaPedido'), 0, 10)) and $this->orderPurchaseRepo->validateDate(substr($request->input('fechaPrevista'), 0, 10))) {
         $orderPurchase->fechaPedido = substr($request->input('fechaPedido'), 0, 10);
         $orderPurchase->fechaPrevista = substr($request->input('fechaPrevista'), 0, 10);
     } else {
         $orderPurchase->fechaPedido = null;
         $orderPurchase->fechaPrevista = null;
     }
     $orderPurchase->save();
     $orderPurchase->detPres()->detach();
     foreach ($var as $object) {
         $detailOrderPurchaseRepox = new DetailOrderPurchaseRepo();
         $insertar = new DetailOrderPurchaseManager($detailOrderPurchaseRepox->getModel(), $object);
         $insertar->save();
         $detailOrderPurchaseRepox = null;
         $stockmodel = new StockRepo();
         $object['warehouse_id'] = $almacen_id;
         $object["variant_id"] = $object["Codigovar"];
         $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
         if (!empty($stockac)) {
             // if($object["esbase"]==0){
             //  $object["porLlegar"]=$stockac->stockActual+($object["cantidad_llegado"]*$object["equivalencia"]);
             // }else{
             if (!empty($object["nuevo"])) {
                 $object["porLlegar"] = $stockac->porLlegar + $object["cantidad"];
             } else {
                 if (!empty($object["cantAnterior"])) {
                     $object["porLlegar"] = floatval($stockac->porLlegar) - floatval($object["cantAnterior"]) + floatval($object["cantidad"]);
                 } else {
                     $object["porLlegar"] = $stockac->porLlegar;
                 }
             }
             //}
             $manager = new StockManager($stockac, $object);
             $manager->save();
             $stock = null;
         } else {
             //if($tipo!=$tipo2){
             // if($object["esbase"]==0)
             // {
             //    $object["stockActual"]=$object["cantidad_llegado"]*$object["equivalencia"];
             //}else{
             $object["porLlegar"] = $object["cantidad"];
             //}
             $manager = new StockManager($stockmodel->getModel(), $object);
             $manager->save();
             $stockmodel = null;
         }
         //}
         $stockac = null;
     }
     $payment = $this->paymentRepo->getModel();
     $payment1 = $this->paymentRepo->paymentById($request->input('id'));
     if (!empty($payment1)) {
         $request->merge(['Acuenta' => $payment1->Acuenta]);
         $request->merge(['orderPurchase_id' => $request->input('id')]);
         $salc = floatval($request->input('montoTotal')) - floatval($request->input('Acuenta'));
         $request->merge(['Saldo' => $salc]);
         $manager = new PaymentManager($payment1, $request->all());
         $manager->save();
         $provicional = $request->idpayment;
     }
     \DB::commit();
     return response()->json(['estado' => true]);
 }
 public function edit(Request $request)
 {
     // var_dump($var=$request->input('detailOrderPurchases'));die();
     \DB::beginTransaction();
     $var = $request->input('detailOrderPurchases');
     //var_dump($request->input("warehouses_id"));die();
     $almacen_id = $request->input("warehouses_id");
     $orderPurchase = $this->orderPurchaseRepo->find($request->id);
     if ($request->Estado == 0) {
         $manager = new OrderPurchaseManager($orderPurchase, $request->except('fechaPedido', 'fechaPrevista'));
         $manager->save();
     } else {
         $manager = new OrderPurchaseManager($orderPurchase, $request->except('fechaPedido', 'fechaPrevista', 'montoBruto', 'montoTotal', 'descuento'));
         $manager->save();
     }
     if ($this->orderPurchaseRepo->validateDate(substr($request->input('fechaPedido'), 0, 10)) and $this->orderPurchaseRepo->validateDate(substr($request->input('fechaPrevista'), 0, 10))) {
         $orderPurchase->fechaPedido = substr($request->input('fechaPedido'), 0, 10);
         $orderPurchase->fechaPrevista = substr($request->input('fechaPrevista'), 0, 10);
     } else {
         $orderPurchase->fechaPedido = null;
         $orderPurchase->fechaPrevista = null;
     }
     $orderPurchase->save();
     // $verSiExiste=$this->detailOrderPurchaseRepo->Comprobar($request->id);
     //$n=0;
     //->except($request->detailOrderPurchases["id"]);
     //$orderPurchase = $this->orderPurchaseRepo->find($request->input('id'));
     //==================================Actualizando Detallles==========================
     //if(!empty($verSiExiste[0])){
     //var_dump("no deve entrar");die();
     // $orderPurchase->detPres()->detach();
     /*foreach($var as $object1){
        //$hola=$var[$n];
        if(!empty($object1["cantidad1"])){
            //var_dump("holay".$object1["cantidad1"]);die();
            //$object1["cantidad"]=$object1["Cantidad_Ll"];
            //$object1["pendiente"]=$object1["pendiente"];
            $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
            $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
        }else{
            //var_dump("dos".$object1["cantidad1"]);die();
            if($object1["Cantidad_Ll"]=='0' && $object1["montoBruto"]=='0'){
              $object1["Cantidad_Ll"]=0;
              $object1["pendiente"]=$object1["cantidad"];
              $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
              $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
            }else{
                if($object1["Cantidad_Ll"]>0){
                     $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                     $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
                }else{  
                     $object1["Cantidad_Ll"]=$object1["cantidad"];
                     $object1["pendiente"]=0;
                     $object1["montoBruto"]=floatval($object1["cantidad"])*floatval($object1["preProducto"]);
                     $object1["montoTotal"]=floatval($object1["montoBruto"])-((floatval($object1["montoBruto"])*floatval($object1["descuento"]))/100);
            }
          }
        }
        
        ////if($hola->cantidad1!=null){
        ////    $object1["Cantidad_Ll"]=$hola->Cantidad_Ll;
        ////    $object1["pendiente"]=$hola->pendiente;
        ////    
        ////}else{
        ////    $object1["Cantidad_Ll"]=$object1["cantidad"];
        ////    $object1["pendiente"]=0;
        ////}
        //var_dump($hola['Cantidad_Ll']);die();
        
        $detailOrderPurchaseRepox = new DetailOrderPurchaseRepo;
        $insertar=new DetailOrderPurchaseManager($detailOrderPurchaseRepox->getModel(),$object1);
        $insertar->save();
        $detailOrderPurchaseRepox = null;
        //$n++;
         $stockmodel = new StockRepo;
                  $object['warehouse_id']=$almacen_id;
                  $object["variant_id"]=$object["Codigovar"];
                  $stockac=$stockmodel->encontrar($object["variant_id"],$almacen_id);
               var_dump($stockac->porLlegar);die();  
            if(!empty($stockac)){ 
              
               // if($object["esbase"]==0){
                //  $object["porLlegar"]=$stockac->stockActual+($object["cantidad_llegado"]*$object["equivalencia"]);
               // }else{
                  $object["porLlegar"]=$stockac->porLlegar+$object["cantidad"];
                //}
                  $manager = new StockManager($stockac,$object);
                  $manager->save();
                  $stock=null;
            }else{
              //if($tipo!=$tipo2){
               // if($object["esbase"]==0)
               // {
                //    $object["stockActual"]=$object["cantidad_llegado"]*$object["equivalencia"];
                //}else{
                    $object["porLlegar"]=$object["cantidad"];
                //}
            
                  $manager = new StockManager($stockmodel->getModel(),$object);
                  $manager->save();
                  $stockmodel = null;
                  }
            //}
            $stockac=null;
       }*/
     // }
     //else{
     foreach ($var as $object) {
         $object["pendiente"] = $object["cantidad"];
         $detailOrderPurchaseRepox = new DetailOrderPurchaseRepo();
         $insertar = new DetailOrderPurchaseManager($detailOrderPurchaseRepox->getModel(), $object);
         $insertar->save();
         $detailOrderPurchaseRepox = null;
         $stockmodel = new StockRepo();
         $object['warehouse_id'] = $almacen_id;
         $object["variant_id"] = $object["Codigovar"];
         $stockac = $stockmodel->encontrar($object["variant_id"], $almacen_id);
         if (!empty($stockac)) {
             // if($object["esbase"]==0){
             //  $object["porLlegar"]=$stockac->stockActual+($object["cantidad_llegado"]*$object["equivalencia"]);
             // }else{
             $object["porLlegar"] = $stockac->porLlegar + $object["cantidad"];
             //}
             $manager = new StockManager($stockac, $object);
             $manager->save();
             $stock = null;
         } else {
             //if($tipo!=$tipo2){
             // if($object["esbase"]==0)
             // {
             //  $object["stockActual"]=$object["cantidad_llegado"]*$object["equivalencia"];
             //}else{
             $object["porLlegar"] = $object["cantidad"];
             //}
             $manager = new StockManager($stockmodel->getModel(), $object);
             $manager->save();
             $stockmodel = null;
         }
         //}
         $stockac = null;
     }
     // }
     //*************************************************************************************
     $verDeudas = $this->pendientAccountRepo->verSaldos($request->input("supplier_id"));
     //var_dump($verDeudas[0]->Saldo);die();
     $SaldoAfavor = $request->input('SaldoUtilizado');
     $provicional = null;
     if ($verDeudas != null) {
         if ($SaldoAfavor > 0) {
             foreach ($verDeudas as $verDeudas) {
                 // $verDeudas=$this->pendientAccountRepo->verSaldos($request->input("supplier_id"));
                 /* if($provicional==null){
                      $payment = $this->paymentRepo->getModel();
                      $request->merge(['montoTotal'=>$montotot]);
                      $request->merge(['Acuenta'=>$verDeudas->Saldo]);
                      $request->merge(['orderPurchase_id'=>$request->input('id')]);
                      $salc=$request->input('montoTotal')-$request->input('Acuenta');
                      $request->merge(['Saldo'=>$salc]);        
                      $manager = new PaymentManager($payment,$request->all());
                      $manager->save();
                      $provicional=$payment->id;
                    }*/
                 if ($verDeudas->Saldo > 0 && $SaldoAfavor <= $verDeudas->Saldo) {
                     $var = $request->detPayments;
                     if ($provicional == null) {
                         $payment = $this->paymentRepo->getModel();
                         // $request->merge(['montoTotal'=>$montotot]);
                         $request->merge(['Acuenta' => $SaldoAfavor]);
                         $request->merge(['orderPurchase_id' => $request->input('id')]);
                         $salc = floatval($request->input('montoTotal')) - floatval($request->input('Acuenta'));
                         //var_dump($request->input('montoTotal'));die();
                         $request->merge(['Saldo' => $salc]);
                         $manager = new PaymentManager($payment, $request->all());
                         $manager->save();
                         $provicional = $payment->id;
                     } else {
                         $saldos = $this->paymentRepo->find($provicional);
                         // $request->merge(['montoTotal'=>$montotot]);
                         $request->merge(['Acuenta' => $saldos->Acuenta + $SaldoAfavor]);
                         $request->merge(['orderPurchase_id' => $request->input('id')]);
                         $salc = floatval($request->input('montoTotal')) - floatval($request->input('Acuenta'));
                         //var_dump($request->input('montoTotal'));die();
                         $request->merge(['Saldo' => $salc]);
                         $payment = new PaymentManager($saldos, $request->all());
                         $payment->save();
                     }
                     // var_dump($var);die();
                     $detPayment = $this->detPaymentRepo->getModel();
                     $pendientAccountRepo = $this->pendientAccountRepo->getModel();
                     $request->merge(['tipoPago' => 'A']);
                     $request->merge(['payment_id' => $provicional]);
                     $request->merge(['montoPagado' => $SaldoAfavor]);
                     $request->merge(['methodPayment_id' => 4]);
                     $request->merge(['Saldo_F' => $verDeudas->id]);
                     $insertDetP = new DetPaymentManager($detPayment, $request->all());
                     $insertDetP->save();
                     $request->merge(['Saldo' => $verDeudas->Saldo - $SaldoAfavor]);
                     $request->merge(['orderPurchase_id' => $verDeudas->orderPurchase_id]);
                     $request->merge(['supplier_id' => $verDeudas->supplier_id]);
                     $updateSaldoF = new pendientAccountManager($verDeudas, $request->all());
                     $updateSaldoF->save();
                     break;
                     //$SaldoAfavor=$verDeudas->Saldo-$request->input('SaldoUtilizado');
                 } else {
                     if ($verDeudas->Saldo > 0) {
                         $var = $request->detPayments;
                         // var_dump($var);die();
                         $SaldoAfavor = $SaldoAfavor - $verDeudas->Saldo;
                         if (!empty($provicional)) {
                             $payment = $this->paymentRepo->getModel();
                             //$request->merge(['montoTotal'=>$montotot]);
                             $request->merge(['Acuenta' => $SaldoAfavor]);
                             $request->merge(['orderPurchase_id' => $request->input('id')]);
                             $salc = floatval($request->input('montoTotal')) - $request->input('Acuenta');
                             //var_dump($request->input('montoTotal'));die();
                             $request->merge(['Saldo' => $salc]);
                             $manager = new PaymentManager($payment, $request->all());
                             $manager->save();
                             $provicional = $payment->id;
                         } else {
                             $saldos = $this->paymentRepo->fine($provicional);
                             // $request->merge(['montoTotal'=>$montotot]);
                             $request->merge(['Acuenta' => $saldos->Acuenta + $SaldoAfavor]);
                             $request->merge(['orderPurchase_id' => $request->input('id')]);
                             $salc = floatval($request->input('montoTotal')) - $request->input('Acuenta');
                             //var_dump($request->input('montoTotal'));die();
                             $request->merge(['Saldo' => $salc]);
                             $payment = new PaymentManager($saldos, $request->all());
                             $payment->save();
                         }
                         $detPayment = $this->detPaymentRepo->getModel();
                         $pendientAccountRepo = $this->pendientAccountRepo->getModel();
                         $request->merge(['tipoPago' => 'A']);
                         $request->merge(['payment_id' => $provicional]);
                         $request->merge(['montoPagado' => $verDeudas->Saldo]);
                         $request->merge(['methodPayment_id' => 4]);
                         $request->merge(['Saldo_F' => $verDeudas->id]);
                         $insertDetP = new DetPaymentManager($detPayment, $request->all());
                         $insertDetP->save();
                         $request->merge(['Saldo' => 0]);
                         $request->merge(['orderPurchase_id' => $verDeudas->orderPurchase_id]);
                         $request->merge(['supplier_id' => $verDeudas->supplier_id]);
                         $updateSaldoF = new pendientAccountManager($verDeudas, $request->all());
                         $updateSaldoF->save();
                     }
                     //fin else
                 }
                 //fin segundo if
             }
             //fin for
         }
         //fin primer if
     }
     //fin if primeross
     //**************************************************************************************
     if ($orderPurchase->Estado === 2) {
         $payment1 = $this->paymentRepo->paymentById($request->input('id'));
         $pendientAccount = $this->pendientAccountRepo->getModel();
         //$pendientAcc=$this->pendientAccountRepo->verSaldos($payment1->id);
         if ($payment1 != null) {
             $detPayment = $this->detPaymentRepo->verPagosAdelantados($payment1->id);
             if ($detPayment != null) {
                 foreach ($detPayment as $detPayment) {
                     $SaldosTemporales = $this->pendientAccountRepo->find2($detPayment['Saldo_F']);
                     if ($SaldosTemporales != null) {
                         $request->merge(['Saldo' => $SaldosTemporales->Saldo + $detPayment['montoPagado']]);
                         $request->merge(['orderPurchase_id' => $SaldosTemporales->orderPurchase_id]);
                         $request->merge(['supplier_id' => $SaldosTemporales->supplier_id]);
                         $insercount = new PendientAccountManager($SaldosTemporales, $request->all());
                         $insercount->save();
                     } else {
                         $request->merge(['orderPurchase_id' => $request->input('id')]);
                         $request->merge(['Saldo' => $payment1->Acuenta]);
                         $insercount = new PendientAccountManager($pendientAccount, $request->all());
                         $insercount->save();
                     }
                 }
             } else {
                 $request->merge(['orderPurchase_id' => $request->input('id')]);
                 $request->merge(['Saldo' => $payment1->Acuenta]);
                 $insercount = new PendientAccountManager($pendientAccount, $request->all());
                 $insercount->save();
                 $provicional = $request->idpayment;
             }
         }
     }
     \DB::commit();
     return response()->json(['estado' => true, 'nombres' => $orderPurchase->nombres]);
 }