<?php
/**
 * Foliora theme bootstrap.
 *
 * @package Foliora
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'FOLIORA_VERSION', '1.0.6' );

require_once get_template_directory() . '/inc/setup.php';
require_once get_template_directory() . '/inc/assets.php';
require_once get_template_directory() . '/inc/cross-sells.php';
require_once get_template_directory() . '/inc/product-copy.php';
require_once get_template_directory() . '/inc/cart-drawer.php';
require_once get_template_directory() . '/inc/woocommerce.php';
require_once get_template_directory() . '/inc/newsletter.php';

/**
 * Theme image URI.
 *
 * @param string $file Filename inside assets/images.
 * @return string
 */
function foliora_image_uri( $file ) {
	return get_theme_file_uri( 'assets/images/' . ltrim( $file, '/' ) );
}

/**
 * Shop URL that works before WooCommerce pages exist.
 *
 * @return string
 */
function foliora_shop_url() {
	if ( function_exists( 'wc_get_page_permalink' ) ) {
		$url = wc_get_page_permalink( 'shop' );
		if ( $url && ! is_wp_error( $url ) ) {
			return $url;
		}
	}
	return home_url( '/shop/' );
}

/**
 * Product permalink by SKU, or a fallback hash/shop URL.
 *
 * @param string $sku     Product SKU.
 * @param string $fallback Fallback URL.
 * @return string
 */
function foliora_product_url( $sku, $fallback = '' ) {
	if ( function_exists( 'wc_get_product_id_by_sku' ) ) {
		$id = wc_get_product_id_by_sku( $sku );
		if ( $id ) {
			$link = get_permalink( $id );
			if ( $link ) {
				return $link;
			}
		}
	}
	return $fallback ? $fallback : foliora_shop_url();
}

/**
 * Category URL or shop fallback.
 *
 * @param string $slug Category slug.
 * @return string
 */
function foliora_cat_url( $slug ) {
	$term = get_term_by( 'slug', $slug, 'product_cat' );
	if ( $term && ! is_wp_error( $term ) ) {
		$link = get_term_link( $term );
		if ( ! is_wp_error( $link ) ) {
			return $link;
		}
	}
	return foliora_shop_url();
}

/**
 * Account URL.
 *
 * @return string
 */
function foliora_account_url() {
	if ( function_exists( 'wc_get_page_permalink' ) ) {
		$url = wc_get_page_permalink( 'myaccount' );
		if ( $url && ! is_wp_error( $url ) ) {
			return $url;
		}
	}
	return home_url( '/my-account/' );
}

/**
 * Cart count for badge.
 *
 * @return int
 */
function foliora_cart_count() {
	if ( function_exists( 'WC' ) && WC()->cart ) {
		return (int) WC()->cart->get_cart_contents_count();
	}
	return 0;
}

/**
 * Format a money number as $X without WC.
 *
 * @param float|string $amount Amount.
 * @return string
 */
function foliora_money( $amount ) {
	return '$' . number_format( (float) $amount, 0 );
}

/**
 * WooCommerce is queryable.
 *
 * @return bool
 */
function foliora_wc_ready() {
	return class_exists( 'WooCommerce' );
}
