/**
  * Function that creates a new item for specified order.
  *
  * @return Response
  */
 public function createItem()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('workerId' => 'required', 'grip' => 'required', 'code' => 'required', 'orderId' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'All fields are required!']);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Check that we still have to produce this kind of item.
     $production = Production::where('Code', '=', Input::get('code'))->where('OrderId', '=', Input::get('orderId'))->get();
     $productionCount = 0;
     foreach ($production as $produced) {
         $productionCount++;
     }
     $breakdown = OrderBreakdown::where('OrderId', '=', Input::get('orderId'))->where('Code', '=', Input::get('code'))->first();
     // If we have already made all the items of this type for this order inform user.
     if ($productionCount == $breakdown->Quantity) {
         return response()->json(['error' => 'Ya no es necesario crear mas ataudes de este tipo para esta orden!']);
     }
     // Check that we aren't producing more items with grips than necessary.
     $gripCount = 0;
     foreach ($production as $produced) {
         if ($produced->Grip) {
             $gripCount++;
         }
     }
     // If we have already created enough items of this type with grips for this order inform user.
     if ($gripCount == $breakdown->Grips) {
         return response()->json(['error' => 'Ya no es necesario crear mas ataudes de este tipo con agarraderos para esta orden!']);
     }
     // Now check that we aren't creating items without grips when there are only items with grips left to be created.
     if ($productionCount - $gripCount >= $breakdown->Quantity - $breakdown->Grips && Input::get('grip') == 'false') {
         return response()->json(['error' => 'Solo hace falta crear ataudes de este tipo con agarraderos para esta orden!']);
     }
     $grip = Input::get('grip') == 'true' ? true : false;
     // Get branchId.
     $branchId = Worker::find(Auth::user()->TypeId)->BranchId;
     // Now if all checks have been passed go ahead and create new item.
     $item = Production::create(array('OrderId' => Input::get('orderId'), 'Code' => Input::get('code'), 'Stage' => 1, 'Grip' => $grip, 'BranchId' => $branchId));
     // Now create the production stage and assign it to appropriate worker.
     ProductionStage::create(array('ProductionId' => $item->Id, 'Stage' => 1, 'WorkerId' => Input::get('workerId'), 'Materials' => '{}', 'Date' => date('Y-m-d H:i:s')));
     // Prepare response.
     $response = array();
     $response['productionId'] = $item->Id;
     return response()->json($response);
 }
 /**
  * Function that searches for past trips.
  *
  * @return Response
  */
 public function searchVehicleTrips()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('vehicle' => 'required', 'start' => 'required', 'end' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'Informacion incompleta!']);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Get trips.
     $start = date('Y-m-d', strtotime(Input::get('start')));
     $end = date('Y-m-d', strtotime(Input::get('end')));
     $trips = Transport::where('VehicleId', '=', Input::get('vehicle'))->where('Date', '>=', $start)->where('Date', '<=', $end)->where('State', '=', 1)->groupBy('Date')->orderBy('Order')->get();
     $tripData = array();
     foreach ($trips as $trip) {
         $driver = Worker::find($trip->DriverId);
         $reason = '';
         switch ($trip->Type) {
             case 1:
                 // Get sale breakdown.
                 $breakdown = SaleBreakdown::find($trip->ReasonId);
                 // Get product or service.
                 $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first();
                 if ($product) {
                     $reason = 'Venta de ' . $product->Description;
                 } else {
                     $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first();
                     $reason = 'Venta de ' . $service->Description;
                 }
                 break;
             case 2:
                 // Get sale.
                 $sale = Sale::find($trip->ReasonId);
                 // Get client or institution.
                 if ($sale->CreditorType == 1) {
                     if ($sale->CreditorId == 0) {
                         $reason = 'Venta a cliente no definido';
                     } else {
                         $client = Client::find($sale->CreditorId);
                         $reason = 'Venta a ' . $client->Name;
                     }
                 } else {
                     $institution = Institution::find($sale->CreditorId);
                     $reason = 'Venta a ' . $institution->Name;
                 }
                 break;
             case 3:
                 // Get order breakdown.
                 $breakdown = OrderBreakdown::find('OrderId', '=', $trip->ReasonId);
                 // Get product or service.
                 $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first();
                 $reason = 'Produccion de ' . $product->Description;
                 break;
             case 4:
                 // Get order.
                 $order = Order::find($trip->ReasonId);
                 // Get client or institution.
                 $client = Client::find($order->ClientId);
                 if ($client->InstitutionId == 0) {
                     $reason = 'Orden de Produccion de ' . $client->Name;
                 } else {
                     $institution = Institution::find($client->InstitutionId);
                     $reason = 'Orden de Produccion de ' . $institution->Name;
                 }
                 break;
             case 5:
                 // Get storage request.
                 $request = StorageRequest::find($trip->ReasonId);
                 $reason = $request->Reason;
                 break;
             case 6:
                 // Get visit.
                 $visit = Visit::find($trip->ReasonId);
                 $reason = 'Visita ' . $visit->Result;
                 break;
             case 7:
                 // Get credit bill.
                 $creditBill = Sale::find($trip->ReasonId);
                 $reason = 'Cobro de Facturo: ' . $creditBill->Id;
                 break;
             case 8:
                 // Contract Payment.
                 $contract = Contract::find($trip->ReasonId);
                 $reason = 'Cobro de Contrato: ' . $contract->Code;
                 break;
             case 9:
                 // Provider purchase.
                 $aiOrder = AIOrder::find($trip->ReasonId);
                 $reason = 'Compra automatica ' . $aiOrder->Id;
                 break;
             case 10:
                 $reason = 'Generado por usuario.';
                 break;
         }
         array_push($tripData, array('Id' => $trip->Id, 'Date' => $trip->Date, 'Driver' => $driver->Name, 'Reason' => $reason, 'Distance' => $trip->Distance, 'Journey' => json_decode($trip->Journey, true), 'StartLat' => $trip->StartLatitude, 'StartLon' => $trip->StartLongitude, 'EndLat' => $trip->EndLatitude, 'EndLon' => $trip->EndLongitude));
     }
     $response['state'] = 'Success';
     $response['trips'] = $tripData;
     return response()->json($response);
 }