protected void Page_Load(object sender, EventArgs e)
        {
            // Grab username and userID from AspNet Authentication
            String userName = Convert.ToString(User.Identity.GetUserName());
            String userID = Convert.ToString(User.Identity.GetUserId());
            lblUsername.Text = userName;
            UserProfile userP = new UserProfile();
            using (fit_trackEntities db = new fit_trackEntities())
            {
                userP = (from up in db.UserProfiles
                         join u in db.AspNetUsers on up.UserID equals u.Id
                         where up.UserID == userID
                         select up).FirstOrDefault();

                // If user already has a profile, print the details to the screen
                if (userP != null)
                {
                    lblFirstName.Text = userP.FirstName;
                    lblLastName.Text = userP.LastName;
                    lblEmail.Text = userP.Email;
                    lblUserHeight.Text = Convert.ToString(userP.UserHeight);
                    lblUserWeight.Text = Convert.ToString(userP.UserWeight);
                    lblAge.Text = Convert.ToString(userP.Age);
                }
                // If the user doesn't have a profile yet (New User), add a new entry to the UserProfile table with their UserID
                else
                {
                    userP = new UserProfile();
                    userP.UserID = userID;
                    db.UserProfiles.Add(userP);
                    db.SaveChanges();
                }

            }
        }
        protected void GetProfile()
        {
            // Populate form with existing UserProfile record
            String UserID = Convert.ToString(User.Identity.GetUserId());

            try
            {
                using (fit_trackEntities db = new fit_trackEntities())
                {
                    UserProfile up = (from objS in db.UserProfiles
                                      where objS.UserID == UserID
                                      select objS).FirstOrDefault();

                    txtFirstName.Text = up.FirstName;
                    txtLastName.Text = up.LastName;
                    txtEmail.Text = up.Email;
                    txtHeight.Text = Convert.ToString(up.UserHeight);
                    txtWeight.Text = Convert.ToString(up.UserWeight);
                    txtAge.Text = Convert.ToString(up.Age);

                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            // Use EF to connect to SQL Server
            using (fit_trackEntities db = new fit_trackEntities())
            {
                // Use the UserProfile Model to save the new record
                UserProfile up = new UserProfile();
                String UserID = Convert.ToString(User.Identity.GetUserId());

                // Get the current UserProfile from the Enity Framework
                up = (from objS in db.UserProfiles
                      where objS.UserID == UserID
                      select objS).FirstOrDefault();

                up.FirstName = txtFirstName.Text;
                up.LastName = txtLastName.Text;
                up.Email = txtEmail.Text;
                up.UserHeight = Convert.ToDecimal(txtHeight.Text);
                up.UserWeight = Convert.ToDecimal(txtWeight.Text);
                up.Age = Convert.ToInt32(txtAge.Text);

                db.SaveChanges();

                // Redirect to the updated Profile page
                Response.Redirect("profile.aspx");
            }
        }
        protected void GetActLog()
        {
            try
            {

                // Connect to EF
                using (fit_trackEntities db = new fit_trackEntities())
                {
                    String userID = Convert.ToString(User.Identity.GetUserId());
                    String sortString = Session["SortColumn"].ToString() + " " + Session["SortDirection"].ToString();
                    // Query the ActivityLog table, using the Enity Framework
                    var ActLog = from al in db.ActivityLogs
                                 join u in db.AspNetUsers on al.UserID equals u.Id
                                 where al.UserID == userID
                                 select new { al.ActLogID, al.ActName, al.ActType, al.ActDuration, al.ActDistance, al.ActWeight, al.ActReps, al.ActDate };

                    grdActLog.DataSource = ActLog.AsQueryable().OrderBy(sortString).ToList();
                    grdActLog.DataBind();
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void btnExercise_Click(object sender, EventArgs e)
        {
            try
            {
                using (fit_trackEntities db = new fit_trackEntities())
                {
                    ActivityLog d = new ActivityLog();
                    Int32 ActLogID = 0;

                    // Grab the userID from the Authentication table
                    String userID = Convert.ToString(User.Identity.GetUserId());

                    // If an Activity Log already exists (Edit), load the values for that ActLogID from the ActLog table
                    if (Request.QueryString["ActLogID"] != null)
                    {
                        // Get the ID from the URL
                        ActLogID = Convert.ToInt32(Request.QueryString["ActLogID"]);

                        // Get the current ActLog from the Enity Framework
                        d = (from objS in db.ActivityLogs
                             where objS.ActLogID == ActLogID
                             select objS).FirstOrDefault();

                    }

                    d.UserID = userID;
                    d.ActName = txtName.Text;
                    d.ActType = ddlExercise.SelectedValue;

                    if (ddlExercise.SelectedValue == "Cardio")
                    {
                        d.ActDistance = Convert.ToDecimal(txtDistance.Text);
                        d.ActDuration = Convert.ToDecimal(txtDuration.Text);
                        d.ActDate = DateTime.Now;

                    }
                    else if (ddlExercise.SelectedValue == "Weight Lifting")
                    {
                        d.ActReps = Convert.ToInt32(txtReps.Text);
                        d.ActWeight = Convert.ToInt32(txtWeight.Text);
                        d.ActDate = DateTime.Now;
                    }

                    // If there is no ActLog, add a new one to the DB now
                    if (ActLogID == 0)
                    {
                        db.ActivityLogs.Add(d);
                    }
                    db.SaveChanges();
                    Response.Redirect("/admin/main-menu.aspx", false);
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void btnAddFood_Click(object sender, EventArgs e)
        {
            try
            {
                using (fit_trackEntities db = new fit_trackEntities())
                {
                    FoodLog d = new FoodLog();
                    Int32 FoodLogID = 0;

                    String userID = Convert.ToString(User.Identity.GetUserId());

                    if (Request.QueryString["FoodLogID"] != null)
                    {
                        // Get the ID from the URL
                        FoodLogID = Convert.ToInt32(Request.QueryString["FoodLogID"]);

                        // Get the current FoodLog from the Enity Framework
                        d = (from objS in db.FoodLogs
                             where objS.FoodLogID == FoodLogID
                             select objS).FirstOrDefault();

                    }

                    d.UserID = userID;
                    d.Meal = ddlMeals.SelectedValue;
                    d.FoodName = txtFoodName.Text;
                    d.Calories = Convert.ToInt32(txtCalories.Text);
                    d.Carbs = Convert.ToInt32(txtCarbs.Text);
                    d.MealServingSize = Convert.ToInt32(txtServings.Text);
                    d.FoodGroup = ddlFoodGroup.SelectedValue;
                    d.Protein = Convert.ToInt32(txtProtein.Text);
                    d.TotalFat = Convert.ToInt32(txtFat.Text);
                    d.Sodium = Convert.ToInt32(txtSodium.Text);
                    d.FoodDate = DateTime.Now;

                    // If this is a new log, add log to FoodLog table
                    if (FoodLogID == 0)
                    {
                        db.FoodLogs.Add(d);
                    }
                    db.SaveChanges();
                    Response.Redirect("/admin/main-menu.aspx", false);
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void GetFoodLog()
        {
            try
            {

                // Connect to EF
                using (fit_trackEntities db = new fit_trackEntities())
                {
                    String userID = Convert.ToString(User.Identity.GetUserId());
                    String sortString = Session["SortColumn"].ToString() + " " + Session["SortDirection"].ToString();
                    // Query the FoodLog table, using the Enity Framework
                    var FoodLog = (from fl in db.FoodLogs
                                   join u in db.AspNetUsers on fl.UserID equals u.Id
                                   where fl.UserID == userID
                                   select new
                                   {
                                       fl.FoodLogID,
                                       fl.FoodName,
                                       fl.Meal,
                                       fl.Calories,
                                       fl.FoodGroup,
                                       fl.MealServingSize,
                                       fl.Carbs,
                                       fl.TotalFat,
                                       fl.Protein,
                                       fl.Sodium,
                                       fl.FoodDate
                                   });

                    grdFoodLog.DataSource = FoodLog.AsQueryable().OrderBy(sortString).ToList();
                    grdFoodLog.DataBind();
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void GetFoodLog()
        {
            // Populate form with existing Food Log record, if it exists
            Int32 FoodID = Convert.ToInt32(Request.QueryString["FoodLogID"]);

            try
            {
                using (fit_trackEntities db = new fit_trackEntities())
                {
                    FoodLog fl = (from objS in db.FoodLogs
                                      where objS.FoodLogID == FoodID
                                      select objS).FirstOrDefault();

                    // If there is already a food log for this meal
                    if (fl != null)
                    {
                        txtFoodName.Text = fl.FoodName;
                        txtCalories.Text = Convert.ToString(fl.Calories);
                        ddlFoodGroup.SelectedValue = fl.FoodGroup;
                        txtServings.Text = Convert.ToString(fl.MealServingSize);
                        txtCarbs.Text = Convert.ToString(fl.Carbs);
                        txtSodium.Text = Convert.ToString(fl.Sodium);
                        txtFat.Text = Convert.ToString(fl.TotalFat);
                        txtProtein.Text = Convert.ToString(fl.Protein);
                        ddlMeals.SelectedValue = fl.Meal;
                        if (ddlMeals.SelectedValue == "breakfast")
                        {
                            pnlBreakfast.Visible = true;
                            pnlDinner.Visible = false;
                            pnlLunch.Visible = false;
                            pnlSnack.Visible = false;
                            pnlFoodForm.Visible = true;

                        }
                        else if (ddlMeals.SelectedValue == "lunch")
                        {
                            pnlBreakfast.Visible = false;
                            pnlDinner.Visible = false;
                            pnlLunch.Visible = true;
                            pnlSnack.Visible = false;
                            pnlFoodForm.Visible = true;

                        }
                        else if (ddlMeals.SelectedValue == "dinner")
                        {
                            pnlBreakfast.Visible = false;
                            pnlDinner.Visible = true;
                            pnlLunch.Visible = false;
                            pnlSnack.Visible = false;
                            pnlFoodForm.Visible = true;
                        }
                        else if (ddlMeals.SelectedValue == "snack")
                        {
                            pnlBreakfast.Visible = false;
                            pnlDinner.Visible = false;
                            pnlLunch.Visible = false;
                            pnlSnack.Visible = true;
                            pnlFoodForm.Visible = true;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void GetAct()
        {
            // Populate form with existing ActLog record
            Int32 ActID = Convert.ToInt32(Request.QueryString["ActLogID"]);

            try
            {
                using (fit_trackEntities db = new fit_trackEntities())
                {
                    ActivityLog al = (from objS in db.ActivityLogs
                                      where objS.ActLogID == ActID
                                      select objS).FirstOrDefault();

                    // If there is an existing Activity Log, populate the form with the valus from the DB
                    if (al != null)
                    {
                        txtName.Text = al.ActName;
                        txtDuration.Text = Convert.ToString(al.ActDuration);
                        txtDistance.Text = Convert.ToString(al.ActDistance);
                        txtReps.Text = Convert.ToString(al.ActReps);
                        txtWeight.Text = Convert.ToString(al.ActWeight);
                        ddlExercise.SelectedValue = al.ActType;
                        // If the type of exercise is Cardio, show cardio fields
                        if (ddlExercise.SelectedValue == "Cardio")
                        {
                            pnlCardio.Visible = true;
                            pnlMuscles.Visible = false;
                            pnlName.Visible = true;
                            pnlButton.Visible = true;
                        }
                        // If the type of exercise is weight lifting, show weight lifting fields
                        else if (ddlExercise.SelectedValue == "Weight Lifting")
                        {
                            pnlCardio.Visible = false;
                            pnlMuscles.Visible = true;
                            pnlName.Visible = true;
                            pnlButton.Visible = true;

                        }
                    }

                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/error.aspx");
            }
        }
        protected void grdFoodLog_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // Store which row was clicked
            Int32 selectedRow = e.RowIndex;

            // Get the selected FoodLogID using the grid's Data Key collection
            Int32 FoodID = Convert.ToInt32(grdFoodLog.DataKeys[selectedRow].Values["FoodLogID"]);

            try
            {
                // Use Entity Framework to remove the selected Food Log from the DB
                using (fit_trackEntities db = new fit_trackEntities())
                {
                    FoodLog fl = (from objF in db.FoodLogs
                                  where objF.FoodLogID == FoodID
                                  select objF).FirstOrDefault(); // Using First would get an error if no data comes back, FirstOrDefault won't throw an error

                    // Do the delete
                    db.FoodLogs.Remove(fl);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Response.Redirect("/error.aspx");
            }

            // Refresh the grid
            GetFoodLog();
        }