<?php
		$pageId = (get_current_screen() == null) ? '' : get_current_screen()->id ;
		$tarots = array();
		$tarotsN = array();
		$tarotsAll = array();


		// dependiendo desde que pagina se cargue la funcion TkNaP_free_option
		if ($pageId == 'tarokkina_free_page_crb_carbon_fields_container_tarot_free') {
			$tarots = carbon_get_theme_option('tarokki_free_complex') ?? [];
		}else{
			$tarots = get_option('tarokki_tarotsAll_free') ?? [];
		}

		// Validar que $tarots es un array antes del foreach
		if ( ! is_array( $tarots ) ) {
			$tarots = [];
		}

	foreach ( $tarots as $tarot) {
		
		// Validar que $tarot es un array válido y tiene la clave necesaria
		if ( ! is_array( $tarot ) || ! isset( $tarot['tkta_free_barajas'] ) ) {
			continue; // Saltar este elemento si no es válido
		}

		$deck_free = $tarot['tkta_free_barajas'];
		
		// Validar que deck_free no esté vacío
		if ( empty( $deck_free ) ) {
			continue; // Saltar si no hay deck asignado
		}
		
		$tarotsAll[] = $tarot;

			$args = array(
				'post_type' => 'tarokkina_free',
				'tax_query' => array(
					array(
						'taxonomy' => 'tarokkina_free-cat',
						'field' => 'id',
						'terms' => $deck_free,
						'include_children' => true,
						)
					),
				'post_status' => 'publish',
				'posts_per_page' => -1,
				'order' => 'ASC'
				);
				$cardsQuery = new WP_Query( $args );
				$cardsQuery = $cardsQuery->posts;

			unset($tarots);
			unset($tarotsN);
			$nombreSC = 'tarokina_tarokina_free';
			$tarots [] = $tarot;
			$tarotsN[] = $nombreSC;

			update_option( 'tarokina_tarokina_free', array_fill_keys($tarotsN,$tarots) );

			 // Crear transient con las imagenes de la categoría
			 $args = array(
				'post_type' => 'tarokkina_free',
				'fields'=>'ids',
				'tax_query' => array(
					array(
						'taxonomy' => 'tarokkina_free-cat',
						'field' => 'term_id',
						'terms' => $deck_free,
						'include_children' => true,
						)
					),
				'post_status' => 'publish',
				'posts_per_page' => -1
				);
	
			$cardsids = new WP_Query( $args );
			
	
			update_option( $deck_free. '_tarokki_cardsids_free', $cardsids->posts );

			$Posts_ID = $cardsids->posts ?? [];
			$cards = [];
			$cards_ssl = [];
			foreach ($Posts_ID as $Post_ID) {
				$cardID = get_post_thumbnail_id( $Post_ID );
				$cardImg = wp_get_attachment_image_src( $cardID, 'tarokkina_free-mini');
				
				if ($cardImg == false ) {
					$cards[$Post_ID]= plugin_dir_url(dirname( __FILE__ ) ).'img/no-card.png';
					$cards_ssl[$Post_ID]= str_replace('http://','https://', plugin_dir_url(dirname( __FILE__ ) ).'img/no-card.png');
				}else{
					$cards[$Post_ID]= $cardImg[0];
					$cards_ssl[$Post_ID]= str_replace('http://','https://',$cardImg[0]);		
				}
			}

			update_option( $deck_free .'_tkna_free_deck' , $cards);
			update_option( $deck_free .'_tkna_free_deck_ssl' , $cards_ssl);

		}

			update_option( 'tarokki_tarotsAll_free',$tarotsAll);
			delete_option('_tarokki_checkCartas_free' );