Example #1
0
 function testGetAuthor()
 {
     $doc = $date = $duration = 0;
     $author = 'John Cena';
     $res = new Reservation($doc, $author, $date, $duration);
     $this->assertIdentical($res->getAuthor(), $author);
 }
 public function addReservation(Reservation $reservation)
 {
     if (!$this->roomIsFree($reservation->getStartDate(), $reservation->getEndDate())) {
         throw new EReservationException();
     }
     $this->reservations[] = $reservation;
 }
 /**
  * @param Reservation $instance
  * @param ReservationSeries $series
  * @param IReservedItemView $existingItem
  * @param BookableResource[] $keyedResources
  * @return bool
  */
 protected function IsInConflict(Reservation $instance, ReservationSeries $series, IReservedItemView $existingItem, $keyedResources)
 {
     if ($existingItem->GetId() == $instance->ReservationId() || $series->IsMarkedForDelete($existingItem->GetId()) || $series->IsMarkedForUpdate($existingItem->GetId())) {
         return false;
     }
     return parent::IsInConflict($instance, $series, $existingItem, $keyedResources);
 }
Example #4
0
function generate_vars($section, &$vars)
{
    $vars['ok'] = false;
    $vars['full'] = false;
    if (!isset($_GET['match_id']) || !isset($_GET['nombre_billet'])) {
        return;
    }
    $nombre_billet = $_GET['nombre_billet'];
    $match = Match::get($_GET['match_id']);
    if ($match == null || $nombre_billet <= 0) {
        return;
    }
    if ($match->places < $nombre_billet) {
        $vars['full'] = true;
        return;
    }
    $match->places = $match->places - $nombre_billet;
    $match->save();
    $reservation = new Reservation();
    $reservation->utilisateur = $vars['userid'];
    $reservation->match_id = $match->id;
    $reservation->qte = $nombre_billet;
    $reservation->expiration = 'now()';
    $reservation->save();
    $vars['ok'] = true;
}
Example #5
0
 public function uploadBankReceipt()
 {
     if (Input::hasFile('uploadReceipt')) {
         $data = array();
         if (is_array(Input::get('room_id'))) {
             foreach (Input::get('room_id') as $key => $val) {
                 $data[$key] = array('am_id' => Input::get('am_id.' . $key), 'rooms' => $val);
             }
         }
         $data2 = array();
         if (is_array(Input::get('add_Am'))) {
             foreach (Input::get('add_Am') as $key => $val) {
                 $data2[$key] = array('am_id' => Input::get('am_id.' . $key), 'rooms' => $val);
             }
         }
         $name = Input::get('packname');
         $price = Input::get('amount');
         $input_dFrom = Input::get('package_datefrom');
         $input_dTo = Input::get('package_dateto');
         $input_nPax = Input::get('num_pax');
         $input_fName = Input::get('fullN');
         $postData = new Reservation();
         $postData->dataInsertPost($name, $price, $input_dFrom, $input_dTo, $input_nPax, $input_fName, json_encode($data), 'Bank', json_encode($data2));
         $lastInsert = DB::getPdo()->lastInsertId();
         $files = Input::file('uploadReceipt');
         $i = 1;
         foreach ($files as $file) {
             try {
                 $path = public_path() . '\\uploads\\bank_deposit\\';
                 $extension = $file->getClientOriginalExtension();
                 $filename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                 $dateNow = date('Ymd_His');
                 $new_filename = Auth::user()->id . '_' . $filename . '_' . $i . '.' . $extension;
                 $upload_success = $file->move($path, $new_filename);
             } catch (Exception $ex) {
                 $path = public_path() . '/uploads/bank_deposit/';
                 $extension = $file->getClientOriginalExtension();
                 $filename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                 $dateNow = date('Ymd_His');
                 $new_filename = Auth::user()->id . '_' . $filename . '_' . $i . '.' . $extension;
                 $upload_success = $file->move($path, $new_filename);
             }
             $insertVal = array('image_fieldvalue' => $lastInsert, 'image_name' => $new_filename);
             $this->GlobalModel->insertModel('tbl_images', $insertVal);
             $i++;
         }
         $data = array('refNumber' => str_pad($lastInsert, 10, "0", STR_PAD_LEFT), 'package' => $name, 'amount' => '₱' . number_format($price, 2), 'paymentMethod' => 'Bank Deposit', 'status' => 1);
         try {
             Mail::send('emails.user.transactionReservation', $data, function ($message) use($data) {
                 $message->from('*****@*****.**', 'El Sitio Filipino');
                 $message->to(Auth::user()->user_email, Auth::user()->user_fname . ' ' . Auth::user()->user_lname)->subject('El Sitio Filipino Transaction Details');
             });
         } catch (Exception $ex) {
             dd($ex->getMessage());
         }
         return Response::json($data);
     }
 }
Example #6
0
 public function checkForValidReservation(Reservation $reservation)
 {
     foreach ($this->reservations as $existingReservation) {
         if ($reservation->getStartDate() >= $existingReservation->getStartDate() && $reservation->getStartDate() <= $existingReservation->getEndDate()) {
             throw new EReservationException($this->roomNumber, $reservation);
         } elseif ($reservation->getEndDate() >= $existingReservation->getStartDate() && $reservation->getEndDate() <= $existingReservation->getEndDate()) {
             throw new EReservationException($this->roomNumber, $reservation);
         }
     }
 }
 public function bindObject(Reservation $reservation)
 {
     $taintedValues = $reservation->toArray(BasePeer::TYPE_FIELDNAME);
     $taintedFiles = array();
     foreach ($taintedValues as $key => $value) {
         if (!isset($this->widgetSchema[$key])) {
             unset($taintedValues[$key]);
         }
     }
     $taintedValues[self::$CSRFFieldName] = $this->getCSRFToken(self::$CSRFSecret);
     $this->bind($taintedValues, $taintedFiles);
 }
 public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 10) as $index) {
         Reservation::create([]);
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     //
     try {
         $reservation = new Reservation();
         $reservation->name = Input::get('name');
         $reservation->sex = Input::get('sex');
         $reservation->phone = Input::get('phone');
         $reservation->email = Input::get('email');
         $reservation->note = Input::get('note');
         $reservation->save();
         return View::make('aesthetics.reservations.ok');
     } catch (Exception $e) {
         return Redirect::back()->withInput()->withErrors('新增失敗');
     }
 }
 public function testCreate()
 {
     $connection = Yii::app()->db;
     $sql = "delete from reservation";
     $command = $connection->createCommand($sql);
     $command->execute();
     $dateOverlapFromObj = new DateTime();
     $dateOverlapFrom = $dateOverlapFromObj->format('Y-m-d');
     $reservation = new Reservation();
     $reservation->setAttributes(array('roomid' => 1, 'datefrom' => $dateOverlapFrom, 'numberofnights' => 10, 'confirmreservation' => true));
     $id = $reservation->save();
     $reservationdetails = new Reservationdetails();
     $reservationdetails->setAttributes(array('reservationid' => $reservation->getAttribute('id'), 'title' => "Mr", 'firstname' => "John", 'lastname' => "Smith", 'contactnumber' => "0123456789", 'emailaddress' => "*****@*****.**", 'city' => "City", 'county' => "County", 'country' => "UK", 'postcode' => "ab12 4cd", 'postaddress' => 'Test postal address', 'otherinfo' => "Test"));
     $this->assertTrue($reservationdetails->save());
     return $reservationdetails;
 }
Example #11
0
 public function deleteAction()
 {
     $this->view->disable();
     $this->response->setContentType('text/plain', 'UTF-8');
     $Reservationid = $this->request->get('reservationid', 'string');
     $reservation = Reservation::findFirst(array('coditions' => 'id=?1', 'bind' => array(1 => $reservationid)));
     if ($reservation != null) {
         $available = $reservation->Available;
         if ($available->date == date('Y-m-d', strtotime('now'))) {
             $this->response->setContent('对不起,该预约单已经超过可取消日期');
             $this->response->send();
             return;
         } else {
             if ($reservation->delete() == false) {
                 $this->response->setContent('对不起,现在无法取消预约单');
                 $this->response->send();
                 return;
             } else {
                 $this->response->setContent('预约单取消成功');
                 $this->response->send();
                 return;
             }
         }
     }
 }
Example #12
0
 /**
  * Checks to see if any of the additional resources conflict
  * @param Reservation $res the reservation object to validate
  * @return An array of available_number and names of any conflicting resources
  */
 function checkAdditionalResources($res, $resources_to_add)
 {
     $return = array();
     $t = new Timer('get_additional_resource_count()');
     $t->start();
     //		$query = 'SELECT ar.resourceid, ar.name, ar.number_available '
     //				. ' FROM ' . $this->get_table(TBL_ADDITIONAL_RESOURCES) . ' ar'
     //				. ' WHERE resourceid IN (' . . ') AND ar.number_available = 0';
     $values = array($res->get_start_date(), $res->get_start_date(), $res->get_start(), $res->get_end_date(), $res->get_end_date(), $res->get_end(), $res->get_start_date(), $res->get_start_date(), $res->get_start(), $res->get_end_date(), $res->get_end_date(), $res->get_end(), $res->get_start_date(), $res->get_start_date(), $res->get_start(), $res->get_start_date(), $res->get_start_date(), $res->get_start(), $res->get_end_date(), $res->get_end_date(), $res->get_end(), $res->get_end_date(), $res->get_end_date(), $res->get_end());
     $resourceids = $this->make_del_list($resources_to_add);
     $id = $res->get_id();
     $and = '';
     if (!empty($id)) {
         $and = ' AND rr.resid <> ?';
         // Modifying this reservation
         array_unshift($values, $id);
     }
     $query = 'SELECT ar.resourceid, ar.name, ar.number_available, COUNT(*) AS total' . ' FROM ' . $this->get_table(TBL_RESERVATION_RESOURCES) . ' rr' . ' INNER JOIN ' . $this->get_table(TBL_ADDITIONAL_RESOURCES) . ' ar ON rr.resourceid = ar.resourceid' . ' INNER JOIN ' . $this->get_table(TBL_RESERVATIONS) . ' r ON r.resid = rr.resid' . ' WHERE rr.resourceid IN (' . $resourceids . ')' . ' AND ar.number_available <> -1 AND ar.number_available IS NOT NULL' . $and . ' AND (' . ' ( (start_date > ? OR (start_date = ? AND starttime > ?)) AND ( end_date < ? OR (end_date = ? AND endtime < ?)) )' . ' OR ( (start_date < ? OR (start_date = ? AND starttime < ?)) AND (end_date > ? OR (end_date = ? AND endtime > ?)) )' . ' OR ( (start_date < ? OR (start_date = ? AND starttime <= ?)) AND (end_date > ? OR (end_date = ? AND endtime > ?)) ) ' . ' OR ( (start_date < ? OR (start_date = ? AND starttime < ?)) AND (end_date > ? OR (end_date = ? AND endtime >= ?)) )' . ' )' . ' GROUP BY ar.resourceid, ar.name, ar.number_available' . ' HAVING COUNT(*) >= ar.number_available' . ' UNION ' . ' SELECT ar.resourceid, ar.name, ar.number_available, 0 AS total' . ' FROM ' . $this->get_table(TBL_ADDITIONAL_RESOURCES) . ' ar' . ' WHERE resourceid IN (' . $resourceids . ') AND ar.number_available = 0';
     $result = $this->db->query($query, $values);
     // Check if error
     $this->check_for_error($result);
     while ($rs = $result->fetchRow()) {
         $return[] = array('name' => $rs['name'], 'number_available' => $rs['number_available']);
     }
     $t->stop();
     $t->print_comment();
     return $return;
 }
Example #13
0
function generate_vars($section, &$vars)
{
    if (!$vars['is_logged']) {
        return;
    }
    if (isset($_GET['reservation_id'])) {
        $reservation = Reservation::get($_GET['reservation_id']);
        if ($reservation != null) {
            $match = $reservation->get_match();
            $match->places += $reservation->qte;
            $match->save();
            $reservation->delete();
        }
    } else {
        if (isset($_GET['tout_effacer'])) {
            $reservations = Reservation::filter_by_user($vars['userid']);
            foreach ($reservations as $reservation) {
                $match = $reservation->get_match();
                $match->places += $reservation->qte;
                $match->save();
                $reservation->delete();
            }
        }
    }
    $reservations = Reservation::filter_by_user($vars['userid']);
    $vars['reservations'] = $reservations;
    $cout_total = 0;
    foreach ($reservations as $reservation) {
        $cout_total += $reservation->get_match()->prix;
    }
    $vars['cout_total'] = $cout_total;
}
Example #14
0
 public function freePlaces()
 {
     $reservation = count(Reservation::filter_by_match($this->id));
     $achat = count(Achat::filter_by_match($this->id));
     $arena = $this->getArena();
     return $arena->largeur * $arena->profondeur - $reservation - $achat;
 }
 public function getColoredModStatusString()
 {
     $statusString = Reservation::modStatusToString($this->modStatus);
     if ($this->modStatus == RES_STATUS_CONFIRMED) {
         $status = "<font color=\"#005500\">" . $statusString . "</font>";
     } else {
         if ($this->modStatus == RES_STATUS_CHECKED_OUT) {
             $status = "<font color=\"#005500\">" . $statusString . "</font>";
         } else {
             if ($this->modStatus == RES_STATUS_CHECKED_IN) {
                 $status = "<font color=\"#005500\">" . $statusString . "</font>";
             } else {
                 if ($this->modStatus == RES_STATUS_PENDING) {
                     $status = $statusString;
                 } else {
                     if ($this->modStatus == RES_STATUS_DENIED) {
                         $status = "<font color=\"#FF0000\">" . $statusString . "</font>";
                     } else {
                         $status = "<font color=\"#FF0000\">" . $statusString . "</font>";
                     }
                 }
             }
         }
     }
     return $status;
 }
Example #16
0
 /**
  * handle object post request
  */
 private function handleObjectPost($objectType)
 {
     // add object to renderlist
     $this->plugin->addRenderList($objectType);
     $this->handleSubNavigation();
     $obj = $this->plugin->getObject($objectType);
     $obj->handleHttpPostRequest();
 }
 public function rejectPayment()
 {
     $_confirmPay = new Reservation();
     $dataId = Input::get('id');
     $_confirmPay->rejectReserv($dataId);
     $reservation = $_confirmPay->getReserv($dataId);
     $users = new User();
     $user = $users->getUserDetailById($reservation->created_by);
     $data = array('refNumber' => str_pad($dataId, 10, "0", STR_PAD_LEFT), 'package' => $reservation->pack_name, 'amount' => '₱' . number_format($reservation->total_amount, 2), 'paymentMethod' => $reservation->payment_method, 'status' => 4, 'email' => $user->user_email, 'name' => $user->user_fname . ' ' . $user->user_lname);
     try {
         Mail::send('emails.user.transactionReservation', $data, function ($message) use($data) {
             $message->from('*****@*****.**', 'El Sitio Filipino');
             $message->to($data['email'], $data['name'])->subject('El Sitio Filipino Transaction Details');
         });
     } catch (Exception $ex) {
     }
     return json_encode(['success' => $_confirmPay]);
 }
 public function get_reservation_status($reservation_id)
 {
     $response_data = $this->core_call("get_reservation_status", array("reservation_id" => array("id" => $reservation_id)));
     if (!$response_data['is_exception']) {
         return Reservation::create($response_data['result']);
     } else {
         die("ERROR: " . $response_data['message'] . "\n");
     }
 }
 public static function dropdown()
 {
     $properties = Reservation::orderBy('created_at', 'desc')->get();
     $nodes = array();
     foreach ($properties as $p) {
         $nodes[$p->id] = $p->id . ' | ' . $p->firstname . ' ' . $p->lastname;
     }
     return $nodes;
 }
 /**
  * this method is used to handle AJAX request for form submit
  */
 public function postForm()
 {
     try {
         if (!isset($_POST)) {
             throw new Exception('Error request [10]');
         }
         $name = \Arr::get($_POST, 'name', false);
         $sex = \Arr::get($_POST, 'sex', 'female');
         $phone = \Arr::get($_POST, 'phone', false);
         $email = \Arr::get($_POST, 'email', false);
         $note = \Arr::get($_POST, 'note', false);
         if (empty($name)) {
             throw new Exception('Error request [1100]');
         }
         if (empty($phone)) {
             throw new Exception('Error request [1101]');
         }
         if (empty($email)) {
             throw new Exception('Error request [1110]');
         } else {
             $reg = '/^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$/';
             if (preg_match($reg, $email) == false) {
                 throw new Exception('Error request [11101]');
             }
         }
         if (empty($note)) {
             throw new Exception('Error request [1101]');
         }
         $model = new \Reservation();
         $model->name = $name;
         $model->sex = $sex;
         $model->phone = $phone;
         $model->email = $email;
         $model->note = $note;
         if (!$model->save()) {
             throw new Exception("Error request [110]");
         }
         return \Response::json(array('status' => 'ok'));
     } catch (Exception $e) {
         return \Response::json(array('status' => 'error', 'message' => $e->getMessage()));
     }
 }
Example #21
0
 public static function reservation($id)
 {
     $user = self::get_user_logged_in();
     $service = Service::find_for_user($user, $id);
     if ($service == null) {
         Redirect::to(\Slim\Slim::getInstance()->urlFor('services_index'), array('message' => 'Palvelua ei löytynyt', 'error' => true));
     }
     $date_now = new DateTime();
     $current_time = new DateTime($service->opens_at);
     $end_time = new DateTime($service->closes_at);
     $current_time->add(new DateInterval("P1D"));
     $end_time->add(new DateInterval("P1D"));
     $unit = new DateInterval(sprintf("PT%dM", $service->reservation_unit));
     $reservations = array();
     $slot = 0;
     $future_reservations = Reservation::find_future_reservations($service);
     $taken_slots = array();
     foreach ($future_reservations as $reservation) {
         $taken_slots[$reservation->reserved_from->format('Y-m-d H:i:s')] = true;
     }
     while (true) {
         $current_time->add($unit);
         if ($current_time > $end_time) {
             break;
         } else {
             $current_time->sub($unit);
         }
         $reservations[$slot] = array();
         $current_date = new DateTime($current_time->format('Y-m-d H:i:s'));
         for ($i = 0; $i < 16; $i++) {
             $next_start = new DateTime($current_date->format('Y-m-d H:i:s'));
             $next_start->add($unit);
             $current_end = new DateTime($current_date->format('Y-m-d H:i:s'));
             $current_end->setTime(intval($end_time->format('H')), intval($end_time->format('i')));
             if ($next_start <= $current_end) {
                 $reservation = array();
                 $reservation['time_slot'] = $current_date->format('H:i') . '-' . $next_start->format('H:i');
                 $reservation['start'] = new DateTime($current_date->format('Y-m-d H:i:s'));
                 if (isset($taken_slots[$current_date->format('Y-m-d H:i:s')])) {
                     $reservation['taken'] = true;
                 } else {
                     $reservation['taken'] = false;
                 }
                 $diff = $date_now->diff($current_date);
                 $reservation['unavailable'] = $diff->d < 1;
                 array_push($reservations[$slot], $reservation);
             }
             $current_date->add(new DateInterval("P1D"));
         }
         $current_time->add($unit);
         $slot++;
     }
     View::make('service/reservation.html', array('service' => $service, 'reservations' => $reservations));
 }
Example #22
0
File: util.php Project: pheze/ydtp3
function clear_deprecated_reserved_matches()
{
    $MAX_TIME = 60 * 5;
    // 5 mins
    foreach (Reservation::find_all() as $reservation) {
        $diff = time() - strtotime($reservation->expiration);
        if ($diff > $MAX_TIME) {
            ajust_ticket_and_delete($reservation);
        }
    }
}
Example #23
0
 public function doprintAction()
 {
     $rid = $this->request->get('reservationid', 'int');
     $r = Reservation::findFirst(array('id=:rid:', 'bind' => array('rid' => $rid)));
     $user = $r->getUser();
     $available = $r->getAvailable();
     $doctor = $available->getDoctor();
     $department = $doctor->getDepartment();
     $hospital = $department->getHospital();
     $this->view->setVars(array('user' => $user, 'available' => $available, 'doctor' => $doctor, 'department' => $department, 'hospital' => $hospital, 'reservation' => $r));
 }
 public function run()
 {
     $tableIds = Table::whereAvailable(1)->lists('id');
     $userIds = User::lists('id');
     $faker = Faker::create();
     $tablesUsed = [];
     foreach ($tableIds as $tableId) {
         $start = Carbon::now()->startOfDay();
         $reservationStart = $start->addHours(rand(0, 720));
         //$active = ($reservationStart->isToday()) ? 1 : 0;
         Reservation::create(['user_id' => $faker->randomElement($userIds), 'table_id' => $tableId, 'reservation_start' => $reservationStart, 'reservation_end' => $start->addHours(3), 'seats' => $faker->randomElement([2, 4, 8]), 'active' => 1]);
     }
 }
Example #25
0
 public static function index()
 {
     $user = self::get_user_logged_in();
     $reservations = null;
     $invoices = null;
     $utilization_rates = null;
     if ($user) {
         $reservations = $user->manager ? Reservation::all_future(null, 5, false) : Reservation::all_future($user->id, 5, false);
         $invoices = $user->manager ? Invoice::all(5) : Invoice::all_for_user($user->id, 5);
         $utilization_rates = $user->manager ? Service::utilization_rates() : null;
     }
     View::make('index.html', array('reservations' => $reservations, 'invoices' => $invoices, 'utilization_rates' => $utilization_rates));
 }
    public function populate($roomType, $dates)
    {
        $this->roomType = $roomType;
        foreach ($dates as $date) {
            $criteria = new CDbCriteria();
            $criteria->condition = ':date between dateFrom and dateTo 
									and roomid=:roomId
									and confirmreservation=true';
            $criteria->params = array(":date" => $date, ":roomId" => $this->roomType->id);
            $result = Reservation::model()->findAll($criteria);
            $this->reservations[$date] = $result;
        }
    }
Example #27
0
 public static function envoyerMessageA($id_trajet)
 {
     $database = UsineBDD::getUsine()->connection();
     $passagers = Reservation::getUtilisateurReservation($id_trajet);
     $info = Trajet::getInformationTrajet($id_trajet)[0];
     $date = date('d-n-Y H:i', $info['timestamp_trajet']);
     $message = "Le trajet " . $info['ville_depart'] . '-' . $info['ville_arrive'] . 'du ' . $date . 'a été annulé ! Vous avez recu 10€ en dédomagement';
     foreach ($passagers as $array => $passager) {
         $sql_message = "INSERT INTO messagerie VALUES('',:ide,:idd,:c,:t,'')";
         $requete = $database->prepare($sql_message);
         $requete->execute(array(':ide' => Utilisateur::getUtilisateurId(), ':idd' => $passager['id_membre'], ':c' => $message, ':t' => time()));
     }
 }
Example #28
0
function generate_vars($section, &$vars)
{
    $vars['success'] = false;
    if (!$vars['is_logged']) {
        return;
    }
    if (!isset($_GET['id']) || !isset($_GET['i']) || !isset($_GET['j'])) {
        return;
    }
    $id_match = $_GET['id'];
    $rangee = $_GET['i'];
    $siege = $_GET['j'];
    $userid = $vars['userid'];
    $reservation = new Reservation();
    $reservation->utilisateur = $userid;
    $reservation->id_match = $id_match;
    $reservation->expiration = 'now()';
    $reservation->rangee = $rangee;
    $reservation->siege = $siege;
    $reservation->save();
    $vars['success'] = true;
}
 /**
  * create and insert a new review into database
  * @param array $fields review info from form post
  */
 function create($fields = array())
 {
     // check input
     if (empty($fields)) {
         throw new Exception("Argument is incorrect");
     }
     // if (empty($fields['content'])) {
     //     $fields['message'] = "";
     // }
     // if (empty($fields['restaurant_id']) ||
     //     empty($fields['title']) ||
     //     empty($fields['content']) ||
     //     empty($fields['rating']) ||
     //     empty($fields['user_id']) ) {
     //     throw new Exception("Error Input!");
     // }
     date_default_timezone_set('America/Los_Angeles');
     $fields['date'] = date("Y-m-d H:i:s", time());
     // check if user has made reservation already
     $restaurant_id = intval($fields['restaurant_id']);
     $user_id = intval($fields['user_id']);
     $rsv = new Reservation();
     $ret = $rsv->if_rsved_restaurant($restaurant_id, $user_id);
     if (!$ret) {
         throw new Exception("Error occured when creating review, user has not made reservation yet!");
     }
     // check if user has reviewed already
     $where = 'user_id = "' . $fields['user_id'] . '" AND ' . 'restaurant_id = "' . $fields['restaurant_id'] . '"';
     if ($this->any_duplicates($where)) {
         throw new Exception("User has already reviewed this restaurant!");
     }
     // insert to db
     $ret = $this->insert($this->_table_name, $fields);
     if ($ret <= 0) {
         throw new Exception("Error occurred when communicating with database, please try again!");
     }
     return $ret;
 }
 public function postCreateReservation()
 {
     // $today = date("Y-m-d");
     /* validate input */
     $validator = Validator::make(Input::all(), array('date' => 'required|date_format:Y-m-d', 'time' => 'required|date_format:H:i', 'numbers' => 'required|integer|between:1,64', 'phonenumber' => 'required'), array('required' => 'The :attribute is required.', 'date.date_format:Y-m-d' => 'The date need to be formatted "dd-mm-yyyy".', 'date.after' => 'You date is invalid.', 'time.date_format:H:i' => 'The time need to be formatted "hh:mm".', 'numbers.integer' => 'We need to know number of people in your reservation.', 'numbers.between:1,64' => 'We can only serve maximum 64 people.'));
     /* if validated */
     if ($validator->passes()) {
         /* get input */
         $reservation = new Reservation();
         $reservation->user_id = Input::get('user_id');
         $reservation->date = Input::get('date');
         $reservation->time = Input::get('time');
         $reservation->numbers = Input::get('numbers');
         $reservation->phonenumber = Input::get('phonenumber');
         $reservation->requirements = Input::has('requirements') ? Input::get('requirements') : '';
         $reservation->save();
         return Response::json(array('message' => array('Your reservation is sent successfully. We will contact with you soon to confirm. Thank you!')), 200);
     } else {
         $messages = $validator->messages()->all();
         return Response::json(array('message' => $messages), 400);
     }
     // end validation
 }