<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

const SPICEPAY_SHOP_PAGE_CACHE_GROUP = 'spicepay-shop';
const SPICEPAY_SHOP_PAGE_CACHE_TTL   = MINUTE_IN_SECONDS;

function spicepay_shop_brand_name() {
	if ( class_exists( 'Spicepay_Settings' ) ) {
		$name = Spicepay_Settings::get( 'business_name' );
		if ( ! empty( $name ) ) {
			return $name;
		}
	}
	return get_bloginfo( 'name' );
}

function spicepay_shop_find_page_with_shortcode( $shortcode ) {
	$cache_key = 'spicepay_shop_pageshortcode_' . md5( $shortcode );
	$cached    = wp_cache_get( $cache_key, SPICEPAY_SHOP_PAGE_CACHE_GROUP );
	if ( false !== $cached ) {
		return '__none__' === $cached ? null : $cached;
	}
	foreach ( get_pages( array( 'sort_column' => 'menu_order' ) ) as $page ) {
		if ( has_shortcode( $page->post_content, $shortcode ) ) {
			$url = get_permalink( $page );
			wp_cache_set( $cache_key, $url, SPICEPAY_SHOP_PAGE_CACHE_GROUP, SPICEPAY_SHOP_PAGE_CACHE_TTL );
			return $url;
		}
	}
	wp_cache_set( $cache_key, '__none__', SPICEPAY_SHOP_PAGE_CACHE_GROUP, SPICEPAY_SHOP_PAGE_CACHE_TTL );
	return null;
}

function spicepay_shop_plugin_configured() {
	if ( ! class_exists( 'Spicepay_Settings' ) ) {
		return false;
	}
	$api_key    = (string) Spicepay_Settings::get( 'api_key' );
	$profile_id = (string) Spicepay_Settings::get( 'profile_id' );
	return '' !== trim( $api_key ) && '' !== trim( $profile_id );
}

function spicepay_shop_footer_copy() {
	$saved = trim( (string) spicepay_shop_customizer_get( 'footer_copyright' ) );
	if ( '' !== $saved ) {
		return $saved;
	}

	$out = '© ' . esc_html( gmdate( 'Y' ) ) . ' ' . esc_html( spicepay_shop_brand_name() );
	if ( class_exists( 'Spicepay_Settings' ) ) {
		$email   = Spicepay_Settings::get( 'business_email' );
		$support = Spicepay_Settings::get( 'business_support' );
		if ( $email ) {
			$out .= ' · <a href="' . esc_url( 'mailto:' . $email ) . '" class="hover:text-fg">' . esc_html( $email ) . '</a>';
		}
		if ( $support ) {
			$out .= ' · ' . esc_html( $support );
		}
	}
	return $out;
}
