public ActionResult AddEditForm(oCollectionForm colForm, FormCollection formData, int? id, string frmAction)
 {
     int cft_id = id ?? -1;
     if (!String.IsNullOrEmpty(frmAction) && (frmAction == "EDIT" || frmAction== "NEW VERSION"))//this means we're came here from Manage form and user needs to unpublish this form
     {
         //frmAction = "EDIT" or "NEW VERSION"
         if (frmAction == "EDIT")//if edit, we need to unpublish
         {
             Session["frmAction"] = "MANAGE-EDIT";
         }
         else if(frmAction == "NEW VERSION")
         {
             Session["frmAction"] = "MANAGE-NEW-VERSION";
         }               
         return RedirectToAction("AddEditForm", new { id = cft_id });
     }
    
     string data_from_form = String.IsNullOrEmpty(formData["formQuestions"]) ? String.Empty : formData["formQuestions"];         
     string is_published = formData["isPublished"];
     if (frmAction == "MANAGE-NEW-VERSION")
     {
         int new_cft_id = versionForm(colForm, data_from_form, is_published, cft_id);
         return RedirectToAction("AddEditForm", new { id = new_cft_id });
     }
     if (cft_id > 0 && db.OBS_COLLECT_FORM_TMPLT.Where(x => x.obs_cft_id == cft_id && x.obs_cft_pub_dtm!=null).Count()>0) 
     {
         return RedirectToAction("AddEditForm", new { id = cft_id });
     }
     cft_id = saveForm(colForm, data_from_form, is_published, cft_id);
     Session["saveMessage"] = "Form Data was saved Successfully";
     if (is_published == "true")
     {
         return RedirectToAction("AddEditForm", new { id = cft_id });
     }
     else { return RedirectToAction("AddEditForm", new { id = cft_id }); 
     }
     
     //return RedirectToAction("Index");
 }
        public ActionResult AddEditForm(int? id, int? copyFrom)
        {
            int cftid = id ?? 0;
            int copyFromID = copyFrom ?? -1;
            oCollectionForm selectedColForm;
            
            // Try creating an instance of the form
            try {
                selectedColForm = new oCollectionForm(cftid);
            }
            catch (Exception ex)
            {
                selectedColForm = new oCollectionForm(0);
                ViewBag.errorMessage = "ERROR Found: " + ex.Message;
            }
            if (copyFromID>0)
            {
                try
                {
                    selectedColForm = new oCollectionForm(copyFromID);
                }
                catch (Exception ex)
                {
                    selectedColForm = new oCollectionForm(0);
                    ViewBag.errorMessage = "ERROR Found: " + ex.Message;
                }
                selectedColForm.cft_id = 0;
                selectedColForm.cft_Title=String.Empty;
                selectedColForm.cft_SubTitle = String.Empty;
                selectedColForm.cft_Nbr = 0;
                selectedColForm.cft_Version = 0;
                selectedColForm.previous_vers_cft_id = 0;
                selectedColForm.cft_new_vers_cft_id = 0;
                selectedColForm.manageAction = String.Empty;
                selectedColForm.screen_Title = "CREATE NEW FORM";
            }
            else if (cftid > 0)
            {                
                string frmAction = String.Empty;
                try
                {
                    frmAction = Session["frmAction"].ToString();
                    Session["frmAction"] = null;
                }
                catch { }
                if (!String.IsNullOrEmpty(frmAction))
                {
                    if (frmAction == "MANAGE-EDIT")
                    {
                        try
                        {
                            OBS_COLLECT_FORM_TMPLT form_to_unpublish = db.OBS_COLLECT_FORM_TMPLT.Find(cftid);
                            selectedColForm.originalPublishDate = form_to_unpublish.obs_cft_pub_dtm;
                            selectedColForm.originalyPublishedBy = form_to_unpublish.obs_cft_pub_by_uid;
                            selectedColForm.cft_isPublished = "NOT PUBLISHED";
                            selectedColForm.manageAction = frmAction;
                            form_to_unpublish.obs_cft_pub_by_uid = null;
                            form_to_unpublish.obs_cft_pub_dtm = null;
                            db.SaveChanges();
                        }
                        catch { }
                    }
                    else if (frmAction == "MANAGE-NEW-VERSION")
                    {
                        selectedColForm.manageAction = frmAction;
                        selectedColForm.cft_isPublished = "NOT PUBLISHED";
                        selectedColForm.previous_vers_cft_id = selectedColForm.cft_id;
                        selectedColForm.cft_id = 0;
                        selectedColForm.cft_Version++;                       
                    }

                }

                //Validate that the start Date is equal or greater than today. Otherwise, reset it to be today.
                selectedColForm.cft_eff_st_dt = selectedColForm.cft_eff_st_dt.HasValue ? selectedColForm.cft_eff_st_dt : DateTime.Now;
                if (selectedColForm.cft_eff_st_dt < DateTime.Now && (frmAction == "MANAGE-NEW-VERSION" || frmAction == "MANAGE-EDIT"))
                { selectedColForm.cft_eff_st_dt = DateTime.Now; }

                selectedColForm.str_cft_eff_st_dt = selectedColForm.cft_eff_st_dt.HasValue ? selectedColForm.cft_eff_st_dt.Value.ToString("MMM dd, yyyy") : String.Empty;
                selectedColForm.str_cft_eff_end_dt = selectedColForm.cft_eff_end_dt < Convert.ToDateTime("12/31/2060") ? selectedColForm.cft_eff_end_dt.ToString("MMM dd, yyyy") : String.Empty;
            }//end of "else if (cftid > 0)"
            else
            {
                selectedColForm.cft_eff_st_dt = DateTime.Now;
                selectedColForm.cft_eff_end_dt = Convert.ToDateTime("12/31/2060");
                selectedColForm.str_cft_eff_st_dt = String.Empty;
                selectedColForm.str_cft_eff_end_dt = String.Empty;
            }
            string selected_lc = "0";
            try { selected_lc = db.DSC_LC.Single(x => x.dsc_lc_name == selectedColForm.cft_LC).dsc_lc_id.ToString(); } catch { }
            string selected_cust = "0";
            try { selected_cust = db.DSC_CUSTOMER.Single(x => x.dsc_cust_name == selectedColForm.cft_Cust).dsc_cust_id.ToString(); } catch { }
            try
            {
                string selected_obs_type = db.OBS_TYPE.Single(x => x.obs_type_name==selectedColForm.cft_obsType).obs_type_id.ToString();
                ViewBag.cft_obsType = new SelectList(db.OBS_TYPE.Where(x => x.obs_type_id >= 0), "obs_type_id", "obs_type_name", selected_obs_type);
            }
            catch
            {
                ViewBag.cft_obsType = new SelectList(db.OBS_TYPE.Where(x => x.obs_type_id >= 0), "obs_type_id", "obs_type_name");
            }

            ViewBag.cft_Cust = new SelectList(db.DSC_CUSTOMER.Where(x => x.dsc_cust_id >= 0), "dsc_cust_id", "dsc_cust_name", selected_cust);
            ViewBag.cft_LC = new SelectList(db.DSC_LC.Where(x => x.dsc_lc_id >= 0).OrderBy(y=>y.dsc_lc_name), "dsc_lc_id", "dsc_lc_name", selected_lc);

            if (selectedColForm.manageAction.Equals("EDIT")|| selectedColForm.manageAction.Equals("NEW VERSION")|| selectedColForm.manageAction.Equals("RESTRICTED")|| selectedColForm.manageAction.Equals("VIEW-ONLY"))
            { // Is published and it has instances
                return View("ManageForm", selectedColForm);
            }
            else {
                return View(selectedColForm);
            }
        }
        private int versionForm(oCollectionForm colForm, string form_questions_from_gui, string isPublished, int id)
        {
            int cft_id = 0;
            colForm.previous_vers_cft_id=id;//represents previous version cft_id

            ViewBag.exception = "";
            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {                    

                        //first we need to save OBS_COLLECT_FORM_TMPLT table data
                        OBS_COLLECT_FORM_TMPLT template_to_save = new OBS_COLLECT_FORM_TMPLT();
                        OBS_COLLECT_FORM_TMPLT prev_form = db.OBS_COLLECT_FORM_TMPLT.Find(colForm.previous_vers_cft_id);
                        template_to_save.dsc_cust_id = prev_form.dsc_cust_id;
                        template_to_save.obs_type_id = prev_form.obs_type_id;
                        template_to_save.dsc_lc_id = prev_form.dsc_lc_id;                 
                        template_to_save.obs_cft_nbr = (short)colForm.cft_Nbr;
                        template_to_save.obs_cft_ver = (short)colForm.cft_Version;
                        template_to_save.obs_cft_title = prev_form.obs_cft_title;
                        template_to_save.obs_cft_subtitle = colForm.cft_SubTitle;
                        template_to_save.obs_cft_eff_end_dt = (colForm.cft_eff_end_dt == null) || (colForm.cft_eff_end_dt < Convert.ToDateTime("01/01/2000")) ? Convert.ToDateTime("12/31/2060") : colForm.cft_eff_end_dt;
                        template_to_save.obs_cft_added_dtm = DateTime.Now;
                        template_to_save.obs_cft_added_uid = User.Identity.Name;
                        template_to_save.obs_cft_last_saved_dtm = DateTime.Now;
                        template_to_save.obs_cft_upd_dtm = DateTime.Now;
                        template_to_save.obs_cft_upd_uid = User.Identity.Name;
                        if (isPublished == "true")
                        {                            
                            //if (colForm.cft_eff_st_dt != null && (colForm.cft_eff_st_dt < Convert.ToDateTime("01/01/2000")))
                            if (colForm.cft_eff_st_dt != null)
                            {                                
                                
                                template_to_save.obs_cft_eff_st_dt = colForm.cft_eff_st_dt;
                                if(prev_form.obs_cft_eff_end_dt > colForm.cft_eff_st_dt)
                                { 
                                   if (prev_form.obs_cft_eff_st_dt == (DateTime)colForm.cft_eff_st_dt)
                                   {
                                      prev_form.obs_cft_eff_end_dt = (DateTime)colForm.cft_eff_st_dt;
                                   }
                                   else
                                   {
                                      prev_form.obs_cft_eff_end_dt = ((DateTime)colForm.cft_eff_st_dt).AddSeconds(-1);
                                   }  
                                }                                                              
                            }
                            else
                            {
                                Session.Add("errorMessage", "ERROR:Can't publish this form. Effective start date is required");
                                return -1;
                            }
                            template_to_save.obs_cft_pub_by_uid = User.Identity.Name;
                            template_to_save.obs_cft_pub_dtm = DateTime.Now;
                        }
                        else if (!(colForm.cft_eff_st_dt == null || (colForm.cft_eff_st_dt < Convert.ToDateTime("01/01/2000"))))
                        {
                            template_to_save.obs_cft_eff_st_dt = colForm.cft_eff_st_dt;
                        }
                        db.OBS_COLLECT_FORM_TMPLT.Add(template_to_save);
                        db.SaveChanges();
                        cft_id = template_to_save.obs_cft_id;

                    //now we need to save all the form questions
                    string[] splitterm = { "," };
                    string[] parsed_questions = form_questions_from_gui.Split(splitterm, StringSplitOptions.RemoveEmptyEntries);
                    short order_counter = 1;
                    foreach (string question in parsed_questions)
                    {
                        //now lets first save split the string we received from the gui
                        // string format should be: order,qat_id,section_text
                        string[] question_items = question.Split(new string[] { "~" }, StringSplitOptions.RemoveEmptyEntries);
                        short order = order_counter;
                        int qat_id = Convert.ToInt32(question_items[0]);
                        int form_section_id = getSectionID(question_items[1]);
                        OBS_COL_FORM_QUESTIONS new_form_question = new OBS_COL_FORM_QUESTIONS();
                        new_form_question.obs_cft_id = cft_id;
                        new_form_question.obs_form_section_id = form_section_id;
                        new_form_question.obs_qat_id = qat_id;
                        new_form_question.obs_col_form_quest_order = order;
                        new_form_question.obs_col_form_quest_wgt = 1;
                        new_form_question.obs_col_form_quest_na_yn = question_items[2];
                        db.OBS_COL_FORM_QUESTIONS.Add(new_form_question);
                        db.SaveChanges();
                        order_counter++;
                    }//end of foreach

                    transaction.Commit();
                    return cft_id;
                }//end of try
                catch (Exception e)
                {
                    Session.Add("errorMessage", e.Message);
                    transaction.Rollback();
                    return -1;
                }
            }//end of  using (var transaction = db.Database.BeginTransaction())

        }
        // GET: ColFormTemplate/Details/5
        public ActionResult Details(int id)
        {
            //if (id == null) { return HttpNotFound(); }

            oCollectionForm selectedColForm = new oCollectionForm(id);
            if (selectedColForm == null) { return HttpNotFound(); }

            return View(selectedColForm);
        }
        private int saveForm(oCollectionForm colForm, string form_questions_from_gui, string isPublished, int id)
        {

            int cft_id = id;
            if (cft_id <= 0 && db.OBS_COLLECT_FORM_TMPLT.Where(item => item.obs_cft_title == colForm.cft_Title).Count() > 0)
            {//we need to check if title passed from user is unique. if it already exists, we need to return the error message back to the screen
                Session.Add("errorMessage", "ERROR: The Question Id is either invalid or the Form Title Already Exist.");
                return -1;
            }

            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {
                    if (cft_id > 0)//this means we are editing an existing form
                    {
                        OBS_COLLECT_FORM_TMPLT template_to_edit = db.OBS_COLLECT_FORM_TMPLT.Find(cft_id);
                        if (colForm.cft_Version == 1)
                        {
                            template_to_edit.dsc_cust_id = Convert.ToInt32(colForm.cft_Cust);
                            template_to_edit.obs_type_id = Convert.ToInt32(colForm.cft_obsType);
                            template_to_edit.dsc_lc_id = Convert.ToInt32(colForm.cft_LC);
                            template_to_edit.obs_cft_title = colForm.cft_Title;
                            
                        }
                        template_to_edit.obs_cft_eff_end_dt = (colForm.cft_eff_end_dt == null) || (colForm.cft_eff_end_dt < Convert.ToDateTime("01/01/2000")) ? Convert.ToDateTime("12/31/2060") : colForm.cft_eff_end_dt;
                        template_to_edit.obs_cft_last_saved_dtm = DateTime.Now;
                        template_to_edit.obs_cft_upd_dtm = DateTime.Now;
                        template_to_edit.obs_cft_upd_uid = User.Identity.Name;
                        template_to_edit.obs_cft_subtitle = colForm.cft_SubTitle;
                        if (isPublished == "true")
                        {
                            //if (colForm.cft_eff_st_dt != null && (colForm.cft_eff_st_dt < Convert.ToDateTime("01/01/2000")))
                            if (colForm.cft_eff_st_dt != null)
                            {
                                template_to_edit.obs_cft_eff_st_dt = colForm.cft_eff_st_dt;
                                if (colForm.previous_vers_cft_id > 0)
                                {
                                    OBS_COLLECT_FORM_TMPLT prev_form = db.OBS_COLLECT_FORM_TMPLT.Find(colForm.previous_vers_cft_id);
                                    if (prev_form.obs_cft_eff_end_dt > colForm.cft_eff_st_dt)
                                    {
                                        if (prev_form.obs_cft_eff_st_dt == (DateTime)colForm.cft_eff_st_dt)
                                        {
                                            prev_form.obs_cft_eff_end_dt = (DateTime)colForm.cft_eff_st_dt;
                                        }
                                        else
                                        {
                                            prev_form.obs_cft_eff_end_dt = ((DateTime)colForm.cft_eff_st_dt).AddSeconds(-1);
                                        }                                        
                                    }
                                }// end ofif (colForm.previous_vers_cft_id > 0)
                            }
                            else
                            {
                                Session.Add("errorMessage", "ERROR:Can't publish this form. Effective start date is required");
                                return -1;
                            }
                            template_to_edit.obs_cft_pub_by_uid = User.Identity.Name;
                            template_to_edit.obs_cft_pub_dtm = DateTime.Now;
                        }
                        else if (!(colForm.cft_eff_st_dt == null || (colForm.cft_eff_st_dt < Convert.ToDateTime("01/01/2000"))))
                        {
                            template_to_edit.obs_cft_eff_st_dt = colForm.cft_eff_st_dt;
                        }
                        else
                        {
                            template_to_edit.obs_cft_eff_st_dt = null;
                        }
                        List<OBS_COL_FORM_QUESTIONS> old_form_questions = db.OBS_COL_FORM_QUESTIONS.Where(x => x.obs_cft_id == cft_id).ToList();
                        db.OBS_COL_FORM_QUESTIONS.RemoveRange(old_form_questions);
                        //foreach (OBS_COL_FORM_QUESTIONS old_form_question in old_form_questions)
                        //{
                        //    db.OBS_COL_FORM_QUESTIONS.Remove(old_form_question)
                        //}
                        db.SaveChanges();
                    }
                    else//this means we're saving new form
                    {
                        //first we need to save OBS_COLLECT_FORM_TMPLT table data
                        OBS_COLLECT_FORM_TMPLT template_to_save = new OBS_COLLECT_FORM_TMPLT();
                        template_to_save.dsc_cust_id = Convert.ToInt32(colForm.cft_Cust);
                        template_to_save.obs_type_id = Convert.ToInt32(colForm.cft_obsType);
                        template_to_save.dsc_lc_id = Convert.ToInt32(colForm.cft_LC);
                        short cft_number = 1;
                        if (db.OBS_COLLECT_FORM_TMPLT.Count() > 0)
                        {  // Verify that at least one form exists in the database
                            cft_number = (short)(db.OBS_COLLECT_FORM_TMPLT.Max(x => x.obs_cft_nbr) + 1);
                        }
                        
                        template_to_save.obs_cft_nbr = cft_number;
                        template_to_save.obs_cft_ver = 1;
                        template_to_save.obs_cft_title = colForm.cft_Title;
                        template_to_save.obs_cft_subtitle = colForm.cft_SubTitle;
                        template_to_save.obs_cft_eff_end_dt = (colForm.cft_eff_end_dt == null) || (colForm.cft_eff_end_dt < Convert.ToDateTime("01/01/2000")) ? Convert.ToDateTime("12/31/2060") : colForm.cft_eff_end_dt;
                        template_to_save.obs_cft_added_dtm = DateTime.Now;
                        template_to_save.obs_cft_added_uid = User.Identity.Name;
                        template_to_save.obs_cft_last_saved_dtm = DateTime.Now;
                        template_to_save.obs_cft_upd_dtm = DateTime.Now;
                        template_to_save.obs_cft_upd_uid = User.Identity.Name;
                        if (isPublished == "true")
                        {

                            if (colForm.cft_eff_st_dt != null && (colForm.cft_eff_st_dt > Convert.ToDateTime("01/01/2000")))
                            {
                                template_to_save.obs_cft_eff_st_dt = colForm.cft_eff_st_dt;
                            }
                            else
                            {
                                Session.Add("errorMessage", "ERROR:Can't publish this form. Effective start date is required");
                                return -1;
                            }
                            template_to_save.obs_cft_pub_by_uid = User.Identity.Name;
                            template_to_save.obs_cft_pub_dtm = DateTime.Now;
                        }
                        else if (!(colForm.cft_eff_st_dt == null || (colForm.cft_eff_st_dt < Convert.ToDateTime("01/01/2000"))))
                        {
                            template_to_save.obs_cft_eff_st_dt = colForm.cft_eff_st_dt;
                        }
                        db.OBS_COLLECT_FORM_TMPLT.Add(template_to_save);
                        db.SaveChanges();
                        cft_id = template_to_save.obs_cft_id;
                        //now we need to query OBS_COLLECT_FORM_TMPLT table to find CFT ID we just created
                        //int cft_id = db.OBS_COLLECT_FORM_TMPLT.Single(item => item.obs_cft_nbr == cft_number && item.obs_cft_ver == 1).obs_cft_id;                       
                    }//end of else(saving new form header form)

                    //now we need to save all the form questions
                    string[] splitterm = { "," };
                    string[] parsed_questions = form_questions_from_gui.Split(splitterm, StringSplitOptions.RemoveEmptyEntries);
                    short order_counter = 1;
                    foreach (string question in parsed_questions)
                    {
                        //now lets first save split the string we received from the gui
                        // string format should be: order,qat_id,section_text
                        string[] question_items = question.Split(new string[] { "~" }, StringSplitOptions.RemoveEmptyEntries);
                        short order = order_counter;
                        int qat_id = Convert.ToInt32(question_items[0]);
                        int form_section_id = getSectionID(question_items[1]);
                        OBS_COL_FORM_QUESTIONS new_form_question = new OBS_COL_FORM_QUESTIONS();
                        new_form_question.obs_cft_id = cft_id;
                        new_form_question.obs_form_section_id = form_section_id;
                        new_form_question.obs_qat_id = qat_id;
                        new_form_question.obs_col_form_quest_order = order;
                        new_form_question.obs_col_form_quest_wgt = 1;
                        new_form_question.obs_col_form_quest_na_yn = question_items[2];
                        db.OBS_COL_FORM_QUESTIONS.Add(new_form_question);
                        db.SaveChanges();
                        order_counter++;
                    }//end of foreach

                    transaction.Commit();
                    return cft_id;
                }//end of try
                catch (Exception e)
                {
                    Session.Add("errorMessage", e.Message);
                    transaction.Rollback();
                    return -1;
                }
            }//end of  using (var transaction = db.Database.BeginTransaction())

        }