package com.example.csbananasite.controllers;

import com.example.csbananasite.components.MyComponent;
import com.example.csbananasite.model.*;
import com.example.csbananasite.repo.*;
import com.example.csbananasite.service.CustomUserDetailsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Controller
public class UserController implements WebMvcConfigurer {

    @Autowired
    PostNewsCSRepo postNewsCSRepo;
    @Autowired
    SkinsAvtomatyRepo skinsAvtomatyRepo;
    @Autowired
    SkinsNakleykiRepo skinsNakleykiRepo;
    @Autowired
    SkinsNoshiRepo skinsNoshiRepo;
    @Autowired
    SkinsPertatkiRepo skinsPertatkiRepo;
    @Autowired
    SkinsPistoletsRepo skinsPistoletsRepo;
    @Autowired
    UserCSRepo userCSRepo;
    @Autowired
    PromocodeRepo promocodeRepo;
    @Autowired
    PaymentRepo paymentRepo;
    @Autowired
    CheatCSRepo cheatCSRepo;
    @Autowired
    StatistikaUserRepo statistikaUserRepo;
    @Autowired
    MyComponent myComponent;
    @Autowired
    private CustomUserDetailsService userDetailsService;


    @GetMapping("/")
    public String home(Model model) {
        return "redirect:/skins";
    }



    @GetMapping("/autoisation")
    public String autorisation() {
        // Проверяем, авторизован ли пользователь
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            return "redirect:/contact";
        } else {
            return "user/autorisation";
        }
    }

/*
    @GetMapping("/regisation")
    public String regisation() {
        return "user/regisation";
    }

    @PostMapping("/regisation")
    public String trueRegisation(@RequestParam String log, @RequestParam String pass1, @RequestParam String pass2, Model model) {
        String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
        if (log.matches(EMAIL_REGEX) && pass1.equals(pass2)) {
            if (userCSRepo.findByUsername(log) != null) {
                model.addAttribute("error", "The user with this username already exists");
            } else {
                userDetailsService.registerNewUser(log, pass1);
                return "redirect:/autoisation";
            }
        } else {
            model.addAttribute("error", "Incorrect email or passwords don't match");
        }
        return "user/regisation";
    }
    */


    @GetMapping("/contact")
    public String contact(Model model) {
        // Получаем данные текущего авторизованного пользователя
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();

        model.addAttribute("name", username);

        model.addAttribute("akk1", myComponent.getMyAkk1());
        model.addAttribute("akk2", myComponent.getMyAkk2());
        model.addAttribute("akk3", myComponent.getMyAkk3());

        return "user/contact";
    }




    @PostMapping("/promocode")
    public String promocode(@RequestParam String promocode, Model model, HttpSession session) {
        Promocode user_promo = promocodeRepo.findByPromo(promocode);
        System.out.println("check promocode - " + promocode);
        if (user_promo != null) {
            System.out.println("legit promocode - " + promocode);
            session.setAttribute("promo", promocode);
        }
        return "redirect:/skins";
    }



    @GetMapping("/posts")
    public String posts(Model model) {
        Iterable<PostNewsCS> posts = postNewsCSRepo.findAll();
        model.addAttribute("posts", posts);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/posts";
    }
    @GetMapping("/post/{id}")
    public String postid(@PathVariable(value = "id") long id, Model model) {
        PostNewsCS postNewsCS = postNewsCSRepo.findById(id).orElseThrow();
        model.addAttribute("post", postNewsCS);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/postid";
    }



    @GetMapping("/cheatCSs")
    public String cheatCSs(Model model) {
        Iterable<CheatCS> posts = cheatCSRepo.findAll();
        model.addAttribute("posts", posts);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/cheatCSs";
    }
    @GetMapping("/cheatCS/{id}")
    public String cheatCSid(@PathVariable(value = "id") long id, Model model) {
        CheatCS cheatCS = cheatCSRepo.findById(id).orElseThrow();
        model.addAttribute("post", cheatCS);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/cheatCSid";
    }




    @GetMapping("/traff/{promik}/posts")
    public String trafferposts(@PathVariable(value = "promik") String promik, Model model, HttpSession session) {
        Promocode user_promo = promocodeRepo.findByPromo(promik);
        if (user_promo != null) {
            session.setAttribute("promo", promik);
        }

        return "redirect:/posts";
    }
    @GetMapping("/traff/{promik}")
    public String trafferhome(@PathVariable(value = "promik") String promik, Model model, HttpSession session) {
        Promocode user_promo = promocodeRepo.findByPromo(promik);
        if (user_promo != null) {
            session.setAttribute("promo", promik);
        }

        return "redirect:/skins";
    }





    @PostMapping("/filter")
    public String applyFilters(@RequestParam(required = false) String minPrice,
                               @RequestParam(required = false) String maxPrice,
                               @RequestParam(required = false) String searchName, HttpSession session) {
        if (searchName != null && !searchName.isEmpty()) {
            session.setAttribute("search", searchName);
        }
        if (minPrice != null && !minPrice.isEmpty() && !minPrice.equals("null")) {
            session.setAttribute("min_cena", Integer.parseInt(minPrice));
        } else {
            session.setAttribute("min_cena", null);
        }
        if (maxPrice != null && !maxPrice.isEmpty() && !maxPrice.equals("null")) {
            session.setAttribute("max_cena", Integer.parseInt(maxPrice));
        } else {
            session.setAttribute("max_cena", null);
        }

        return "redirect:/skins";
    }

    @GetMapping("/sbrosfilters")
    public String sbrosFilters(HttpSession session) {
        session.setAttribute("search", null);
        session.setAttribute("min_cena", null);
        session.setAttribute("max_cena", null);

        return "redirect:/skins";
    }

    @GetMapping("/skins")
    public String skins(Model model, HttpSession session) {
        String promo = (String) session.getAttribute("promo");

        // Получаем все скины из репозиториев
        List<SkinsAvtomaty> skinsAvtomaty = StreamSupport.stream(skinsAvtomatyRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        List<SkinsNakleyki> skinsNakleyki = StreamSupport.stream(skinsNakleykiRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        List<SkinsNoshi> skinsNoshi = StreamSupport.stream(skinsNoshiRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        List<SkinsPertatki> skinsPertatki = StreamSupport.stream(skinsPertatkiRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        List<SkinsPistolets> skinsPistolets = StreamSupport.stream(skinsPistoletsRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());


        if (promo != null && !promo.equals("no")) {
            skinsAvtomaty.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
            skinsNakleyki.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
            skinsNoshi.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
            skinsPertatki.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
            skinsPistolets.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
        }

        String search_str = (String) session.getAttribute("search");
        Integer min_cena = (Integer) session.getAttribute("min_cena");
        Integer max_cena = (Integer) session.getAttribute("max_cena");

        if (search_str != null && !search_str.isEmpty()) {
            skinsAvtomaty = skinsAvtomaty.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena)
                            && (skin.getName().toLowerCase().contains(search_str.toLowerCase())))
                    .collect(Collectors.toList());
            skinsNakleyki = skinsNakleyki.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena)
                            && (skin.getName().toLowerCase().contains(search_str.toLowerCase())))
                    .collect(Collectors.toList());
            skinsNoshi = skinsNoshi.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena)
                            && (skin.getName().toLowerCase().contains(search_str.toLowerCase())))
                    .collect(Collectors.toList());
            skinsPertatki = skinsPertatki.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena)
                            && (skin.getName().toLowerCase().contains(search_str.toLowerCase())))
                    .collect(Collectors.toList());
            skinsPistolets = skinsPistolets.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena)
                            && (skin.getName().toLowerCase().contains(search_str.toLowerCase())))
                    .collect(Collectors.toList());
        } else if (min_cena != null || max_cena != null) {
            skinsAvtomaty = skinsAvtomaty.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena))
                    .collect(Collectors.toList());
            skinsNakleyki = skinsNakleyki.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena))
                    .collect(Collectors.toList());
            skinsNoshi = skinsNoshi.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena))
                    .collect(Collectors.toList());
            skinsPertatki = skinsPertatki.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena))
                    .collect(Collectors.toList());
            skinsPistolets = skinsPistolets.stream()
                    .filter(skin -> (min_cena == null || skin.getCena() >= min_cena)
                            && (max_cena == null || skin.getCena() <= max_cena))
                    .collect(Collectors.toList());
        }

        // Добавляем атрибуты в модель
        model.addAttribute("skinsAvtomaty", skinsAvtomaty);
        model.addAttribute("skinsNakleyki", skinsNakleyki);
        model.addAttribute("skinsNoshi", skinsNoshi);
        model.addAttribute("skinsPertatki", skinsPertatki);
        model.addAttribute("skinsPistolets", skinsPistolets);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/skins";
    }

    @GetMapping("/skinsAvtomaty/{id}")
    public String skinsAvtomatyid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (promo != null) {
            promo = (String) session.getAttribute("promo");
        }

        SkinsAvtomaty skinsAvtomaty = skinsAvtomatyRepo.findById(id).orElseThrow();
        model.addAttribute("post", skinsAvtomaty);


        List<SkinsAvtomaty> skinsAvtomatyList = StreamSupport.stream(skinsAvtomatyRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        if (promo != null && !promo.equals("no")) {
            skinsAvtomatyList.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
        }
        model.addAttribute("skinsAvtomaty", skinsAvtomatyList);


        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/skinsAvtomatyskinsid";
    }
    @GetMapping("/skinsNakleyki/{id}")
    public String skinsNakleykiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = (String) session.getAttribute("promo");
        SkinsNakleyki skinsNakleyki = skinsNakleykiRepo.findById(id).orElseThrow();
        model.addAttribute("post", skinsNakleyki);

        List<SkinsNakleyki> skinsNakleykiList = StreamSupport.stream(skinsNakleykiRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        if (promo != null && !promo.equals("no")) {
            skinsNakleykiList.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
        }
        model.addAttribute("skinsNakleyki", skinsNakleykiList);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/skinsNakleykiskinsid";
    }
    @GetMapping("/skinsNoshi/{id}")
    public String skinsNoshiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = (String) session.getAttribute("promo");
        SkinsNoshi skinsNoshi = skinsNoshiRepo.findById(id).orElseThrow();
        model.addAttribute("post", skinsNoshi);

        List<SkinsNoshi> skinsNoshiList = StreamSupport.stream(skinsNoshiRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        if (promo != null && !promo.equals("no")) {
            skinsNoshiList.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
        }
        model.addAttribute("skinsNoshi", skinsNoshiList);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/skinsNoshiskinsid";
    }
    @GetMapping("/skinsPertatki/{id}")
    public String skinsPertatkiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = (String) session.getAttribute("promo");
        SkinsPertatki skinsPertatki = skinsPertatkiRepo.findById(id).orElseThrow();
        model.addAttribute("post", skinsPertatki);

        List<SkinsPertatki> skinsPertatkiList = StreamSupport.stream(skinsPertatkiRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        if (promo != null && !promo.equals("no")) {
            skinsPertatkiList.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
        }
        model.addAttribute("skinsPertatki", skinsPertatkiList);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/skinsPertatkiskinsid";
    }
    @GetMapping("/skinsPistolets/{id}")
    public String skinsPistoletsid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = (String) session.getAttribute("promo");
        SkinsPistolets skinsPistolets = skinsPistoletsRepo.findById(id).orElseThrow();
        model.addAttribute("post", skinsPistolets);

        List<SkinsPistolets> skinsPistoletsList = StreamSupport.stream(skinsPistoletsRepo.findAll().spliterator(), false)
                .collect(Collectors.toList());
        if (promo != null && !promo.equals("no")) {
            skinsPistoletsList.forEach(skin -> {
                double discountedPrice = skin.getCena() * 0.8;
                double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
                skin.setCena(roundedPrice);
            });
        }
        model.addAttribute("skinsPistolets", skinsPistoletsList);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());
        } else {
            model.addAttribute("root", null);
        }

        return "user/skinsPistoletsskinsid";
    }



    @GetMapping("/skinsAvtomaty/card/bay/{id}")
    public String bayCardSkinsAvtomatyid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsAvtomaty skinsAvtomaty = skinsAvtomatyRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsAvtomaty.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsAvtomaty.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsAvtomaty.getCena());


        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsAvtomaty.getName());
            session.setAttribute("cena", skinsAvtomaty.getCena());
            session.setAttribute("merch", "card");
            session.setAttribute("adressmoney", myComponent.getCards());
            model.addAttribute("adressmoney", myComponent.getCards());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/card";
    }
    @GetMapping("/skinsNakleyki/card/bay/{id}")
    public String bayCardSkinsNakleykiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsNakleyki skinsNakleyki = skinsNakleykiRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsNakleyki.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsNakleyki.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsNakleyki.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsNakleyki.getName());
            session.setAttribute("cena", skinsNakleyki.getCena());
            session.setAttribute("merch", "card");
            session.setAttribute("adressmoney", myComponent.getCards());
            model.addAttribute("adressmoney", myComponent.getCards());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/card";
    }
    @GetMapping("/skinsNoshi/card/bay/{id}")
    public String bayCardSkinsNoshiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsNoshi skinsNoshi = skinsNoshiRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsNoshi.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsNoshi.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsNoshi.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsNoshi.getName());
            session.setAttribute("cena", skinsNoshi.getCena());
            session.setAttribute("merch", "card");
            session.setAttribute("adressmoney", myComponent.getCards());
            model.addAttribute("adressmoney", myComponent.getCards());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/card";
    }
    @GetMapping("/skinsPertatki/card/bay/{id}")
    public String bayCardSkinsPertatkiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsPertatki skinsPertatki = skinsPertatkiRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsPertatki.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsPertatki.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsPertatki.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsPertatki.getName());
            session.setAttribute("cena", skinsPertatki.getCena());
            session.setAttribute("merch", "card");
            session.setAttribute("adressmoney", myComponent.getCards());
            model.addAttribute("adressmoney", myComponent.getCards());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/card";
    }
    @GetMapping("/skinsPistolets/card/bay/{id}")
    public String bayCardSkinsPistoletsid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsPistolets skinsPistolets = skinsPistoletsRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsPistolets.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsPistolets.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsPistolets.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsPistolets.getName());
            session.setAttribute("cena", skinsPistolets.getCena());
            session.setAttribute("merch", "card");
            session.setAttribute("adressmoney", myComponent.getCards());
            model.addAttribute("adressmoney", myComponent.getCards());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/card";
    }




    @GetMapping("/skinsAvtomaty/crypto/bay/{id}")
    public String bayCryptoSkinsAvtomatyid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsAvtomaty skinsAvtomaty = skinsAvtomatyRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsAvtomaty.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsAvtomaty.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsAvtomaty.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsAvtomaty.getName());
            session.setAttribute("cena", skinsAvtomaty.getCena());
            session.setAttribute("merch", "crypto");
            session.setAttribute("adressmoney", myComponent.getCrypto());
            model.addAttribute("adressmoney", myComponent.getCrypto());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/cryptowallet";
    }
    @GetMapping("/skinsNakleyki/crypto/bay/{id}")
    public String bayCryptoSkinsNakleykiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsNakleyki skinsNakleyki = skinsNakleykiRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsNakleyki.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsNakleyki.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsNakleyki.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsNakleyki.getName());
            session.setAttribute("cena", skinsNakleyki.getCena());
            session.setAttribute("merch", "crypto");
            session.setAttribute("adressmoney", myComponent.getCrypto());
            model.addAttribute("adressmoney", myComponent.getCrypto());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/cryptowallet";
    }
    @GetMapping("/skinsNoshi/crypto/bay/{id}")
    public String bayCryptoSkinsNoshiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsNoshi skinsNoshi = skinsNoshiRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsNoshi.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsNoshi.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsNoshi.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsNoshi.getName());
            session.setAttribute("cena", skinsNoshi.getCena());
            session.setAttribute("merch", "crypto");
            session.setAttribute("adressmoney", myComponent.getCrypto());
            model.addAttribute("adressmoney", myComponent.getCrypto());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/cryptowallet";
    }
    @GetMapping("/skinsPertatki/crypto/bay/{id}")
    public String bayCryptoSkinsPertatkiid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsPertatki skinsPertatki = skinsPertatkiRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsPertatki.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsPertatki.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsPertatki.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsPertatki.getName());
            session.setAttribute("cena", skinsPertatki.getCena());
            session.setAttribute("merch", "crypto");
            session.setAttribute("adressmoney", myComponent.getCrypto());
            model.addAttribute("adressmoney", myComponent.getCrypto());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/cryptowallet";
    }
    @GetMapping("/skinsPistolets/crypto/bay/{id}")
    public String bayCryptoSkinsPistoletsid(@PathVariable(value = "id") long id, Model model, HttpSession session) {
        String promo = "no";
        if (session.getAttribute("promo") != null) {
            promo = (String) session.getAttribute("promo");
        }
        SkinsPistolets skinsPistolets = skinsPistoletsRepo.findById(id).orElseThrow();
        if (!promo.equals("no")) {
            double discountedPrice = skinsPistolets.getCena() * 0.8;
            double roundedPrice = Math.round(discountedPrice * 100.0) / 100.0;
            skinsPistolets.setCena(roundedPrice);
        }
        model.addAttribute("post", skinsPistolets.getCena());

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            model.addAttribute("root", authentication.getName());

            session.setAttribute("username", authentication.getName());
            session.setAttribute("userskin", skinsPistolets.getName());
            session.setAttribute("cena", skinsPistolets.getCena());
            session.setAttribute("merch", "crypto");
            session.setAttribute("adressmoney", myComponent.getCrypto());
            model.addAttribute("adressmoney", myComponent.getCrypto());

        } else {
            model.addAttribute("root", null);
        }

        return "pay/cryptowallet";
    }



    @PostMapping("/checkpay")
    public String checkpay(@RequestParam String comment, Model model, HttpSession session) {
        if (session.getAttribute("promo") != null && session.getAttribute("username")
                != null && session.getAttribute("userskin") != null && session.getAttribute("cena") != null
                && session.getAttribute("merch") != null && session.getAttribute("adressmoney") != null) {


            Payment payment = new Payment((String) session.getAttribute("username"), (String) session.getAttribute("userskin"), (Double) session.getAttribute("cena"), (String) session.getAttribute("merch"), (String) session.getAttribute("adressmoney"), comment);
            paymentRepo.save(payment);

            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM");
            String formattedDate = currentDate.format(dateFormatter);

            Optional<StatistikaUser> existingRecord = statistikaUserRepo.findByData(formattedDate);

            if (existingRecord.isPresent()) {
                StatistikaUser statistikaUser = existingRecord.get();
                statistikaUser.setKolvo(statistikaUser.getKolvo() + 1);
                statistikaUserRepo.save(statistikaUser);
            } else {
                StatistikaUser statistikaUser = new StatistikaUser(formattedDate, String.valueOf(1));
                statistikaUserRepo.save(statistikaUser);
            }

            return "user/momento";
        } else {
            return "redirect:/skins";
        }
    }



    @GetMapping("/images/{filename:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        Resource file = new FileSystemResource("src/main/resources/static/images/" + filename);
        return ResponseEntity.ok()
                .cacheControl(CacheControl.noCache())
                .body(file);
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:src/main/resources/static/images/");
    }

}
