using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using atakanozbancom.Models.classes;

namespace atakanozbancom.Controllers
{
    public class adminController : Controller
    {
        private readonly Context db = new Context();

        [Authorize]
        public ActionResult Index() // shows what we have
        {
            var value = db.MyProjects.ToList();
            return View(value);
        }

        [HttpGet]
        public ActionResult myprojectsget(int id)
        {
            var p = db.MyProjects
                      .Include(x => x.Translations)
                      .FirstOrDefault(x => x.id == id);

            if (p == null)
                return HttpNotFound();

            var tr = p.Translations?
                       .FirstOrDefault(t => t.culture == "tr" || t.culture == "tr-TR");

            var vm = new AdminMyProjectsEditVM
            {
                id = p.id,
                image = p.image,
                iframe = p.iframe,

                TitleEN = p.title,
                DescEN = p.description,

                TitleTR = tr != null ? tr.title : "",
                DescTR = tr != null ? tr.description : ""
            };

            return View("myprojectsget", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult myprojectsget(AdminMyProjectsEditVM vm, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
                return View("myprojectsget", vm);

            var p = db.MyProjects.FirstOrDefault(x => x.id == vm.id);
            if (p == null) return HttpNotFound();

            var imageUrl = p.image;

            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
                    var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".webp" };

                    if (!allowedExtensions.Contains(ext))
                    {
                        ModelState.AddModelError("", "You can just upload these formats: '.jpg', '.jpeg', '.png', '.webp'");
                        return View("myprojectsget", vm);
                    }

                    var maxFileSize = 5 * 1024 * 1024;
                    if (file.ContentLength > maxFileSize)
                    {
                        ModelState.AddModelError("", "The size of file exceeds 5MB limit.");
                        return View("myprojectsget", vm);
                    }

                    var uploadsRoot = Server.MapPath("~/Content/uploads/projects");
                    if (!Directory.Exists(uploadsRoot))
                        Directory.CreateDirectory(uploadsRoot);

                    var fileName = Guid.NewGuid().ToString("N") + ext;
                    var filePath = Path.Combine(uploadsRoot, fileName);
                    file.SaveAs(filePath);

                    imageUrl = "/Content/uploads/projects/" + fileName;
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "An error occured while upload: " + ex.Message);
                    return View("myprojectsget", vm);
                }
            }

            // EN -> base
            p.title = vm.TitleEN;
            p.description = vm.DescEN;
            p.image = imageUrl;
            p.iframe = vm.iframe;

            // TR -> translations
            var tr = db.myprojectstranslations
                       .FirstOrDefault(x => x.project_id == p.id && (x.culture == "tr" || x.culture == "tr-TR"));

            if (tr == null)
            {
                tr = new myprojectstranslation { project_id = p.id, culture = "tr" };
                db.myprojectstranslations.Add(tr);
            }

            tr.title = vm.TitleTR;
            tr.description = vm.DescTR;

            db.SaveChanges();
            TempData["ok"] = "Project updated successfully!";
            return RedirectToAction("myprojectsget", new { id = p.id });
        }

        public ActionResult myprojectsupdate(myprojects x)
        {
            var ag = db.MyProjects.Find(x.id);
            ag.description = x.description;
            ag.title = x.title;
            ag.image = x.image;
            ag.iframe = x.iframe;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult newmppost() // newmppost = New My Projects Post
        {
            return View(new AdminMyProjectsEditVM());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult newmppost(AdminMyProjectsEditVM vm, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
                return View(vm);

            string imageUrl = vm.image;

            try
            {
                if (file != null && file.ContentLength > 0)
                {
                    var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
                    var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".webp" };

                    if (!allowedExtensions.Contains(ext))
                    {
                        ModelState.AddModelError("", "You can just upload these formats: '.jpg', '.jpeg', '.png', '.webp'");
                        return View(vm);
                    }

                    var maxFileSize = 5 * 1024 * 1024;
                    if (file.ContentLength > maxFileSize)
                    {
                        ModelState.AddModelError("", "The size of file exceeds 5MB limit.");
                        return View(vm);
                    }

                    var uploadsRoot = Server.MapPath("~/Content/uploads/projects");
                    if (!Directory.Exists(uploadsRoot))
                        Directory.CreateDirectory(uploadsRoot);

                    var fileName = Guid.NewGuid().ToString("N") + ext;
                    var filePath = Path.Combine(uploadsRoot, fileName);
                    file.SaveAs(filePath);

                    imageUrl = "/Content/uploads/projects/" + fileName;
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "An errror occured while upload: " + ex.Message);
                return View(vm);
            }

            // EN -> base table
            var newProject = new myprojects
            {
                title = vm.TitleEN,
                description = vm.DescEN,
                image = imageUrl,
                iframe = vm.iframe
            };

            db.MyProjects.Add(newProject);
            db.SaveChanges();

            // TR -> translations
            var tr = new myprojectstranslation
            {
                project_id = newProject.id,
                culture = "tr",
                title = vm.TitleTR,
                description = vm.DescTR
            };

            db.myprojectstranslations.Add(tr);
            db.SaveChanges();

            TempData["ok"] = "Project added successfully!";
            return RedirectToAction("Index");
        }

        public ActionResult myprojectsdelete(int id)
        {
            var mpd = db.MyProjects.Find(id); // mpd = my projects delete
            if (mpd != null)
            {
                db.MyProjects.Remove(mpd);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult EditProject(AdminMyProjectsEditVM vm)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return View("myprojectsget", vm);
        //    }

        //    var p = db.MyProjects.FirstOrDefault(x => x.id == vm.id);
        //    if (p == null) return HttpNotFound();

        //    p.image = vm.image;
        //    p.iframe = vm.iframe;
        //    p.title = vm.TitleEN;
        //    p.description = vm.DescEN;

        //    var tr = db.myprojectstranslations
        //               .FirstOrDefault(x => x.project_id == p.id && (x.culture == "tr" || x.culture == "tr-TR"));

        //    if (tr == null)
        //    {
        //        tr = new myprojectstranslation { project_id = p.id, culture = "tr" };
        //        db.myprojectstranslations.Add(tr);
        //    }

        //    tr.title = vm.TitleTR;
        //    tr.description = vm.DescTR;

        //    db.SaveChanges();

        //    TempData["ok"] = "Project updated.";
        //    return RedirectToAction("myprojectsget", new { id = p.id });
        //}
    }
}