public ActionResult UpdatePickup(Pickup pickup)
        {
            // get the current user 
            //
            string currentUserId = User.Identity.GetUserId();
            string fullName = null;
            try
            {
                
                // Get info for Current user
                //
                ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
                
                // Get user's full name to notify others
                //
                fullName = currentUser.FirstName + " " + currentUser.LastName;


            }
            catch (Exception ex)
            {

                Debug.Write("Error autheticating user: "******"none";

                        // Update Comnpany Data
                        //
                        newItem.Company = "ZFM";

                        db2.Items.Add(newItem);
                    }
                }

                try
                {
                    db2.SaveChanges();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    // Provide for exceptions.
                }

                #endregion

                pickup.LastEditBy = fullName;
                
                //Azure time conversion
                //
                DateTime timeUtc = DateTime.UtcNow;
                TimeZoneInfo pstZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
                DateTime pstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, pstZone);

                pickup.LastModified = pstTime;


                //BMK Pickup Completed
                //
                if (pickup.Status.ToLower().Contains("completed") || pickup.Status.ToLower().Contains("closed"))
                {
                    pickup.Closed = pstNow();
                    pickup.ClosedBy = fullName;


                    // then delete all the pictures if any
                    foreach (var item in pickup.Items)
                    {
                        // Get file and erase
                        if (!String.IsNullOrEmpty(item.Picture1) && item.Picture1 != "none")
                        {
                            // Get file name
                            var file = Path.GetFileName(item.Picture1);
                            // Create Path

                            var path = Path.Combine(Server.MapPath("/Content/Photos/"), file);

                            // Erase File
                            FileInfo fi1 = new FileInfo(path);

                            if (fi1.Exists)     // check  if its there and delete
                                fi1.Delete();

                        }
                    }


                }

                //BMK Pickup Completed with SMS
                //
                if (pickup.Status.ToLower().Contains("completed sms") || pickup.Status.ToLower().Contains("closed sms"))
                {
                    
                    // Update the Status 
                    //
                    pickup.Closed = pstNow();
                    pickup.ClosedBy = fullName;

                    // Get the Sales Rep Number
                    //
                    ApplicationUser salesRep4PU = db.Users.FirstOrDefault(x => x.FirstName + " " + x.LastName == pickup.Rep);

                    // Get user's full name to notify others
                    //
                    string repSMS = salesRep4PU.CellNumber;


                    // Get the Courier Number
                    //
                    ApplicationUser courierSMS = db.Users.FirstOrDefault(x => x.FirstName + " " + x.LastName == pickup.TransporterName);

                    // Get user's full name to notify others
                    //
                    string trasportSMS = courierSMS.CellNumber;


                    // Cleanup
                    //
                    salesRep4PU = null;
                    courierSMS = null;

                    // Add the Prefix ( +1 ) if the numbers don't have them 
                    //
                    if(repSMS.Substring(0, 2) != "+1")
                        repSMS = "+1" + repSMS;

                    if (trasportSMS.Substring(0, 2) != "+1")
                        trasportSMS = "+1" + trasportSMS;
                    
                    // Send the SMS alert
                    //
                    
                    // Find your Account Sid and Auth Token at twilio.com/user/account
                    //
                    string AccountSid = "AC1ac0db79f475dc98b90b50a4f245217f";
                    string AuthToken = "b6c641704a0678be31dc089173aae90a";

                    var twilio = new TwilioRestClient(AccountSid, AuthToken);
                    //var message = twilio.SendMessage(repSMS, trasportSMS, "Pickup #: " + pickup.PickupNumber + " - Closed by: " + pickup.ClosedBy , " -> NOTES: " + pickup.Notes);
                    //var message = twilio.SendMessage( "+15107882884",  repSMS + "," + trasportSMS, "Hello World");

                    // Send Message to Sales Rep
                    //
                    var messageRep = twilio.SendMessage("+15107882884", repSMS, "Pickup #: " + pickup.PickupNumber + "\n\nClosed by: " + pickup.ClosedBy + "\n\n" + pickup.Notes);
                        

                     // Send Message to Courier
                     //
                    var messageCourier = twilio.SendMessage("+15107882884", trasportSMS, "Pickup #: " + pickup.PickupNumber + "\n\nClosed by: " + pickup.ClosedBy + "\n\n" + pickup.Notes);
                     

                     if (messageRep.RestException != null || messageCourier.RestException != null)
                    {

                        
                        // handle the error ...
                        //
                            Debug.Print(messageRep.RestException.Message);
                            Debug.Print(messageCourier.RestException.Message);
                    }



                    // then delete all the pictures if any
                    foreach (var item in pickup.Items)
                    {
                        // Get file and erase
                        if (!String.IsNullOrEmpty(item.Picture1) && item.Picture1 != "none")
                        {
                            // Get file name
                            var file = Path.GetFileName(item.Picture1);
                            // Create Path

                            var path = Path.Combine(Server.MapPath("/Content/Photos/"), file);

                            // Erase File
                            FileInfo fi1 = new FileInfo(path);

                            if (fi1.Exists)     // check  if its there and delete
                                fi1.Delete();

                        }
                    }


                }


                db2.Entry(pickup).State = EntityState.Modified;
                db2.SaveChanges();

                // Check if the Location Already Exists
                //
                var locationCheck = (from l in db2.Locations
                                     where l.Name.Contains(pickup.LocationName)
                                     select l);

                if (locationCheck.Count() == 0)
                {
                    // Add it to the Locations database
                    Location newLocatioEntry = new Location
                    {
                        Name = pickup.LocationName

                    };
                    db2.Locations.Add(newLocatioEntry);
                    db2.SaveChanges();
                }

                // Send Message To All Users To Update Pickup List
                //              
                string updatedPickup = pickup.PickupNumber.ToString();  // Get Pickup Number

                var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<ZTRAK.Hubs.PickupHub>();
                hub.Clients.All.newDataUpdate(fullName, updatedPickup);

                return Json(pickup.ID);

                #endregion
            }
            else
            {
                #region Create a new Pickup

                // Determine if this is a new pickup
                //
                if (pickup.ID == 0)
                {

                    // Convert the pickup to a list so we can remove items if needed
                    //
                    foreach (var item in pickup.Items.ToList())
                    {
                        // Remove Items marked
                        if (item.Qty == 0)
                        {
                            pickup.Items.Remove(item);

                        }
                    }

                    // Update the Company Name for new pickup
                    //
                    pickup.Company = "ZFM";

                    // Save new pickup - fix ID and proceed to save
                    // Calculate the new PickupID and assign it to the new pickup in order to 
                    // avoid drastic number changes
                    var pUcount = (from r in db2.Pickups
                                 where r.ID != null
                                 select r).Count() + 1; // Increase by One for new Pickup

                    pickup.PickupNumber = pUcount;

                    // Get the Team name if the value was not given
                    //
                    if(String.IsNullOrEmpty(pickup.Team))
                    {
                        // Get the Team Name
                        string teamName = (from t in db2.AspNetUsers
                                        where (t.FirstName.ToLower().Trim() + " " + t.LastName.ToLower().Trim() == pickup.Rep.ToLower().Trim())
                                       select t.TeamName).FirstOrDefault(); // Try to Find the Team for the new Pickup

                        // Assign the Team if the Team is found
                        //
                        if(!String.IsNullOrEmpty(teamName))
                        pickup.Team = teamName.ToString();
                    }

                    //
                    db2.Entry(pickup).State = EntityState.Added;
                    db2.SaveChanges();

                    string NewPickup = pickup.PickupNumber.ToString();  // Get Pickup Number


                    // Let the others know
                    //
                    var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<Hubs.PickupHub>();
                    hub.Clients.All.newDataUpdate(fullName, NewPickup);


                    return Json(NewPickup);

                }

                #endregion

            }
            return View();
        }
        // [ValidateAntiForgeryToken]
        public JsonResult GetPickups(string requestType)
        {

            #region Setup the View for the user credentials
            //
            try
            {
                // Setup user for the View 
                string currUser = setupViewForUser();
            }
            catch (Exception e)
            {
                //Return the exception message as JSON
                return Json(new { error = e.Message });
            }
            #endregion

            // Setup all the variables needed - user is extracted from the current logged in user
            //
            var user = (from u in db.Users
                        where u.UserName != null && u.UserName == User.Identity.Name
                        select u).First();

            string userTeam = user.TeamName.ToLower();
            string userRole = user.RoleName;
            string accessLevel = "Team";
            var allPickups = (from p in db2.Pickups
                              where p.Created != null && !p.Status.ToLower().Contains("deleted") && p.Status.ToLower().Contains("completed")
                              select p).Take(1);


            if (requestType == "standard")
            {
                #region Determine the users role to choose one or all teams

                // Determine if user can see more than his Team
                //
                if (userRole == "Warehouse Admin" || userRole == "Courier Admin" || userRole == "Warehouse" || userRole == "Courier")
                {
                    // Show all the pickups
                    //
                    accessLevel = "All Teams";
                }

                #endregion

                #region Get the Pickups for the determined role

                switch (accessLevel)
                {

                    case "All Teams":

                        allPickups = (from p in db2.Pickups
                                      where p.Created != null && !p.Status.ToLower().Contains("deleted") && !p.Status.ToLower().Contains("completed") && !p.Status.ToLower().Contains("closed") && p.Company == "ZFM"
                                      orderby p.Created descending
                                      select p);
                        break;


                    case "Team":

                        allPickups = (from p in db2.Pickups
                                      where p.Created != null && !p.Status.ToLower().Contains("deleted") && !p.Status.ToLower().Contains("completed") && !p.Status.ToLower().Contains("closed") && p.Team.ToLower() == userTeam
                                      orderby p.Created descending
                                      select p);

                        break;

                }
                #endregion
            }
            else if (requestType == "completed")
            {

                #region Determine the users role to choose one or all teams

                // Determine if user can see more than his Team
                //
                if (userRole == "Warehouse Admin" || userRole == "Courier Admin" || userRole == "Warehouse" || userRole == "Courier")
                {
                    // Show all the pickups
                    //
                    accessLevel = "All Teams";
                }

                #endregion

                #region Update All Pickups  to use the the right template 
                //
                using (var ctx = new ZtrakEntities())
                {
                    var displayModeList = (from p in ctx.Pickups
                                           where p.Created != null && !p.Status.ToLower().Contains("deleted") && p.Status.ToLower().Contains("completed") || p.Status.ToLower().Contains("closed") && p.Company == "ZFM"
                                           select p);

                    if (displayModeList.Count() >= 1)
                    {
                        // Update Mode to 'done' template
                        //
                        foreach (var item in displayModeList)
                        {
                            item.Mode = "done";
                        }

                        ctx.SaveChanges();
                    }
                }
                        
                #endregion


                #region Return all the Completed Pickups
                //
                switch (accessLevel)
                {


                    case "All Teams":

                        allPickups = (from p in db2.Pickups
                                      where p.Created != null && !p.Status.ToLower().Contains("deleted") && p.Status.ToLower().Contains("completed") || p.Status.ToLower().Contains("closed") && p.Company == "ZFM"
                                      orderby p.Created descending
                                      select p);
                        break;


                    case "Team":

                        allPickups = (from p in db2.Pickups
                                      where p.Created != null && !p.Status.ToLower().Contains("deleted") && p.Status.ToLower().Contains("completed") || p.Status.ToLower().Contains("completed") && p.Team.ToLower() == userTeam && p.Company == "ZFM"
                                      orderby p.Created descending
                                      select p);

                        break;

                }
                #endregion


            }


            #region Send the results back
            //
            // Log
            Debug.Write(Environment.NewLine + "JSON Request for all Pickups granted");
            Debug.Write(Environment.NewLine + "Number of Pickups sent: " + allPickups.Count().ToString());


            // instantiating JsonNetResult
            var result = new JsonNetResult
            {
                Data = allPickups.ToList(),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };


            return result;
            //
            #endregion

        }
        public JsonResult RemovePickup(string pickupID)
        {
            string result = "";

            if (String.IsNullOrEmpty(pickupID))
            {
                result = "failure";

                return Json(result, JsonRequestBehavior.AllowGet);

            }
            else
            {

                // Convert string to integer
                //
                int pickID = Convert.ToInt16(pickupID);

                // Locate the Pick and Remove It
                //
                using (var ctx = new ZtrakEntities())
                {

                    var Pickup2Remove = (from p in ctx.Pickups
                                         where p.PickupNumber  == pickID
                                         select p);

                    // Mark Pickup deleted
                    //
                    foreach (var pickup in Pickup2Remove)
                    {
                        // First the pickup
                        pickup.Status = "Deleted";

                        // then all the pictures if any
                        foreach (var item in pickup.Items)
                        {
                            // Get file and erase
                            if (!String.IsNullOrEmpty(item.Picture1))
                            {
                                // Get file name
                                var file = Path.GetFileName(item.Picture1);
                                // Create Path

                                var path = Path.Combine(Server.MapPath("/Content/Photos/"), file);

                                // Erase File
                                FileInfo fi1 = new FileInfo(path);

                                if (fi1.Exists)     // check  if its there and delete
                                    fi1.Delete();

                            }
                        }

                    }




                    if (Pickup2Remove.Count() >= 1)
                    {
                        ctx.SaveChanges();

                        result = "success";
                    }
                }

            }


            // Get Pickup Number
            //
            string removedPickup = pickupID;

            string currentUserId = User.Identity.GetUserId();
            ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
            // Get user's full name to notify others
            //
            string fullName = currentUser.FirstName + " " + currentUser.LastName;


            // Send Message To All Users To Update Pickups
            //
            var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<Hubs.PickupHub>();
            hub.Clients.All.pickupRemoved(fullName, removedPickup);

            // Send this to the Jquery control
            return Json(result, JsonRequestBehavior.AllowGet);

        }
        public JsonResult SaveLocation(string locInfo)
        {

            // Break apart the address
            //
            string[] loc;
            string status="";

            // Extract The fields
            loc = locInfo.Split(',');

            // Check if a duplicate exists
            //
            // Limit return to the first five matches
            string locName = loc[0];
            string locOverwrite = loc[7].Trim();
            var result = db2.Locations
                           .Where(r => r.Name.ToLower() == locName.ToLower() && r.Company == "ZFM")
                           .Select(r => new { label = r.Name }).Distinct();

            // Deyect duplicates
            //
            if (result.Count() >= 1)
            {
                // Duplicate Detected
                status = "duplicate";
            }
            
            if (locOverwrite == "yes" && result.Count() >= 1)
            {
                try
                {
                    // delete existing
                    //
                    using (var ctx = new ZtrakEntities())
                    {

                        var listToRemove = (from i in ctx.Locations
                                        where i.Name.ToLower() == locName.ToLower()  && i.Company == "ZFM"
                                        select i);


                        if (listToRemove.Count() >= 1)
                        {
                            ctx.Locations.RemoveRange(listToRemove);
                            ctx.SaveChanges();
                        }
                    }

                    //Save the Location
                    //
                    Location newLocation = new Location
                    {
                        Name = loc[0].ToLower(),
                        Address = loc[1],
                        City = loc[2],
                        State = loc[3],
                        Zip = loc[4],
                        Latitude = Convert.ToDouble(loc[5]),
                        Longitude = Convert.ToDouble(loc[6]),
                        Company = "ZFM"

                    };

                    // Save it 
                    db2.Locations.Add(newLocation);
                    db2.SaveChanges();
                    status = "saved!";

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    // Provide for exceptions.
                }
            }
            
            if (locOverwrite == "no" && result.Count() == 0)
            {
                try
                {
                    //Save the Location
                    //
                    Location newLocation = new Location
                    {
                        Name = loc[0].ToLower(),
                        Address = loc[1],
                        City = loc[2],
                        State = loc[3],
                        Zip = loc[4],
                        Latitude = Convert.ToDouble(loc[5]),
                        Longitude = Convert.ToDouble(loc[6]),
                        Company = "ZFM"

                    };

                    // Save it 
                    db2.Locations.Add(newLocation);
                    db2.SaveChanges();
                    status = "saved!";

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    // Provide for exceptions.
                }
            }
        
            //
            return Json(new { answer = status }, JsonRequestBehavior.AllowGet);

        }
        public ActionResult Files(IEnumerable<HttpPostedFileBase> files, string PickupNumber)
        {


            #region Get User Info and prepare database update
            //
            var user = (from u in db.Users
                        where u.UserName != null && u.UserName == User.Identity.Name
                        select u).First();


            #endregion

            #region  Process Files
            //

            string[] ImageList = new string[files.Count()]; // keep trak of image names

            var fileList = files.ToList();

            for (int i = 0; i < fileList.Count(); i++)
            {

                #region Compress Each Photo

                // Create File List
                //
                var file = fileList[i];

                // skip empty ones              
                if (file == null || file.ContentLength == 0)
                {

                    // Enter a spacer to keep the item reference from beeing lost
                    //
                    ImageList[i] = "empty";

                    /// now move on
                    continue;
                }

                // Create the file name with the extention
                //
                var fileName = DateTime.Now.Millisecond.ToString() + randomName(4) + Path.GetExtension(file.FileName);
                System.Threading.Thread.Sleep(10);

                /// Create Path
                var path = Path.Combine(Server.MapPath("/Content/Photos/"), fileName);

                // Store the file name to uptade items database
                ImageList[i] = fileName;

                // Create Compressedn Image 
                //
                Bitmap img = new Bitmap(file.InputStream);
                imgcompression(img, path, fileName);


                #endregion

            }
            #endregion Files Processed

            #region  Log to database
            
            // Pickup to ID
            int pickup2Match = Convert.ToInt16(PickupNumber);
            int pickupID = (from p in db2.Pickups
                            where p.PickupNumber == pickup2Match
                            select p.ID).FirstOrDefault();

            // Erase current Items
            //
            using (var ctx = new ZtrakEntities())
            {

                var listToRemove = (from i in ctx.Items
                                    where i.PickupReff == pickup2Match
                                    select i);

                // Delete All Existing Graphics Pictures
                //
                foreach (var item in listToRemove)
                {

                    // Delete existing image first and then replace
                    //
                    if (!String.IsNullOrEmpty(item.Picture1))
                    {
                        // erase existing picture from disk
                        //
                        string file = Path.GetFileName(item.Picture1);

                        var path = Path.Combine(Server.MapPath("/Content/Photos/"), file);

                        // Erase File
                        FileInfo fi1 = new FileInfo(path);

                        if (fi1.Exists)     // check  if file exists and delete
                            fi1.Delete();

                    }
                }

                // Delete All Entries
                if (listToRemove.Count() >= 1)
                {
                    ctx.Items.RemoveRange(listToRemove);
                    ctx.SaveChanges();
                }
            }


            // Add all the Items Received
            //
            for (int i = 0; i < ImageList.Length; i++)
			{
                string fileName= ImageList[i];
                if (fileName == "empty")
                    continue;

               
			    Item newPhotoUpload = new Item
                {
                    PickupReff = pickup2Match,
                    PickupID = pickupID,
                     Company = "ZFM",
                     Qty = 1,
                     AddedBy = user.FirstName + " " + user.LastName,
                     AddedDate = pstNow(),
                     Description = "Photo Upload",
                     Picture1 = "http://ztrak.azurewebsites.net/Content/Photos/" + fileName
                };
                
                // Save it 
                db2.Items.Add(newPhotoUpload);

                // Log it
                //
                GraphicsLog graphicLogEntry = new GraphicsLog
                {

                    User = user.FirstName + " " + user.LastName,
                    Date = pstNow(),
                    DeviceIP = Request.UserHostAddress,
                    Team = user.TeamName,
                    Picture = "http://ztrak.azurewebsites.net/Content/Photos/" + fileName,
                    Size = fileList[i].ContentLength,
                    Pickup = PickupNumber,
                    Item = "Photo Upload"
                };

                // Save it 
                db2.GraphicsLogs.Add(graphicLogEntry);

			}

            try
            {
                db2.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                // Provide for exceptions.
            }

         
            #endregion Database Update

            // Alert the users that an Update has taken place
            //
            string fullName = user.FirstName + " " + user.LastName;

            var hub = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<ZTRAK.Hubs.PickupHub>();
            hub.Clients.All.newDataUpdate(fullName, PickupNumber);


            return Json(PickupNumber);
            // return Json(files.Select(x => new { name = x.FileName }));
            //return RedirectToAction("/", new { pID = pickupID });

        }