/**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index(Region $region, TrainRoad $trainRoad, Stantion $stantion)
 {
     $regionsCount = $region->count();
     $tRoadsCount = $trainRoad->count();
     $stationsCount = $stantion->count();
     $condCount = Condition::count();
     $productsCount = Product::count();
     $servicesCount = Service::count();
     $catCount = Category::count();
     $statusesCount = Status::count();
     $serviceStatusesCount = ServiceStatus::count();
     $newOrdersCount = Order::where('is_new', 1)->count();
     $newServiceOrdersCount = ServiceOrder::where('is_new', 1)->count();
     $customers = Firm::where('accountant_fio', null)->get();
     return view('admin.adminArea', ['regionsCount' => $regionsCount, 'tRoadsCount' => $tRoadsCount, 'stationsCount' => $stationsCount, 'condCount' => $condCount, 'catCount' => $catCount, 'productsCount' => $productsCount, 'servicesCount' => $servicesCount, 'statusesCount' => $statusesCount, 'newOrdersCount' => $newOrdersCount, 'serviceStatusesCount' => $serviceStatusesCount, 'newServiceOrdersCount' => $newServiceOrdersCount, 'customers' => $customers]);
 }
 /**
  * Execute the command.
  *
  * @return void
  */
 public function handle()
 {
     $selfFirmUser = User::with('firm')->where('role_id', User::ADMIN)->first();
     $clientCompany = User::with('firm')->where('id', $this->order->user_id)->first();
     $products = $this->order->products_in_order;
     $firm = $clientCompany->firm;
     $productsArr = [];
     foreach ($products as $product) {
         $productsArr[] = ['product_name' => $product->product_name, 'product_amount' => $product->product_amount, 'product_price' => $product->product_price];
     }
     $date = DateTime::createFromFormat('Y-m-d H:i:s', $this->order->created_at);
     $date = strtotime($date->format('d F Y'));
     $pdf = App::make('dompdf.wrapper');
     $viewType = null;
     if ($this->isTorg) {
         $viewType = 'documents.torg_12';
     } else {
         $viewType = 'documents.schet_factura';
     }
     $pdf->loadView($viewType, ['orderNumber' => $this->order->id, 'orderDate' => date('d.m.Y', $date), 'firm' => $firm, 'selfFirm' => $selfFirmUser->firm, 'products' => $productsArr]);
     //$pdf->setOrientation('landscape');
     $pdf->setPaper('A4', 'landscape');
     $documents = Config::get('documents');
     $whereAreClientDocuments = $documents['documents_folder'];
     //client_{id}
     if (!Storage::disk('local')->exists($whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id)) {
         Storage::makeDirectory($whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id);
     }
     //paymentDocs
     if (!Storage::disk('local')->exists($whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id . DIRECTORY_SEPARATOR . 'paymentDocs')) {
         Storage::makeDirectory($whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id . DIRECTORY_SEPARATOR . 'paymentDocs');
     }
     $clientFolder = storage_path() . DIRECTORY_SEPARATOR . 'app' . $whereAreClientDocuments . DIRECTORY_SEPARATOR . 'client_' . $this->order->user_id . DIRECTORY_SEPARATOR . 'paymentDocs';
     //(torg12/schetfactura)_{orderID}_{depoName}_date_{currentDate}
     $fileNameTemplate = $documents['client_invoice_template'];
     $fileNameTemplate = Utils::mb_str_replace('{docType}', Order::getDocTypeName($this->isTorg ? Order::AUCTION_12_TYPE : Order::INVOICE_ACCT_TYPE), $fileNameTemplate);
     $fileNameTemplate = Utils::mb_str_replace('{orderID}', $this->order->id, $fileNameTemplate);
     $depo = Stantion::find($this->order->products_in_order[0]->stantion_id);
     $depoName = Utils::mb_str_replace(' ', '', $depo->stantion_name);
     $depoName = Utils::translit($depoName);
     $fileNameTemplate = Utils::mb_str_replace('{depoName}', $depoName, $fileNameTemplate);
     $fileNameTemplate = Utils::mb_str_replace('{currentDate}', time(), $fileNameTemplate);
     $pdf->save($clientFolder . DIRECTORY_SEPARATOR . $fileNameTemplate);
     $docs = new Document();
     $docs->type = $this->isTorg ? Order::AUCTION_12_TYPE : Order::INVOICE_ACCT_TYPE;
     $docs->user_id = $this->order->user_id;
     $docs->order_id = $this->order->id;
     $docs->file_name = $clientFolder . DIRECTORY_SEPARATOR . $fileNameTemplate;
     $docs->save();
     Bus::dispatch(new SendEmailWithPaymentDocs($docs->file_name, $this->isTorg, $this->order));
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Request $request)
 {
     $validationRules = ['oferta' => 'accepted', 'userID' => 'integer|required|in:' . Auth::user()->id];
     $v = Validator::make($request->all(), $validationRules);
     if ($v->fails()) {
         return redirect()->route('confirmOrder', ['user_id' => Auth::user()->id])->withErrors($v->errors());
         //            $newRequest = Request::create('confirmOrder/'.Auth::user()->id, 'POST', [], [], [], [],['blat'=>$v->errors()]);
         //            return Route::dispatch($newRequest)->getContent();
     }
     $userID = $request->userID;
     if (Auth::user()->id == (int) $userID) {
         $productsByDepoArr = [];
         $newProductsByDepoArr = [];
         $orderNumbers = [];
         DB::transaction(function () use($userID, &$productsByDepoArr, &$orderNumbers, &$newProductsByDepoArr) {
             $products = ProductCart::with('product.condition', 'price.stantion')->where('user_id', $userID)->get();
             foreach ($products as $productCart) {
                 $productsByDepoArr[$productCart->price->stantion[0]->id][] = [$productCart->product->name . '( состояние - ' . $productCart->product->condition->condition . ')', $productCart->product_count, $productCart->price->price, $productCart->price->id, $productCart->product->id, $productCart->price->stantion[0]->stantion_name, $productCart->price->nds];
                 $productCart->price->amount -= $productCart->product_count;
                 $productCart->price->save();
             }
             $userCompany = User::with('firm')->where('id', $userID)->first();
             $status = Status::where('is_first', Order::IS_FIRST)->first();
             foreach ($productsByDepoArr as $depoID => $productsArr) {
                 $order = new Order();
                 $order->status_id = $status->id;
                 $order->user_id = $userID;
                 $order->firm_id = $userCompany->firm->id;
                 $order->email = Auth::user()->email;
                 $order->save();
                 $orderNumbers[] = $order->id;
                 foreach ($productsArr as $product) {
                     $productsInOrder = new ProductsInOrder();
                     $productsInOrder->order_id = $order->id;
                     $productsInOrder->product_name = $product[0];
                     $productsInOrder->product_price = $product[2];
                     $productsInOrder->product_amount = $product[1];
                     $productsInOrder->stantion_id = $depoID;
                     $productsInOrder->price_id = $product[3];
                     $productsInOrder->product_id = $product[4];
                     $productsInOrder->stantion_name = $product[5];
                     $productsInOrder->nds = $product[6];
                     $productsInOrder->save();
                 }
                 $newProductsByDepoArr[$order->id] = $productsArr;
                 //Запускаем команду на формирование счета
                 Bus::dispatch(new CreateInvoice($order, Stantion::find($depoID)));
             }
             ProductCart::where('user_id', $userID)->delete();
         });
         $files = Document::where('user_id', Auth::user()->id)->where(function ($query) use($orderNumbers) {
             foreach ($orderNumbers as $number) {
                 $query->orWhere('file_name', 'like', '%' . Order::getDocTypeName(Order::INVOICE_TYPE) . '_' . $number . '_%');
             }
         })->get();
         $fileNames = [];
         foreach ($files as $file) {
             $fileNames[] = $file->file_name;
         }
         $messageParams = [];
         $messageParams['productByDepoWithOrderIdAsKey'] = $newProductsByDepoArr;
         //            //Запускаем команду на отправку email
         Bus::dispatch(new SendEmailWithInvoices($messageParams, $fileNames));
         //            Bus::dispatch(new SendWithTanksForOrder($messageParams));
         return view('orders.success', ['p' => 'purchases', 'ordersAmount' => count($productsByDepoArr)]);
     } else {
         return redirect('fatal_error')->with('alert-danger', 'Произошла ошибка в работе сайта. Мы уже исправляем эту проблему. Попробуйте через некоторое время.');
     }
 }
 /**
  * Update the specified resource in storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function update(Request $request, $id)
 {
     try {
         $product = Product::with(['price', 'price.stantion'])->where('id', $id)->first();
     } catch (ModelNotFoundException $e) {
         abort(404);
     }
     if (!$product) {
         abort(404);
     }
     $id = $request->route('products');
     $validationRules = ['name' => 'required|alpha_spaces_numbers|max:35|unique:products,name,' . $id, 'article' => 'required|alpha_spaces_numbers|max:15', 'description' => 'required|alpha_spaces_numbers', 'condition_id' => 'required|integer'];
     $depos = Stantion::all();
     foreach ($depos as $depo) {
         $validationRules['price' . $depo->id] = 'required|numeric';
         $validationRules['amount' . $depo->id] = 'required|numeric';
         $validationRules['vat' . $depo->id] = 'required|numeric';
     }
     $v = Validator::make($request->all(), $validationRules);
     if ($v->fails()) {
         return redirect()->back()->withErrors($v->errors())->withInput();
     }
     $prices = $product->price;
     DB::transaction(function () use($product, $request, $prices) {
         $product->article = $request->article;
         $product->name = $request->name;
         $product->description = $request->description;
         $product->condition_id = $request->condition_id;
         if (!(int) $request->category_id) {
             $product->category_id = null;
         } else {
             $product->category_id = $request->category_id;
         }
         $product->save();
         foreach ($prices as $price) {
             $priceInputName = 'price' . $price->stantion[0]->id;
             $priceInputAmount = 'amount' . $price->stantion[0]->id;
             $priceInputVAT = 'vat' . $price->stantion[0]->id;
             $price->price = $request->{$priceInputName};
             $price->amount = $request->{$priceInputAmount};
             $price->nds = $request->{$priceInputVAT};
             $price->save();
         }
     });
     return redirect('products')->with('alert-success', 'Товар обновлен');
 }
 public function getPriceListInCurrentCategory(ProductCart $productCart, $categoryName, $depoId)
 {
     $category = Category::with('product.price.stantion.train_road')->where('category', $categoryName)->first();
     $stantion = Stantion::where('id', $depoId)->first();
     $depoName = $stantion->stantion_name;
     $productsArr = [];
     if (Auth::guest()) {
         $userID = 0;
     } else {
         $userID = Auth::user()->id;
     }
     foreach ($category->product as $product) {
         foreach ($product->price as $price) {
             if ($price->price > 0 && $price->amount > 0) {
                 $productsArr[$price->stantion[0]->train_road->tr_name][$price->stantion[0]->stantion_name][] = ['name' => $product->name, 'product_id' => $product->id, 'depo_id' => $price->stantion[0]->id, 'price_id' => $price->id, 'article' => $product->article, 'description' => $product->description, 'price' => $price->price, 'amount' => $price->amount];
             }
         }
     }
     $sumAndCount = $this->getGeneralViewOfCart($productCart);
     return view('purchases.trainCarPriceListInCurrentCategory', ['p' => 'purchases', 'productsArr' => $productsArr, 'category' => $categoryName, 'userID' => $userID, 'productsCount' => $sumAndCount['productsCount'], 'productsSum' => $sumAndCount['productsSum'], 'whatDepoIdWeAre' => $depoId, 'whatDepoNameWeAre' => $depoName]);
 }
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy($id)
 {
     //$station = Stantion::find($id);
     $station = Stantion::with(['price'])->where('id', $id)->first();
     DB::transaction(function () use($station) {
         $station->price()->detach();
         foreach ($station->price as $price) {
             $price->delete();
         }
         $station->delete();
     });
     //Region::destroy($id);
     return back()->with('alert-success', 'Станция ' . $station->stantion_name . ' удалена');
 }