// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';


import { ConfigService } from 'src/app/providers/config.service';
import { LayoutService } from '../../providers/layout.service';
import { FavoritesService } from '../../providers/favorites.service';
import { CompaniesService } from '../../providers/companies.service';
import { ProdService } from 'src/app/providers/prod.service';
import { ServiceCard } from '../../models/serviceCard.model';

@Component({
  selector: 'app-onlineshop',
  templateUrl: './onlineshop.component.html',
  styleUrls: ['./onlineshop.component.scss'],
  standalone: false,
})
export class OnlineshopComponent implements OnInit{


  constructor(private prodService : ProdService,
    		      private activatedRoute: ActivatedRoute,
              private location : Location,
              private router : Router,
              private companiesService: CompaniesService,
              private favoritesService: FavoritesService,
              private configService: ConfigService,
              private layoutService: LayoutService,){}

  // VARIABILI
  responsiveOptions: any[] = [
    { breakpoint: '1024px', numVisible: 5 },
    { breakpoint: '768px', numVisible: 3 },
    { breakpoint: '560px', numVisible: 1 }
  ];
  filtered_lst_products: any[][] = []; 
  lst_typeproducts: any[] = []; 
  lst_products: any[] = [];
  filter: any = {};
  filterTypewine:any;
  lstFilter: any[] = [];
  Stars: any[] = [];
  score_product =0;
  type: any = -1;
  cerca?: string;
  cmp_id: number = 0;
  prt_id:number = 0;
  rec = '';
  onlineshopImageUrl = '';


  private paramsSubscription!: Subscription;

  ngOnInit(): void {
    this.onlineshopImageUrl = this.configService.onlineshopImageUrl;
    this.paramsSubscription = this.activatedRoute.params.subscribe((params) => {
			if (params['cmp_id']) this.cmp_id = +params['cmp_id'];
      if (params['prt_id']) this.prt_id = +params['prt_id'];
		});
    this.initHeroImage();
   	this.resetFilter();
    this.resetFilterTypeWine();
    this.prodService.get_typewine(this.filterTypewine).subscribe(res => {
      this.lst_typeproducts = res;
      this.filtered_lst();
    });
  }

  ionViewWillEnter() {
    this.loadCompanyInfo();
	}

  ngOnDestroy() {
		this.paramsSubscription?.unsubscribe();
	}


//-------------------------------------------------
//---------------COMPANY---------------------------
//-------------------------------------------------
	company: any = null;
	heroImage: string | null = null;
	heroBackgroundClass: string = '';
	heroOpacity: number = 0.8;
	isFavorite: boolean = false;
	serviceDescription: string = '';
	activeCard: ServiceCard | null = null;
  headerCollapsed: boolean = false;


  loadCompanyInfo(): void {
		this.companiesService.GetCompany(this.cmp_id).subscribe({
			next: (data: any) => {
				this.company = data;
				if (data?.name) {
					this.layoutService.setPageConfig({ title: data.name });
				}
			},
		});
	}

  getServiceDescription(): string {
		return this.serviceDescription || 'Servizio di compravendita online.';
	}

  getCompanyAddress(): string {
		if (!this.company) return '';
		const of = this.company.of;
		if (of) {
			const parts = [of.of_address, of.of_number, of.of_cap, of.of_municipality_name].filter(Boolean);
			if (parts.length > 0) return parts.join(', ');
		}
		const parts = [
			this.company.cmp_rlegal_res_address,
			this.company.cmp_rlegal_res_number,
			this.company.cmp_rlegal_res_cup,
			this.company.cmp_rlegal_res_city,
		].filter(Boolean);
		return parts.join(', ');
	}

  getDirections(): void {
		const addr = this.getCompanyAddress();
		if (addr) {
			window.open(`https://maps.google.com/maps?q=${encodeURIComponent(addr)}`, '_system');
		}
	}
  
  callCompany(): void {
		if (this.company?.cmp_phone_number) {
			window.open(`tel:${this.company.cmp_phone_number}`, '_system');
		}
	}

  private initHeroImage(): void {
		const card: ServiceCard | null = this.companiesService.activeServiceCard;
		if (card) {
			this.activeCard = card;
			this.serviceDescription = card.srv_description || '';
			this.isFavorite = this.favoritesService.isFavorite(card.srv_id, card.company?.id || 0);
			if (card.srv_show_hero_image && card.srv_background_image) {
				this.heroImage = card.srv_background_image;
				this.heroBackgroundClass = card.srv_background_class || '';
				this.heroOpacity = card.srv_background_opacity ?? 0.8;
			}
		}
	}

  toggleHeader(): void {
		this.headerCollapsed = !this.headerCollapsed;
	}

  toggleFavorite(): void {
		if (!this.activeCard) return;
		const srvId = this.activeCard.srv_id;
		const cmpId = this.activeCard.company?.id || 0;
		this.favoritesService.toggleFavorite(srvId, cmpId);
		this.isFavorite = this.favoritesService.isFavorite(srvId, cmpId);
	}

  // LISTA PRODOTTI

  filtered_lst(){
    this.filtered_lst_products=[];
    for(let i=0;i<this.lst_typeproducts.length;i++){
      this.filter.type_wine = this.lst_typeproducts[i].tpw_id;
      let tmpfilter=JSON.parse(JSON.stringify(this.filter));
      this.filtered_lst_products.push([]);
      this.callListProduct(tmpfilter,i)
      
    }
  }

  callListProduct(filter:any,i:number){
  this.prodService.lstProducts(filter).subscribe(res => {

        switch (this.rec){
          case 'net':
            this.score_product = res?.vote_network;
          break;
          case 'friends':
            this.score_product = res?.vote_friends;
          break;
          default:
          break;
        }
      this.lst_products = res;
      this.filtered_lst_products[i]=this.lst_products;

    });
  }

  // RESET FILTERS

  resetFilter() {
    this.filter = {};
    this.filter.cmp_id = this.cmp_id;
    this.filter.pagina = 1;
    this.filter.righePagina = 10;
    this.filter.orderBy = 'prd_title';
    this.filter.type_wine = -1;
    this.filter.price_from = null;
    this.filter.price_to = null;
    this.filter.fav = false;

    this.lstFilter = [];
  }

    resetFilterTypeWine(){
    this.filterTypewine = {};
    this.filterTypewine.tpw_cmp_id = this.cmp_id;
    this.filterTypewine.pagina = 1;
    this.filterTypewine.righePagina = 99999;
    this.filterTypewine.orderBy = 'tpw_name';
  }
   
/*  RECENSIONI
  getStarName(value: number, check_number: number) {
    if (value > check_number + 1) {
      return '../../../assets/icons/app/icona-stella.svg';
    } else if (value === check_number + 1) {
      //return 'star-half';
      return '../../../assets/icons/app/icona-stella.svg';
    }
    else if (value <= check_number) {
      //Stella piena
      return '../../../assets/icons/app/icona-stella-2.svg';
    }
    return '';
  }*/


  // INDIRIZZAMENTI

  goToTprd(t : number){
    this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'products', t]);
  }
  prd_detail(prd_id: number){
    this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'product-detail', prd_id ]);
  }
  goToPrdt(){
    this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'products']);
  }
  goToCart(){
    this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'cart']);
  }
  goToOrd(){
    this.router.navigate(['/portale', this.prt_id, 'company', this.cmp_id, 'service', 'onlineshop', 'orders']);
  }
  goBack(): void{
    this.location.back();
  }

}

