using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using QRRapidoApp.Services; using System.Security.Claims; using System.Threading.Tasks; using QRRapidoApp.Models.ViewModels; using System.Linq; namespace QRRapidoApp.Controllers { [Authorize] public class PagamentoController : Controller { private readonly IPlanService _planService; private readonly AdDisplayService _adDisplayService; private readonly IUserService _userService; private readonly StripeService _stripeService; private readonly ILogger _logger; public PagamentoController(IPlanService planService, IUserService userService, StripeService stripeService, ILogger logger, AdDisplayService adDisplayService) { _planService = planService; _userService = userService; _stripeService = stripeService; _logger = logger; _adDisplayService = adDisplayService; } [HttpGet] public async Task SelecaoPlano() { var plans = await _planService.GetActivePlansAsync(); var countryCode = GetUserCountryCode(); // Implement this method based on your needs _adDisplayService.SetViewBagAds(ViewBag); var model = new SelecaoPlanoViewModel { Plans = plans, CountryCode = countryCode }; return View(model); } [HttpPost] public async Task CreateCheckout(string planId) { var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(userId)) { return Json(new { success = false, error = "User not authenticated" }); } var plan = await _planService.GetPlanByIdAsync(planId); if (plan == null) { return Json(new { success = false, error = "Plan not found" }); } var countryCode = GetUserCountryCode(); var priceId = plan.PricesByCountry.ContainsKey(countryCode) ? plan.PricesByCountry[countryCode].StripePriceId : plan.StripePriceId; try { var checkoutUrl = await _stripeService.CreateCheckoutSessionAsync(userId, priceId); return Json(new { success = true, url = checkoutUrl }); } catch (Exception ex) { _logger.LogError(ex, $"Error creating checkout session for user {userId} and plan {planId}"); return Json(new { success = false, error = ex.Message }); } } [HttpGet] public IActionResult Sucesso() { _adDisplayService.SetViewBagAds(ViewBag); ViewBag.SuccessMessage = "Pagamento concluĂ­do com sucesso! Bem-vindo ao Premium."; return View(); } [HttpGet] public IActionResult Cancelar() { _adDisplayService.SetViewBagAds(ViewBag); ViewBag.CancelMessage = "O pagamento foi cancelado. VocĂȘ pode tentar novamente a qualquer momento."; return View("SelecaoPlano"); } [HttpPost] [AllowAnonymous] public async Task StripeWebhook() { try { using var reader = new StreamReader(HttpContext.Request.Body); var json = await reader.ReadToEndAsync(); var signature = Request.Headers["Stripe-Signature"].FirstOrDefault(); if (string.IsNullOrEmpty(signature)) { return BadRequest("Missing Stripe signature"); } await _stripeService.HandleWebhookAsync(json, signature); return Ok(); } catch (Exception ex) { _logger.LogError(ex, "Error processing Stripe webhook"); return BadRequest(ex.Message); } } private string GetUserCountryCode() { // Prioritize Cloudflare header, fallback to a default or other methods return HttpContext.Request.Headers["CF-IPCountry"].FirstOrDefault() ?? "BR"; } } }