using ConstructorAppUI.Dtos.FooterDtos;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text;

namespace ConstructorAppUI.Controllers
{
    public class FooterController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly string _apiBaseUrl;

        public FooterController(IHttpClientFactory httpClientFactory, IWebHostEnvironment webHostEnvironment, IConfiguration configuration)
        {
            _httpClientFactory = httpClientFactory;
            _webHostEnvironment = webHostEnvironment;
            _apiBaseUrl = configuration["ApiSettings:BaseUrl"];
        }

        public async Task<IActionResult> Index()
        {
            var client = _httpClientFactory.CreateClient();
            var responseMessage = await client.GetAsync($"{_apiBaseUrl}/api/Footer");
            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<List<ResultFooterDto>>(jsonData);
                return View(values);
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> UpdateFooter(int id)
        {
            var client = _httpClientFactory.CreateClient();
            var responseMessage = await client.GetAsync($"{_apiBaseUrl}/api/Footer/{id}");
            if (responseMessage.IsSuccessStatusCode)
            {
                var jsonData = await responseMessage.Content.ReadAsStringAsync();
                var values = JsonConvert.DeserializeObject<UpdateFooterDto>(jsonData);
                return View(values);
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UpdateFooter(UpdateFooterDto updateFooterDto, IFormFile ImageFile)
        {
            var client = _httpClientFactory.CreateClient();

            // Mevcut "Footer" verisini al
            var existingSliderResponse = await client.GetAsync($"{_apiBaseUrl}/api/Footer/{updateFooterDto.FooterID}");
            if (existingSliderResponse.IsSuccessStatusCode)
            {
                var existingJsonData = await existingSliderResponse.Content.ReadAsStringAsync();
                var existingSlider = JsonConvert.DeserializeObject<UpdateFooterDto>(existingJsonData);

                // Görseller için "wwwroot/Images" klasörünün varlığını kontrol et
                var imagesPath = Path.Combine(_webHostEnvironment.WebRootPath, "Images");
                if (!Directory.Exists(imagesPath))
                {
                    Directory.CreateDirectory(imagesPath);
                }

                // ImageUrl için işlem
                if (ImageFile != null && ImageFile.Length > 0)
                {
                    // Eski görseli sil
                    if (!string.IsNullOrEmpty(existingSlider.LogoUrl))
                    {
                        var oldImagePath = Path.Combine(_webHostEnvironment.WebRootPath, existingSlider.LogoUrl.TrimStart('/'));
                        if (System.IO.File.Exists(oldImagePath))
                        {
                            System.IO.File.Delete(oldImagePath);
                        }
                    }

                    // Yeni görseli yükle
                    var fileName = Path.GetFileName(ImageFile.FileName);
                    var imagePath = Path.Combine(imagesPath, fileName);
                    using (var stream = new FileStream(imagePath, FileMode.Create))
                    {
                        await ImageFile.CopyToAsync(stream);
                    }
                    updateFooterDto.LogoUrl = $"/Images/{fileName}";
                }
                else
                {
                    updateFooterDto.LogoUrl = existingSlider.LogoUrl;
                }

                // API'ye güncelleme isteği gönder
                var updatedJsonData = JsonConvert.SerializeObject(updateFooterDto);
                StringContent stringContent = new StringContent(updatedJsonData, Encoding.UTF8, "application/json");
                var responseMessage = await client.PutAsync($"{_apiBaseUrl}/api/Footer/", stringContent);
                if (responseMessage.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index");
                }
            }

            return View(updateFooterDto);
        }
    }
}
