<?php
/**
 * Nebula Ocean enhancements.
 * Copyright storytimeandconfession.
 *
 * @package Nebula Ocean
 */

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

function nebula_ocean_has_seo_plugin() {
	return defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'AIOSEO_VERSION' ) || class_exists( 'WPSEO_Frontend' ) || class_exists( 'RankMath' );
}

function nebula_ocean_excerpt_text( $post_id = 0, $words = 28 ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	$post = get_post( $post_id );
	if ( ! $post ) {
		return get_bloginfo( 'description' );
	}
	$text = has_excerpt( $post_id ) ? get_the_excerpt( $post_id ) : $post->post_content;
	$text = wp_strip_all_tags( strip_shortcodes( $text ) );
	$text = preg_replace( '/\s+/', ' ', $text );
	return wp_trim_words( $text, $words, '' );
}

function nebula_ocean_meta_description() {
	if ( is_singular() ) {
		return nebula_ocean_excerpt_text( get_the_ID(), 28 );
	}
	if ( is_category() || is_tag() || is_tax() ) {
		$term = get_queried_object();
		if ( $term && ! empty( $term->description ) ) {
			return wp_strip_all_tags( $term->description );
		}
		return sprintf( 'Explore %s stories on The Confessions, featuring emotional secrets, dark memories, betrayal, pain, survival, and truth.', single_term_title( '', false ) );
	}
	if ( is_search() ) {
		return 'Search emotional stories, dark secrets, painful memories, betrayal, love, guilt, and survival on The Confessions.';
	}
	return 'Read The Confessions on storytimeandconfessions, a dark emotional universe of stories, secrets, guilt, betrayal, pain, love, shame, and survival.';
}

function nebula_ocean_social_image() {
	if ( is_singular() && has_post_thumbnail() ) {
		$url = get_the_post_thumbnail_url( get_the_ID(), 'full' );
		if ( $url ) {
			return $url;
		}
	}
	return get_template_directory_uri() . '/images/nebula-ocean-bg.jpg';
}

function nebula_ocean_schema() {
	$schema = array(
		'@context' => 'https://schema.org',
		'@type'    => is_singular( 'post' ) ? 'BlogPosting' : 'WebSite',
		'name'     => get_bloginfo( 'name' ),
		'url'      => home_url( '/' ),
	);
	if ( is_singular() ) {
		$schema['headline']      = get_the_title();
		$schema['description']   = nebula_ocean_meta_description();
		$schema['mainEntityOfPage'] = get_permalink();
		$schema['datePublished'] = get_the_date( DATE_W3C );
		$schema['dateModified']  = get_the_modified_date( DATE_W3C );
		$schema['image']         = nebula_ocean_social_image();
		$schema['author']        = array( '@type' => 'Person', 'name' => get_the_author_meta( 'display_name' ) );
		$schema['publisher']     = array(
			'@type' => 'Organization',
			'name'  => 'storytimeandconfession',
			'url'   => home_url( '/' ),
		);
	} else {
		$schema['potentialAction'] = array(
			'@type'       => 'SearchAction',
			'target'      => home_url( '/?s={search_term_string}' ),
			'query-input' => 'required name=search_term_string',
		);
	}
	return $schema;
}

function nebula_ocean_head_seo() {
	if ( nebula_ocean_has_seo_plugin() ) {
		return;
	}
	$description = esc_attr( nebula_ocean_meta_description() );
	$title       = esc_attr( wp_get_document_title() );
	$url         = esc_url( is_singular() ? get_permalink() : home_url( add_query_arg( null, null ) ) );
	$image       = esc_url( nebula_ocean_social_image() );
	$type        = is_singular( 'post' ) ? 'article' : 'website';
	echo "\n" . '<meta name="description" content="' . $description . '">' . "\n";
	echo '<meta property="og:title" content="' . $title . '">' . "\n";
	echo '<meta property="og:description" content="' . $description . '">' . "\n";
	echo '<meta property="og:image" content="' . $image . '">' . "\n";
	echo '<meta property="og:url" content="' . $url . '">' . "\n";
	echo '<meta property="og:type" content="' . esc_attr( $type ) . '">' . "\n";
	echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
	echo '<meta name="twitter:title" content="' . $title . '">' . "\n";
	echo '<meta name="twitter:description" content="' . $description . '">' . "\n";
	echo '<meta name="twitter:image" content="' . $image . '">' . "\n";
	echo '<script type="application/ld+json">' . wp_json_encode( nebula_ocean_schema(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . '</script>' . "\n";
}
add_action( 'wp_head', 'nebula_ocean_head_seo', 4 );

function nebula_ocean_document_title_parts( $parts ) {
	if ( is_front_page() || is_home() ) {
		$parts['title'] = 'The Confessions | Real Stories, Dark Secrets, Emotional Truths';
	} elseif ( is_singular() ) {
		$parts['site'] = 'The Confessions';
	} elseif ( is_category() || is_tag() || is_tax() ) {
		$parts['title'] = single_term_title( '', false ) . ' Stories';
		$parts['site']  = 'The Confessions';
	}
	return $parts;
}
add_filter( 'document_title_parts', 'nebula_ocean_document_title_parts' );

function nebula_ocean_enqueue_layer() {
	wp_enqueue_style( 'nebula-ocean-layer', get_template_directory_uri() . '/assets/css/nebula-ocean.css', array(), filemtime( get_template_directory() . '/assets/css/nebula-ocean.css' ) );
	wp_enqueue_script( 'nebula-ocean-layer', get_template_directory_uri() . '/assets/js/nebula-ocean.js', array(), filemtime( get_template_directory() . '/assets/js/nebula-ocean.js' ), true );
}
add_action( 'wp_enqueue_scripts', 'nebula_ocean_enqueue_layer', 99 );

function nebula_ocean_extra_sidebars() {
	$sidebars = array(
		'nebula-story-sidebar' => 'Nebula Story Sidebar',
		'nebula-home-sidebar'  => 'Nebula Homepage Sidebar',
		'nebula-mobile-sidebar'=> 'Nebula Mobile Sidebar',
		'nebula-ad-sidebar'    => 'Nebula Ad Sidebar',
	);
	foreach ( $sidebars as $id => $name ) {
		register_sidebar( array(
			'name'          => esc_html__( $name, 'nebula-ocean' ),
			'id'            => $id,
			'description'   => esc_html__( 'Nebula Ocean additional responsive sidebar area.', 'nebula-ocean' ),
			'before_widget' => '<aside id="%1$s" class="widget %2$s">',
			'after_widget'  => '</aside>',
			'before_title'  => '<h3 class="widget-title">',
			'after_title'   => '</h3>',
		) );
	}
}
add_action( 'widgets_init', 'nebula_ocean_extra_sidebars', 20 );

function nebula_ocean_count_post_views() {
	if ( ! is_single() ) {
		return;
	}
	$post_id = get_the_ID();
	$count   = (int) get_post_meta( $post_id, '_nebula_views', true );
	update_post_meta( $post_id, '_nebula_views', $count + 1 );
}
add_action( 'wp', 'nebula_ocean_count_post_views' );

function nebula_ocean_card_markup( $post_id ) {
	$title = get_the_title( $post_id );
	$link  = get_permalink( $post_id );
	$img   = get_the_post_thumbnail( $post_id, 'medium_large', array( 'loading' => 'lazy', 'decoding' => 'async', 'alt' => $title . ' - The Confessions' ) );
	if ( ! $img ) {
		$img = '<img src="' . esc_url( get_template_directory_uri() . '/images/nebula-ocean-bg.jpg' ) . '" loading="lazy" decoding="async" alt="' . esc_attr( $title . ' - The Confessions' ) . '">';
	}
	return '<article class="stc-card">' . $img . '<div class="stc-card-body"><h3><a href="' . esc_url( $link ) . '">' . esc_html( $title ) . '</a></h3><p>' . esc_html( nebula_ocean_excerpt_text( $post_id, 18 ) ) . '</p><a class="stc-btn" href="' . esc_url( $link ) . '">Read Story</a></div></article>';
}

function nebula_ocean_posts_grid( $args, $columns = 3, $carousel = false ) {
	$q = new WP_Query( $args );
	if ( ! $q->have_posts() ) {
		return '<p>No stories found.</p>';
	}
	$class = $carousel ? 'stc-carousel' : 'stc-grid';
	$out = '<div class="' . esc_attr( $class ) . '" style="--cols:' . absint( $columns ) . '">';
	while ( $q->have_posts() ) {
		$q->the_post();
		$out .= nebula_ocean_card_markup( get_the_ID() );
	}
	wp_reset_postdata();
	$out .= '</div>';
	return $out;
}

function nebula_ocean_shortcode_latest( $atts ) {
	$atts = shortcode_atts( array( 'count' => 6, 'columns' => 3 ), $atts );
	return nebula_ocean_posts_grid( array( 'post_type' => 'post', 'posts_per_page' => absint( $atts['count'] ), 'ignore_sticky_posts' => true ), absint( $atts['columns'] ) );
}
add_shortcode( 'stc_latest_posts', 'nebula_ocean_shortcode_latest' );

function nebula_ocean_shortcode_category( $atts ) {
	$atts = shortcode_atts( array( 'category' => '', 'count' => 6, 'columns' => 3 ), $atts );
	return nebula_ocean_posts_grid( array( 'post_type' => 'post', 'posts_per_page' => absint( $atts['count'] ), 'category_name' => sanitize_title( $atts['category'] ), 'ignore_sticky_posts' => true ), absint( $atts['columns'] ) );
}
add_shortcode( 'stc_category_posts', 'nebula_ocean_shortcode_category' );

function nebula_ocean_shortcode_story_grid( $atts ) {
	$atts = shortcode_atts( array( 'count' => 12, 'columns' => 3, 'order' => 'latest' ), $atts );
	$args = array( 'post_type' => 'post', 'posts_per_page' => absint( $atts['count'] ), 'ignore_sticky_posts' => true );
	if ( 'random' === $atts['order'] ) { $args['orderby'] = 'rand'; }
	if ( 'popular' === $atts['order'] ) { $args['meta_key'] = '_nebula_views'; $args['orderby'] = 'meta_value_num'; $args['order'] = 'DESC'; }
	if ( 'commented' === $atts['order'] ) { $args['orderby'] = 'comment_count'; $args['order'] = 'DESC'; }
	return nebula_ocean_posts_grid( $args, absint( $atts['columns'] ) );
}
add_shortcode( 'stc_story_grid', 'nebula_ocean_shortcode_story_grid' );

function nebula_ocean_shortcode_trending( $atts ) {
	$atts = shortcode_atts( array( 'count' => 6, 'columns' => 3, 'days' => 30 ), $atts );
	return nebula_ocean_posts_grid( array( 'post_type' => 'post', 'posts_per_page' => absint( $atts['count'] ), 'meta_key' => '_nebula_views', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'date_query' => array( array( 'after' => absint( $atts['days'] ) . ' days ago' ) ) ), absint( $atts['columns'] ) );
}
add_shortcode( 'stc_trending_posts', 'nebula_ocean_shortcode_trending' );

function nebula_ocean_shortcode_carousel( $atts ) {
	$atts = shortcode_atts( array( 'count' => 8, 'category' => '' ), $atts );
	return nebula_ocean_posts_grid( array( 'post_type' => 'post', 'posts_per_page' => absint( $atts['count'] ), 'category_name' => sanitize_title( $atts['category'] ), 'ignore_sticky_posts' => true ), 3, true );
}
add_shortcode( 'stc_story_carousel', 'nebula_ocean_shortcode_carousel' );

function nebula_ocean_shortcode_featured( $atts ) {
	$atts = shortcode_atts( array( 'id' => 0 ), $atts );
	$post_id = absint( $atts['id'] );
	if ( ! $post_id ) { $posts = get_posts( array( 'posts_per_page' => 1, 'post_type' => 'post' ) ); $post_id = $posts ? $posts[0]->ID : 0; }
	if ( ! $post_id ) { return ''; }
	$img = get_the_post_thumbnail( $post_id, 'large', array( 'loading' => 'lazy', 'decoding' => 'async', 'alt' => get_the_title( $post_id ) . ' - The Confessions' ) );
	return '<section class="stc-hero-card"><div><span class="stc-badge">Featured Confession</span><h2><a href="' . esc_url( get_permalink( $post_id ) ) . '">' . esc_html( get_the_title( $post_id ) ) . '</a></h2><p>' . esc_html( nebula_ocean_excerpt_text( $post_id, 32 ) ) . '</p><a class="stc-btn" href="' . esc_url( get_permalink( $post_id ) ) . '">Read Featured Story</a></div><div>' . $img . '</div></section>';
}
add_shortcode( 'stc_featured_post', 'nebula_ocean_shortcode_featured' );

function nebula_ocean_shortcode_quote( $atts ) { $a=shortcode_atts(array('text'=>''),$atts); return '<blockquote class="stc-quote">“' . esc_html($a['text']) . '”</blockquote>'; }
add_shortcode( 'stc_quote', 'nebula_ocean_shortcode_quote' );
function nebula_ocean_shortcode_quote_share( $atts ) { $a=shortcode_atts(array('text'=>''),$atts); $text=esc_attr($a['text']); return '<div class="stc-quote">“'.esc_html($a['text']).'”<div class="stc-share"><a target="_blank" rel="noopener" href="https://twitter.com/intent/tweet?text='.rawurlencode($a['text']).'&url='.esc_url(get_permalink()).'">Share quote</a><button class="stc-copy-link" data-label="Copy quote" data-stc-copy="'.$text.'">Copy quote</button></div></div>'; }
add_shortcode( 'stc_quote_share', 'nebula_ocean_shortcode_quote_share' );
function nebula_ocean_shortcode_warning( $atts ) { $a=shortcode_atts(array('text'=>''),$atts); return '<div class="stc-warning"><strong>Reader warning:</strong> '.esc_html($a['text']).'</div>'; }
add_shortcode( 'stc_warning', 'nebula_ocean_shortcode_warning' );
function nebula_ocean_shortcode_read_time() { $words=str_word_count(wp_strip_all_tags(get_post_field('post_content',get_the_ID()))); return '<span class="stc-read-time">Estimated reading time: '.max(1,ceil($words/220)).' minutes</span>'; }
add_shortcode( 'stc_read_time', 'nebula_ocean_shortcode_read_time' );
function nebula_ocean_shortcode_related( $atts ) { $a=shortcode_atts(array('count'=>4),$atts); $cats=wp_get_post_categories(get_the_ID()); return nebula_ocean_posts_grid(array('post_type'=>'post','posts_per_page'=>absint($a['count']),'post__not_in'=>array(get_the_ID()),'category__in'=>$cats,'ignore_sticky_posts'=>true),2); }
add_shortcode( 'stc_related_posts', 'nebula_ocean_shortcode_related' );
function nebula_ocean_shortcode_next() { $p=get_next_post(); return $p?'<a class="stc-btn" href="'.esc_url(get_permalink($p)).'">Next Confession: '.esc_html(get_the_title($p)).'</a>':''; }
add_shortcode( 'stc_next_confession', 'nebula_ocean_shortcode_next' );
function nebula_ocean_shortcode_previous() { $p=get_previous_post(); return $p?'<a class="stc-btn" href="'.esc_url(get_permalink($p)).'">Previous Confession: '.esc_html(get_the_title($p)).'</a>':''; }
add_shortcode( 'stc_previous_confession', 'nebula_ocean_shortcode_previous' );
function nebula_ocean_shortcode_random( $atts ) { $a=shortcode_atts(array('text'=>'Take me to a random confession'),$atts); $p=get_posts(array('post_type'=>'post','posts_per_page'=>1,'orderby'=>'rand')); return $p?'<a class="stc-btn" href="'.esc_url(get_permalink($p[0])).'">'.esc_html($a['text']).'</a>':''; }
add_shortcode( 'stc_random_confession', 'nebula_ocean_shortcode_random' );

function nebula_ocean_shortcode_share() {
	$url=rawurlencode(get_permalink()?:home_url('/')); $title=rawurlencode(get_the_title()?:get_bloginfo('name'));
	$links=array('Facebook'=>'https://www.facebook.com/sharer/sharer.php?u='.$url,'WhatsApp'=>'https://api.whatsapp.com/send?text='.$title.'%20'.$url,'Telegram'=>'https://t.me/share/url?url='.$url.'&text='.$title,'X'=>'https://twitter.com/intent/tweet?url='.$url.'&text='.$title,'LinkedIn'=>'https://www.linkedin.com/shareArticle?mini=true&url='.$url.'&title='.$title,'Reddit'=>'https://www.reddit.com/submit?url='.$url.'&title='.$title);
	$out='<div class="stc-share">'; foreach($links as $name=>$href){$out.='<a href="'.esc_url($href).'" target="_blank" rel="noopener">'.esc_html($name).'</a>';}
	$out.='<button class="stc-copy-link" data-label="Copy link" data-stc-copy="'.esc_url(get_permalink()).'">Copy link</button></div>'; return $out;
}
add_shortcode( 'stc_share_buttons', 'nebula_ocean_shortcode_share' );
function nebula_ocean_shortcode_copy_link( $atts ) { $a=shortcode_atts(array('text'=>'Copy this confession'),$atts); return '<button class="stc-copy-link" data-label="'.esc_attr($a['text']).'" data-stc-copy="'.esc_url(get_permalink()).'">'.esc_html($a['text']).'</button>'; }
add_shortcode( 'stc_copy_link', 'nebula_ocean_shortcode_copy_link' );
function nebula_ocean_shortcode_newsletter( $atts ) { $a=shortcode_atts(array('title'=>'Keep updated with stories!','subtitle'=>'Get the newest confessions before they disappear into silence.'),$atts); return '<section class="stc-newsletter"><h2>'.esc_html($a['title']).'</h2><p>'.esc_html($a['subtitle']).'</p><form method="post"><input type="email" name="nebula_email" placeholder="Your email address" aria-label="Email address"><button type="submit">Subscribe</button></form></section>'; }
add_shortcode( 'stc_newsletter', 'nebula_ocean_shortcode_newsletter' );
function nebula_ocean_shortcode_author() { return '<div class="stc-author-box"><h3>'.esc_html(get_the_author()).'</h3><p>'.esc_html(get_the_author_meta('description')).'</p><a class="stc-btn" href="'.esc_url(get_author_posts_url(get_the_author_meta('ID'))).'">More from this author</a></div>'; }
add_shortcode( 'stc_author_box', 'nebula_ocean_shortcode_author' );
function nebula_ocean_shortcode_ad( $atts, $content='' ) { return '<div class="stc-ad-slot">'.do_shortcode($content).'</div>'; }
add_shortcode( 'stc_ad_slot', 'nebula_ocean_shortcode_ad' );
function nebula_ocean_shortcode_cta( $atts ) { $a=shortcode_atts(array('title'=>'Have a confession?','button'=>'Submit Your Story','url'=>'/submit-story'),$atts); return '<section class="stc-cta"><h2>'.esc_html($a['title']).'</h2><a class="stc-btn" href="'.esc_url($a['url']).'">'.esc_html($a['button']).'</a></section>'; }
add_shortcode( 'stc_cta', 'nebula_ocean_shortcode_cta' );
function nebula_ocean_shortcode_divider() { return '<div class="stc-divider" aria-hidden="true"></div>'; }
add_shortcode( 'stc_divider', 'nebula_ocean_shortcode_divider' );
function nebula_ocean_shortcode_badge( $atts ) { $a=shortcode_atts(array('mood'=>'Confession'),$atts); return '<span class="stc-badge">'.esc_html($a['mood']).'</span>'; }
add_shortcode( 'stc_mood_badge', 'nebula_ocean_shortcode_badge' );
function nebula_ocean_shortcode_confession_box( $atts ) { $a=shortcode_atts(array('title'=>'Confession','text'=>''),$atts); return '<div class="stc-confession-box"><h3>'.esc_html($a['title']).'</h3><p>'.esc_html($a['text']).'</p></div>'; }
add_shortcode( 'stc_confession_box', 'nebula_ocean_shortcode_confession_box' );
function nebula_ocean_shortcode_timeline( $atts, $content='' ) { return '<div class="stc-timeline">'.do_shortcode($content).'</div>'; }
add_shortcode( 'stc_timeline', 'nebula_ocean_shortcode_timeline' );
function nebula_ocean_shortcode_timeline_item( $atts ) { $a=shortcode_atts(array('title'=>'','text'=>''),$atts); return '<div class="stc-timeline-item"><h3>'.esc_html($a['title']).'</h3><p>'.esc_html($a['text']).'</p></div>'; }
add_shortcode( 'stc_timeline_item', 'nebula_ocean_shortcode_timeline_item' );
function nebula_ocean_shortcode_faq( $atts, $content='' ) { return '<div class="stc-faq">'.do_shortcode($content).'</div>'; }
add_shortcode( 'stc_faq', 'nebula_ocean_shortcode_faq' );
function nebula_ocean_shortcode_faq_item( $atts ) { $a=shortcode_atts(array('question'=>'','answer'=>''),$atts); return '<details class="stc-faq-item"><summary>'.esc_html($a['question']).'</summary><p>'.esc_html($a['answer']).'</p></details>'; }
add_shortcode( 'stc_faq_item', 'nebula_ocean_shortcode_faq_item' );
function nebula_ocean_shortcode_toc() { return '<nav class="stc-toc"><strong>Contents</strong><p>Use H2 and H3 headings in the editor. Most SEO plugins and browsers can jump to those sections automatically.</p></nav>'; }
add_shortcode( 'stc_toc', 'nebula_ocean_shortcode_toc' );


function nebula_ocean_attachment_alt_fallback( $attr, $attachment, $size ) {
	if ( empty( $attr['alt'] ) ) {
		$parent = get_post_parent( $attachment->ID );
		$attr['alt'] = $parent ? get_the_title( $parent ) . ' - The Confessions' : get_the_title( $attachment->ID ) . ' - The Confessions';
	}
	$attr['loading'] = isset( $attr['loading'] ) ? $attr['loading'] : 'lazy';
	$attr['decoding'] = isset( $attr['decoding'] ) ? $attr['decoding'] : 'async';
	return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'nebula_ocean_attachment_alt_fallback', 10, 3 );
