/**
  * Function that makes a reservation.
  *
  * @return Response
  */
 public function makeReservation()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('items' => 'required', 'institution' => 'required', 'discount' => 'required', 'reservationAmount' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'No se envio la informacion completa!']);
     }
     // 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(['state' => 'Unauthorized']);
     }
     // Get user branch.
     $worker = Worker::find(Auth::user()->TypeId);
     $userBranch = $worker->BranchId;
     $reservationPrice = 0;
     $branch = Branch::find($userBranch);
     // Get the user's cashbox.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     // Check that we actually have a cashbox open.
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'La caja no esta abierta o por lo tanto no se puede realizar la reservacion!';
         return response()->json($response);
     }
     // Check discount is not greater than what user is allowed.
     $permissions = json_decode(UserLevel::find(Auth::user()->UserLevel)->Permissions);
     if (Input::get('discount') > $permissions->permissions->sales->discount->limit) {
         // Check if we have an auth code we can use.
         if (Input::get('authCode') == 0) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         $request = Request::find(Input::get('authCode'));
         if ($request->Used == 1) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         if ($request->Amount != Input::get('discount')) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         $request->Used = 1;
         $request->save();
     }
     // Get client.
     $client = Client::where('Cedula', '=', Input::get('client'))->first();
     // Get institution if defined.
     $institution;
     if (Input::get('institution') != 0) {
         $institution = Institution::find(Input::get('institution'));
         if (!$institution) {
             $response['state'] = 'Error';
             $response['error'] = 'La institucion definida no fue encontrada en el sistema!';
             return response()->json($response);
         }
     }
     // Loop through products and services and get prices.
     $items = json_decode(Input::get('items'));
     foreach ($items as $code => $info) {
         // Check if it is a product.
         $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Check if it is a service.
             $service = Service::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
             if (!$service) {
                 $response['state'] = 'Error';
                 $response['error'] = 'No se reconocio uno de los productos o servicios!';
                 return response()->json($response);
             }
             // Add price to total of quotation.
             $reservationPrice += $service->Price * $info->quantity;
         } else {
             // Add price to total of quotation.
             $reservationPrice += $product->Price * $info->quantity;
         }
     }
     $subTotal = $reservationPrice;
     $discount = $reservationPrice * (Input::get('discount') / 100);
     // Give discount.
     $reservationPrice = $reservationPrice * (1 - Input::get('discount') / 100);
     // Calculate tax if required.
     $tax = 0;
     if (json_decode($branch->DefaultExpenses)->regimen == 'cuotageneral') {
         if (Input::get('institution') != 0) {
             if (!$institution->Excempt) {
                 $tax = $salePrice * 0.15;
             }
         } else {
             if (!$client || !$client->Excempt) {
                 $tax = $salePrice * 0.15;
             }
         }
     }
     // Save client information.
     $clientInfo = array();
     if (Input::get('institution') != 0) {
         // Save institution information.
         $clientInfo = array('Name' => $institution->Name, 'Address' => $institution->Address, 'Id' => $institution->RUC);
     } else {
         // Save institution information.
         if ($client) {
             $clientInfo = array('Name' => $client->Name, 'Address' => $client->Address, 'Id' => $client->Cedula);
         }
     }
     // Get reservation info.
     $config = Configuration::find(0);
     // Check that the deposit covers the minimum.
     if (Input::get('reservationAmount') < $config->Dollar * $config->MinimumReservation) {
         $response['state'] = 'Error';
         $response['error'] = 'El deposito minimo para realizar la reservacion es de ' . $config->Dollar * $config->MinimumReservation . ' Cordobas o ' . $config->MinimumReservation . ' Dolares Americanos.';
         return response()->json($response);
     }
     // Make Reservation.
     $reservation;
     if (Input::get('institution') != 0) {
         // Creditor Type 1 = Client, 2 = Institution.
         $reservation = Reservation::create(array('WorkerId' => $worker->Id, 'Value' => $reservationPrice, 'Discount' => Input::get('discount'), 'Tax' => $tax, 'CreditorId' => Input::get('institution'), 'CreditorType' => 2, 'TransactionId' => 0, 'State' => 'fresh', 'Life' => $config->ReservationLife, 'Deposit' => Input::get('reservationAmount')));
     } else {
         if (!$client) {
             $reservation = Reservation::create(array('WorkerId' => $worker->Id, 'Value' => $reservationPrice, 'Discount' => Input::get('discount'), 'Tax' => $tax, 'CreditorId' => 0, 'CreditorType' => 1, 'TransactionId' => 0, 'State' => 'fresh', 'Life' => $config->ReservationLife, 'Deposit' => Input::get('reservationAmount')));
         } else {
             $reservation = Reservation::create(array('WorkerId' => $worker->Id, 'Value' => $reservationPrice, 'Discount' => Input::get('discount'), 'Tax' => $tax, 'CreditorId' => $client->Id, 'CreditorType' => 1, 'TransactionId' => 0, 'State' => 'fresh', 'Life' => $config->ReservationLife, 'Deposit' => Input::get('reservationAmount')));
         }
     }
     // Now that the reservation has been created, create the transaction for it.
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 9, 'Amount' => Input::get('reservationAmount'), 'Reason' => 'Deposito de Reservacion: ' . $reservation->Id . '.'));
     $reservation->TransactionId = $transaction->Id;
     $reservation->save();
     // Loop through items and add them to Reservation Breakdown.
     foreach ($items as $code => $info) {
         // Check if product.
         $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Get service cost.
             $service = Service::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
             ReservationBreakdown::create(array('ReservationId' => $reservation->Id, 'Code' => $code, 'Quantity' => $info->quantity, 'Price' => $service->Price));
         } else {
             ReservationBreakdown::create(array('ReservationId' => $reservation->Id, 'Code' => $code, 'Quantity' => $info->quantity, 'Price' => $product->Price));
         }
     }
     // Return success message and return quotation information.
     $response['state'] = 'Success';
     $response['reservationInfo'] = array('SubTotal' => $subTotal, 'Discount' => $discount, 'Tax' => $tax, 'Total' => $reservationPrice + $tax, 'ReservationId' => $reservation->Id, 'Date' => date('d/m/Y'), 'Life' => $config->ReservationLife, 'Deposit' => Input::get('reservationAmount'));
     $response['clientInfo'] = $clientInfo;
     return response()->json($response);
 }
<?php

use App\ReservationBreakdown;
use App\Stock;
use App\Service;
use App\Worker;
// Get the worker and branch.
$worker = Worker::find(Auth::user()->TypeId);
$userBranch = $worker->BranchId;
// Get the breakdown of the reservation.
$reservationBreakdown = ReservationBreakdown::where('ReservationId', '=', $id)->get();
function getName($code, $branch)
{
    // Try getting a normal product for this code
    $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $branch)->first();
    if (!$product) {
        // If we failed try getting a service.
        $service = Service::where('Code', '=', $code)->where('BranchId', '=', $branch)->first();
        return $service->Description;
    }
    return $product->Description;
}
?>
<thead>
	<tr><th>Producto</th><th>Precio Individual</th><th>Cantidad</th></tr>
</thead>
<tbody>
	@foreach($reservationBreakdown as $breakdown)
		<tr><td>{{ getName($breakdown->Code, $userBranch) }}</td><td>{{ $breakdown->Price }}</td><td>{{ $breakdown->Quantity }}</td></tr>
	@endforeach
</tbody>
 /**
  * Function that gets reservation information.
  *
  * @return Response
  */
 public function getReservationData()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('id' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'No se recibieron los datos necesarios!']);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         $response['state'] = 'No Autorizado';
         $response['error'] = 'Usuario no autorizado!';
         return response()->json($response);
     }
     // Get user branch.
     $worker = Worker::find(Auth::user()->TypeId);
     $userBranch = $worker->BranchId;
     // Get the reservation.
     $reservation = Reservation::find(Input::get('id'));
     // Get the breakdown of the reservation.
     $reservationBreakdown = ReservationBreakdown::where('ReservationId', '=', $reservation->Id)->get();
     $reservationItems = array();
     foreach ($reservationBreakdown as $breakdown) {
         // Try getting the product.
         $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // If it's not a product it's a service.
             $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
             array_push($reservationItems, array('quantity' => $breakdown->Quantity, 'description' => $service->Description, 'price' => $service->Price));
         } else {
             array_push($reservationItems, array('quantity' => $breakdown->Quantity, 'note' => $product->Description, 'price' => $product->Price));
         }
     }
     // Get the client's or institution's information.
     $client;
     if ($reservation->CreditorId != 0) {
         if ($reservation->CreditorType != 1) {
             $temp = Institution::find($reservation->CreditorId);
             $client = array('Name' => $temp->Name, 'Address' => $temp->Address, 'Id' => $temp->RUC);
         } else {
             $temp = Client::find($reservation->CreditorId);
             $client = array('Name' => $temp->Name, 'Address' => $temp->Address, 'Id' => $temp->Id);
         }
     } else {
         $client = array('Name' => 'No asignado', 'Address' => 'No asignado', 'Id' => 'No asignado');
     }
     // Get configuration info.
     $config = Configuration::find(0);
     //  Now prepare all the information to be returned to user.
     $response['state'] = 'Success';
     $response['clientInfo'] = $client;
     $response['reservationInfo'] = array('Date' => date('Y-m-d', strtotime($reservation->Created)), 'Life' => $config->ReservationLife, 'ReservationId' => $reservation->Id, 'SubTotal' => $reservation->Value, 'Discount' => $reservation->Discount, 'Tax' => $reservation->Tax, 'Deposit' => $reservation->Deposit, 'Total' => $reservation->Value + $reservation->Tax - $reservation->Discount);
     $response['reservationItems'] = $reservationItems;
     // Return response.
     return response()->json($response);
 }