/**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     $user = $this->auth->user()->id;
     $count = $this->carrello->where('utente', '=', $user)->count();
     if ($count == 0) {
         return Response::json(array('code' => '500', 'msg' => 'KO', 'error' => 'No items into cart for user.'));
     }
     $carrello = $this->carrello->with('prodotti')->where('utente', '=', $user)->get();
     $totaleCarrello = number_format(round($request->get('cartTotal'), 2), 2);
     $scontoQuantita = number_format(round($request->get('discountUnits'), 2), 2);
     $scontoPagamento = number_format(round($request->get('discountPayment'), 2), 2);
     $costoSpedizione = number_format(round($request->get('shippingPrice'), 2), 2);
     $totaleCarrelloScontato = number_format(round($request->get('cartTotalDiscounted'), 2), 2);
     $tipoPagamento = $request->paymentType;
     $sconto = number_format(round($scontoPagamento + $scontoQuantita, 2), 2);
     //valido i dati di ingresso per la testata dell'ordine
     $data = array('utente' => $this->auth->user()->id, 'costo' => $totaleCarrello, 'costospedizione' => $costoSpedizione, 'sconto' => $sconto, 'tipopagamento' => $tipoPagamento);
     //validate images
     if (!$this->ordine->validate($data)) {
         $errors = $this->ordine->getErrors();
         return Response::json(array('code' => '500', 'msg' => 'KO', 'error' => $errors));
     }
     //salvo la testata
     $this->ordine->store($data);
     //salvo il dettaglio
     foreach ($carrello as $item) {
         $this->ordine->prodotti()->attach($item->prodotto, ['quantita' => $item->quantita, 'costo' => $item->prodotti->prezzo]);
     }
     //salvo lo stato
     $stato = $this->stato->where('descrizione', '=', 'LAVORAZIONE')->first();
     $this->ordine->stati()->attach($stato);
     $cliente = $this->auth->user()->clienti()->where('utente', '=', $this->auth->user()->id)->first();
     $nome = $cliente->nome . ' ' . $cliente->cognome;
     //ritorno
     $data = array('item_name' => $this->ordine->id, 'amount' => $totaleCarrelloScontato, 'return' => url('/admin/ordini/' . $this->ordine->id), 'name' => $nome, 'username' => $this->auth->user()->username);
     //cancello il carrello dell'utente
     foreach ($carrello as $item) {
         $this->carrello->destroy($item->id);
     }
     //tutto ok ora invio le mail di conferma
     $this->sendMail($this->ordine->id);
     return Response::json(array('code' => '200', 'msg' => 'OK', 'item' => $data));
 }