public async Task <IActionResult> Create(TournamentVM tournamentVM)
        {
            if (ModelState.IsValid)
            {
                string image = "default_tournament_image.jpg";
                _fileManagementController = new FileManagementController(_appEnvironment);

                #region Image
                //if we uploaded an image
                if (tournamentVM.TournamentImage != null)
                {
                    //  #region File Upload Validation
                    bool fileUploadError = _fileManagementController.ValidateFileUploadExtensionAndSize(ModelState, tournamentVM.TournamentImage, FileType.Image, 2);
                    //return error if there is a file upload Error
                    if (fileUploadError)
                    {
                        TempData["message"] = NotificationSystem.AddMessage("لقد حصل خطأ في تحميل الملف", NotificationType.Danger.Value);
                        return(View(tournamentVM));
                    }
                    // upload and remove existing
                    image = _fileManagementController.UploadFile(tournamentVM.TournamentImage, "Media/Tournament");
                }
                #endregion

                // create tournament
                Tournament tournament = new Tournament()
                {
                    TournamentImage = image,
                    Name            = tournamentVM.Name,
                    Note            = tournamentVM.Note,
                    CreationDate    = DateTime.Now.Date,
                    IsActive        = true
                };

                _context.Add(tournament);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(tournamentVM));
        }
        public async Task <IActionResult> Edit(OfficerVM officerVM)
        {
            if (ModelState.IsValid)
            {
                string image = "defaultofficer.png";
                _fileManagementController = new FileManagementController(_appEnvironment);

                #region Image
                //if we uploaded an image
                if (officerVM.Profileimage != null)
                {
                    //  #region File Upload Validation
                    bool fileUploadError = _fileManagementController.ValidateFileUploadExtensionAndSize(ModelState, officerVM.Profileimage, FileType.Image, 2);
                    //return error if there is a file upload Error
                    if (fileUploadError)
                    {
                        TempData["message"] = NotificationSystem.AddMessage("لقد حصل خطأ في تحميل الملف", NotificationType.Danger.Value);
                        return(View(officerVM));
                    }
                    // upload and remove existing
                    image = _fileManagementController.UploadFile(officerVM.Profileimage, "Media/Officer_Profile");
                }
                else
                {
                    image = officerVM.ExistingImage;
                }
                #endregion

                // create officer
                Officer officer = new Officer()
                {
                    Id                    = officerVM.Id,
                    TournamentId          = officerVM.TournamentId,
                    Name                  = officerVM.Name,
                    MilitaryNumber        = officerVM.MilitaryNumber,
                    PhoneNumber           = officerVM.PhoneNumber,
                    Email                 = officerVM.Email,
                    BirthAddress          = officerVM.BirthAddress,
                    BirthDate             = officerVM.BirthDate,
                    Nationality           = officerVM.Nationality,
                    Address               = officerVM.Address,
                    BloodType             = officerVM.BloodType,
                    Height                = officerVM.Height,
                    PreviousJob           = officerVM.PreviousJob,
                    HealthProblem         = officerVM.HealthProblem,
                    RatingEnteringYear    = officerVM.RatingEnteringYear,
                    RatingEnteringNumber  = officerVM.RatingEnteringNumber,
                    Specialization        = officerVM.Specialization,
                    RatingGradutionYear   = officerVM.RatingGradutionYear,
                    RatingGradutionNumber = officerVM.RatingGradutionNumber,
                    Notes                 = officerVM.Notes,
                    ProfileImage          = image,
                    IsActive              = true,
                    CreationDate          = DateTime.Now
                };
                _context.Officers.Update(officer);



                // clear all EducationalAttainments for current officer
                ClearEducationalAttainments(officerVM.Id);
                // loop each row in educational list then insert to database
                foreach (EducationalAttainment item in officerVM.EducationalAttainments)
                {
                    EducationalAttainment educationalAttainment = new EducationalAttainment()
                    {
                        Certificate = item.Certificate,
                        Source      = item.Source,
                        Date        = item.Date,
                        Grade       = item.Grade,
                        OfficerId   = officer.Id
                    };
                    _context.EducationalAttainments.Update(educationalAttainment);
                }


                // clear all Language for current officer
                ClearLanguages(officerVM.Id);
                // loop each row in Language list then insert to database
                foreach (Language item in officerVM.Languages)
                {
                    Language language = new Language()
                    {
                        Name      = item.Name,
                        Listen    = item.Listen,
                        Speak     = item.Speak,
                        Read      = item.Read,
                        Write     = item.Write,
                        OfficerId = officer.Id
                    };
                    _context.Languages.Update(language);
                }

                // clear all Hobbies for current officer
                ClearHobbies(officerVM.Id);
                // loop each row in Hobby list then insert to database
                foreach (Hobby item in officerVM.Hobbies)
                {
                    Hobby hobby = new Hobby()
                    {
                        Name        = item.Name,
                        Explanation = item.Explanation,
                        Level       = item.Level,
                        OfficerId   = officer.Id
                    };
                    _context.Hobbies.Update(hobby);
                }

                await _context.SaveChangesAsync();

                TempData["message"] = NotificationSystem.AddMessage("تم تعديل ضابط بنجاح", NotificationType.Success.Value);
                return(RedirectToAction(nameof(Index)));
            }
            return(View(officerVM));
        }
        public async Task <IActionResult> Create(OfficerVM officerVM, int TournamnetId)
        {
            // if has an error  on post i keep latest tournament
            var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            // tournament Id assigned to current user Id
            int        TournamentId = _context.UserTournaments.Where(u => u.UserId == userId).Select(t => t.TournamentId).FirstOrDefault();
            Tournament tournament   = _context.Tournaments.Where(t => t.Id == TournamentId).First(); officerVM.TournamentId = tournament.Id;

            officerVM.TournamentId   = tournament.Id;
            officerVM.TournamentName = tournament.Name;

            if (ModelState.IsValid)
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        string image = "defaultofficer.png";
                        _fileManagementController = new FileManagementController(_appEnvironment);

                        #region Image
                        //if we uploaded an image
                        if (officerVM.Profileimage != null)
                        {
                            //  #region File Upload Validation
                            bool fileUploadError = _fileManagementController.ValidateFileUploadExtensionAndSize(ModelState, officerVM.Profileimage, FileType.Image, 2);
                            //return error if there is a file upload Error
                            if (fileUploadError)
                            {
                                TempData["message"] = NotificationSystem.AddMessage("لقد حصل خطأ في تحميل الملف", NotificationType.Danger.Value);
                                return(View(officerVM));
                            }
                            // upload and remove existing
                            image = _fileManagementController.UploadFile(officerVM.Profileimage, "Media/Officer_Profile");
                        }
                        #endregion

                        // create officer
                        Officer officer = new Officer()
                        {
                            TournamentId          = TournamnetId,
                            Name                  = officerVM.Name,
                            MilitaryNumber        = officerVM.MilitaryNumber,
                            PhoneNumber           = officerVM.PhoneNumber,
                            Email                 = officerVM.Email,
                            BirthAddress          = officerVM.BirthAddress,
                            BirthDate             = officerVM.BirthDate,
                            Nationality           = officerVM.Nationality,
                            Address               = officerVM.Address,
                            BloodType             = officerVM.BloodType,
                            Height                = officerVM.Height,
                            PreviousJob           = officerVM.PreviousJob,
                            HealthProblem         = officerVM.HealthProblem,
                            RatingEnteringYear    = officerVM.RatingEnteringYear,
                            RatingEnteringNumber  = officerVM.RatingEnteringNumber,
                            Specialization        = officerVM.Specialization,
                            RatingGradutionYear   = officerVM.RatingGradutionYear,
                            RatingGradutionNumber = officerVM.RatingGradutionNumber,
                            Notes                 = officerVM.Notes,
                            ProfileImage          = image,
                            IsActive              = true,
                            CreationDate          = DateTime.Now
                        };
                        _context.Officers.Add(officer);
                        _context.SaveChanges();



                        // loop each row in educational list then insert to database
                        foreach (EducationalAttainment item in officerVM.EducationalAttainments)
                        {
                            if (!String.IsNullOrEmpty(item.Certificate))
                            {
                                EducationalAttainment educationalAttainment = new EducationalAttainment()
                                {
                                    Certificate = item.Certificate,
                                    Source      = item.Source,
                                    Date        = item.Date,
                                    Grade       = item.Grade,
                                    OfficerId   = officer.Id
                                };
                                _context.EducationalAttainments.Add(educationalAttainment);
                            }
                        }

                        // loop each row in Language list then insert to database
                        foreach (Language item in officerVM.Languages)
                        {
                            if (!String.IsNullOrEmpty(item.Name))
                            {
                                Language language = new Language()
                                {
                                    Name      = item.Name,
                                    Listen    = item.Listen,
                                    Speak     = item.Speak,
                                    Read      = item.Read,
                                    Write     = item.Write,
                                    OfficerId = officer.Id
                                };
                                _context.Languages.Add(language);
                            }
                        }

                        // loop each row in Hobby list then insert to database
                        foreach (Hobby item in officerVM.Hobbies)
                        {
                            if (!String.IsNullOrEmpty(item.Name))
                            {
                                Hobby hobby = new Hobby()
                                {
                                    Name        = item.Name,
                                    Explanation = item.Explanation,
                                    Level       = item.Level,
                                    OfficerId   = officer.Id
                                };
                                _context.Hobbies.Add(hobby);
                            }
                        }

                        await _context.SaveChangesAsync();

                        transaction.Commit();
                        TempData["message"] = NotificationSystem.AddMessage("تم اضافة ضابط بنجاح", NotificationType.Success.Value);
                        return(RedirectToAction(nameof(Index)));
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Console.WriteLine("Error occurred.");
                    }
                }
            }
            TempData["message"] = NotificationSystem.AddMessage("يجب التأكد من حقل الدورة قبل ادخال الضابط", NotificationType.Danger.Value);

            return(View(officerVM));
        }
        public async Task <IActionResult> Edit(int id, TournamentVM tournamentVM)
        {
            if (id != tournamentVM.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    List <Officer> officers = _context.Officers.Where(t => t.TournamentId == tournamentVM.Id).ToList();

                    if (!tournamentVM.IsActive)
                    {
                        foreach (var item in officers)
                        {
                            item.IsActive = false;
                            _context.Officers.Update(item);
                        }
                    }
                    else
                    {
                        foreach (var item in officers)
                        {
                            item.IsActive = true;
                            _context.Officers.Update(item);
                        }
                    }

                    string image = "default_tournament_image.jpg";
                    _fileManagementController = new FileManagementController(_appEnvironment);

                    #region Image
                    //if we uploaded an image
                    if (tournamentVM.TournamentImage != null)
                    {
                        //  #region File Upload Validation
                        bool fileUploadError = _fileManagementController.ValidateFileUploadExtensionAndSize(ModelState, tournamentVM.TournamentImage, FileType.Image, 2);
                        //return error if there is a file upload Error
                        if (fileUploadError)
                        {
                            TempData["message"] = NotificationSystem.AddMessage("لقد حصل خطأ في تحميل الملف", NotificationType.Danger.Value);
                            return(View(tournamentVM));
                        }
                        // upload and remove existing
                        image = _fileManagementController.UploadFile(tournamentVM.TournamentImage, "Media/Tournament");
                    }
                    else
                    {
                        image = tournamentVM.ExistingTournamentImage;
                    }
                    #endregion

                    Tournament tournament = _context.Tournaments.Find(tournamentVM.Id);
                    tournament.IsActive        = tournamentVM.IsActive;
                    tournament.Name            = tournamentVM.Name;
                    tournament.Note            = tournamentVM.Note;
                    tournament.TournamentImage = image;
                    _context.Update(tournament);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TournamentExists(tournamentVM.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                TempData["message"] = NotificationSystem.AddMessage("تم تعديل الدورة بنجاح", NotificationType.Success.Value);

                return(RedirectToAction(nameof(Index)));
            }
            return(View(tournamentVM));
        }