| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- $page_title = "Add Location";
- $customer = Customer::getForAdmin();
- if(!$customer) throw new Exception("You do not have permission to access this page.");
- Core::addBreadcrumb("/account", "Account");
- Core::addBreadcrumb("/account/locations", "Locations");
- Core::addBreadcrumb("/account/locations?customer_id=$customer->id", "$customer->name Locations");
- Core::addBreadcrumb("/account/locations/add", $page_title);
- $location = new Location;
- $location->customer_id = $customer->id;
- $submit = http::value("submit");
- if($submit) {
- try {
- Core::validateCSRFToken($submit);
- $form_exception = new FormException;
- $location->name = http::value("name", "trim");
- $location->address_1 = http::value("address", "trim");
- if(empty($location->name)) $form_exception->addError("Name is required.");
- if(empty($location->address_1)) {
- $form_exception->addError("Full address is required.");
- }
- else {
- // Geocode the full address
- try {
- $results = Geolocation::geocode($location->address_1);
- $result = $results[0];
- foreach($result->address_components as $component) {
- $types = $component->types;
- if(in_array("postal_code", $types)) $location->postal_code = $component->long_name;
- if(in_array("route", $types)) $location->address_1 = $component->long_name;
- if(in_array("postal_town", $types)) $location->city = $component->long_name;
- if(in_array("administrative_area_level_1", $types)) $location->state = $component->long_name;
- if(in_array("country", $types)) $location->country = $component->long_name;
- }
- $location->latitude = $result->geometry->location->lat;
- $location->longitude = $result->geometry->location->lng;
- }
- catch(Exception $e) {
- $form_exception->addError("Failed to get location from full address: " . $e->getMessage());
- }
- }
- if($form_exception->hasErrors()) throw $form_exception;
- $success = $location->commit();
- if(!$success) throw new Exception("Failed to add location at this time. Please try again later.");
- Core::addAlert("success", "Location added successfully.");
- HTTP::redirect("/account/locations/$location->id");
- }
- catch(FormException $e) {
- $e->generateAlerts();
- }
- catch(Exception $e) {
- Core::addAlert("danger", $e->getMessage());
- }
- }
- View::includeOnce("header", compact("page_title"));
- View::include("location_add_form", compact("location"));
- View::includeOnce("footer");
- ?>
|