public async Task <IHttpActionResult> PostCompany(CompanyBindingModel model)
        {
            // Get the current User
            var user = db.Users.Find(User.Identity.GetUserId());

            // Get the users owner profile
            var owner      = user.Profiles.OfType <Owner>().FirstOrDefault();
            var driver     = user.Profiles.OfType <Driver>().FirstOrDefault();
            var manager    = user.Profiles.OfType <Manager>().FirstOrDefault();
            var accountant = user.Profiles.OfType <Accountant>().FirstOrDefault();

            // Get existing addresses with the same PlaceId
            var existingAddress = db.Addresses.FirstOrDefault(a => a.PlaceId == model.PlaceId);

            Address address;

            // Is there any addresses?
            if (existingAddress == null)
            {
                // No so we need to check with Google and get the details
                var addressResult = await GeocodingService.GetAddress(model.PlaceId);

                // Create the new Address in database
                address = new Address
                {
                    Id          = Guid.NewGuid(),
                    PlaceId     = addressResult.PlaceId,
                    Coordinates = new Coordinates
                    {
                        Id        = Guid.NewGuid(),
                        Latitude  = addressResult.Latitude,
                        Longitude = addressResult.Longitude
                    }
                };
            }
            else
            {
                // Theres an existing adress stored so use that one
                address = existingAddress;
            }

            // Setup the new company
            var newCompany = new Company
            {
                Id                 = Guid.NewGuid(),
                Name               = model.Name,
                AutoAccept         = model.AutoAccept,
                HighRate           = model.HighRate,
                LowRate            = model.LowRate,
                Vat                = model.Vat,
                VatNumber          = model.VatNumber,
                Address            = address,
                AutoAcceptDistance = model.AutoAcceptDistance,
                Owner              = owner,
                Personal           = false
            };

            // Add the owners profiles to the company
            newCompany.Profiles.Add(driver);
            newCompany.Profiles.Add(manager);
            newCompany.Profiles.Add(accountant);

            // Save the changes
            await db.SaveChangesAsync();

            // Return the new company's details
            return(Ok(new CompanyViewModel
            {
                Id = newCompany.Id.ToString(),
                Name = model.Name,
                HighRate = model.HighRate,
                LowRate = model.LowRate,
                Personal = false
            }));
        }
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var existingAddress = db.Addresses.FirstOrDefault(a => a.PlaceId == model.PlaceId);

            Address address;

            if (existingAddress == null)
            {
                var addressResult = await GeocodingService.GetAddress(model.PlaceId);

                address = new Address
                {
                    Id          = Guid.NewGuid(),
                    PlaceId     = addressResult.PlaceId,
                    Coordinates = new Coordinates
                    {
                        Id        = Guid.NewGuid(),
                        Latitude  = addressResult.Latitude,
                        Longitude = addressResult.Longitude
                    }
                };
            }
            else
            {
                address = existingAddress;
            }

            var user = new ApplicationUser
            {
                UserName  = model.Email,
                Email     = model.Email,
                FirstName = model.FirstName,
                LastName  = model.LastName
            };

            var result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            var dbuser = db.Users.Find(user.Id);

            dbuser.Address = address;

            var owner = new Owner
            {
                Id = Guid.NewGuid()
            };
            var accountant = new Accountant
            {
                Id = Guid.NewGuid()
            };
            var manager = new Manager
            {
                Id = Guid.NewGuid()
            };
            var driver = new Driver
            {
                Id = Guid.NewGuid()
            };

            var personalCompany = new Company
            {
                Id                 = Guid.NewGuid(),
                Name               = "Personal",
                AutoAccept         = true,
                HighRate           = 0.45M,
                LowRate            = 0.25M,
                Address            = address,
                AutoAcceptDistance = 160934,
                Personal           = true,
                Vat                = false
            };

            personalCompany.Profiles.Add(driver);

            owner.Companies.Add(personalCompany);

            dbuser.Profiles.Add(owner);
            dbuser.Profiles.Add(accountant);
            dbuser.Profiles.Add(manager);
            dbuser.Profiles.Add(driver);
            try
            {
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                var m = ex.Message;
            }
            var hostname = Request.RequestUri.Host;

            //var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            //var callbackUrl = "http://" + hostname + "/Account/ConfirmEmail?userId=" + user.Id +
            //                  "&code=" + code;

            //await UserManager.SendEmailAsync(user.Id, "Welcome to MileEyes", callbackUrl);

            return(Ok());
        }
        public async Task <IHttpActionResult> PostJourney(JourneyBindingModel model)
        {
            // Check Model State
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Get User and then Driver Profile
            var user = db.Users.Find(User.Identity.GetUserId());

            var driver = user.Profiles.OfType <Driver>().FirstOrDefault();

            // Get Company
            var company = db.Companies.Find(Guid.Parse(model.Company.CloudId));

            if (company == null)
            {
                return(BadRequest());
            }

            // Get Vehicle
            var vehicle = db.Vehicles.Find(Guid.Parse(model.Vehicle.CloudId));

            if (vehicle == null)
            {
                return(BadRequest());
            }

            // Create new Journey
            var j = new Journey()
            {
                Id         = Guid.NewGuid(),
                Driver     = driver,
                Accepted   = false,
                Rejected   = false,
                Company    = company,
                Vehicle    = vehicle,
                Date       = model.Date,
                Distance   = model.Distance,
                Reason     = model.Reason,
                Invoiced   = model.Invoiced,
                Passengers = model.Passengers
            };

            // Loop through Waypoints in Model
            foreach (var w in model.Waypoints)
            {
                // Create new Waypoint
                var newWaypoint = new Waypoint()
                {
                    Id        = Guid.NewGuid(),
                    Step      = w.Step,
                    Timestamp = w.Timestamp
                };

                // Check if Model Waypoint has a PlaceId
                if (!string.IsNullOrEmpty(w.PlaceId))
                {
                    // Get existing Addresses with PlaceId
                    var existingAddresses = db.Addresses.Where(a => a.PlaceId == w.PlaceId);

                    //Check if weve already stored the Address
                    if (existingAddresses.Any())
                    {
                        newWaypoint.Address = existingAddresses.FirstOrDefault();
                    }
                    // Deal with us not having Address stored
                    else
                    {
                        var addressResult = await GeocodingService.GetAddress(w.PlaceId);

                        // Create a new Address
                        newWaypoint.Address = new Address()
                        {
                            Id          = Guid.NewGuid(),
                            PlaceId     = addressResult.PlaceId,
                            Coordinates = new Coordinates()
                            {
                                Id        = Guid.NewGuid(),
                                Latitude  = addressResult.Latitude,
                                Longitude = addressResult.Longitude
                            }
                        };
                    }
                }
                // Deal with having no PlaceId
                else
                {
                    var existingAddresses =
                        db.Addresses.Where(
                            a =>
                            Math.Abs(a.Coordinates.Latitude - w.Latitude) < 0.0005 &&
                            Math.Abs(a.Coordinates.Longitude - w.Longitude) < 0.0005);
                    //Check if weve already stored the Address
                    if (existingAddresses.Any())
                    {
                        newWaypoint.Address = existingAddresses.FirstOrDefault();
                    }
                    // Deal with us not having Address stored
                    else
                    {
                        var addressResult = await GeocodingService.GetAddress(w.Latitude, w.Longitude, w.Step);

                        if (addressResult == null)
                        {
                            break;
                        }

                        // Create a new Address
                        newWaypoint.Address = new Address()
                        {
                            Id          = Guid.NewGuid(),
                            PlaceId     = addressResult.PlaceId,
                            Coordinates = new Coordinates()
                            {
                                Id        = Guid.NewGuid(),
                                Latitude  = addressResult.Latitude,
                                Longitude = addressResult.Longitude
                            }
                        };
                    }
                }
                newWaypoint.Journey = j;
                j.Waypoints.Add(newWaypoint);
            }

            // Calculate Cost and VAT
            j.Cost    = j.CalculateCost();
            j.FuelVat = j.CalculateFuelVat();

            // Add Journey to the Database
            j = db.Journeys.Add(j);

            // Save Changes
            await db.SaveChangesAsync();

            // Return Journey with new Id
            return(Ok(new JourneyViewModel()
            {
                Accepted = j.Accepted,
                Company = new CompanyViewModel()
                {
                    Id = j.Company.Id.ToString()
                },
                Cost = Convert.ToDouble(j.Cost),
                Date = j.Date,
                Distance = j.Distance,
                Id = j.Id.ToString(),
                Invoiced = j.Invoiced,
                Passengers = j.Passengers,
                Reason = j.Reason,
                Rejected = j.Rejected,
                Waypoints = j.Waypoints.Select(w => new WaypointViewModel()
                {
                    Latitude = w.Address.Coordinates.Latitude,
                    Longitude = w.Address.Coordinates.Longitude,
                    PlaceId = w.Address.PlaceId,
                    Step = w.Step,
                    Timestamp = w.Timestamp,
                    Id = w.Id.ToString()
                }).ToList()
            }));
        }