<?php
/**
 * Alien AI Tools Premium Theme - Starter Production Code
 */

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

define( 'ALIEN_AI_TOOLS_VERSION', wp_get_theme()->get( 'Version' ) );

/* =========================
   THEME SETUP
========================= */
function alien_ai_tools_setup() {
	load_theme_textdomain( 'alien-ai-tools', get_template_directory() . '/languages' );

	add_theme_support( 'title-tag' );
	add_theme_support( 'post-thumbnails' );
	add_theme_support( 'custom-logo' );
	add_theme_support( 'responsive-embeds' );
	add_theme_support( 'align-wide' );
	add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script' ) );

	register_nav_menus(
		array(
			'primary' => __( 'Primary Menu', 'alien-ai-tools' ),
			'footer'  => __( 'Footer Menu', 'alien-ai-tools' ),
		)
	);
}
add_action( 'after_setup_theme', 'alien_ai_tools_setup' );

/* =========================
   ASSETS
========================= */
function alien_ai_tools_enqueue_assets() {
	wp_enqueue_style( 'alien-style', get_stylesheet_uri(), array(), ALIEN_AI_TOOLS_VERSION );
	wp_enqueue_style( 'alien-premium', get_template_directory_uri() . '/assets/css/premium.css', array( 'alien-style' ), ALIEN_AI_TOOLS_VERSION );
	wp_enqueue_script( 'alien-theme', get_template_directory_uri() . '/assets/js/theme.js', array( 'jquery' ), ALIEN_AI_TOOLS_VERSION, true );

	wp_localize_script(
		'alien-theme',
		'alienAjax',
		array(
			'ajaxurl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'alien_nonce' ),
		)
	);
}
add_action( 'wp_enqueue_scripts', 'alien_ai_tools_enqueue_assets' );

/* =========================
   SIDEBAR
========================= */
function alien_ai_tools_widgets_init() {
	register_sidebar(
		array(
			'name'          => __( 'Sidebar', 'alien-ai-tools' ),
			'id'            => 'sidebar-1',
			'before_widget'  => '<section class="sidebar-widget">',
			'after_widget'   => '</section>',
			'before_title'   => '<h3 class="sw-head">',
			'after_title'    => '</h3>',
		)
	);
}
add_action( 'widgets_init', 'alien_ai_tools_widgets_init' );

/* =========================
   CUSTOM POST TYPES
========================= */
function alien_ai_tools_register_cpts() {
	register_post_type(
		'ai_tool',
		array(
			'labels' => array(
				'name'          => __( 'AI Tools', 'alien-ai-tools' ),
				'singular_name' => __( 'AI Tool', 'alien-ai-tools' ),
			),
			'public'       => true,
			'menu_icon'    => 'dashicons-superhero',
			'supports'     => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
			'has_archive'  => true,
			'rewrite'      => array( 'slug' => 'tools' ),
			'show_in_rest' => true,
		)
	);

	register_post_type(
		'comparison',
		array(
			'labels' => array(
				'name'          => __( 'Comparisons', 'alien-ai-tools' ),
				'singular_name' => __( 'Comparison', 'alien-ai-tools' ),
			),
			'public'       => true,
			'menu_icon'    => 'dashicons-randomize',
			'supports'     => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
			'has_archive'  => true,
			'rewrite'      => array( 'slug' => 'compare' ),
			'show_in_rest' => true,
		)
	);

	register_taxonomy(
		'tool_category',
		array( 'ai_tool' ),
		array(
			'labels'       => array(
				'name'          => __( 'Tool Categories', 'alien-ai-tools' ),
				'singular_name' => __( 'Tool Category', 'alien-ai-tools' ),
			),
			'hierarchical' => true,
			'show_in_rest' => true,
			'rewrite'      => array( 'slug' => 'tool-category' ),
		)
	);
}
add_action( 'init', 'alien_ai_tools_register_cpts' );

/* =========================
   TOOL META BOXES
========================= */
function alien_ai_tools_add_meta_boxes() {
	add_meta_box( 'alien_tool_meta', __( 'Tool Details', 'alien-ai-tools' ), 'alien_tool_meta_cb', 'ai_tool', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'alien_ai_tools_add_meta_boxes' );

function alien_tool_meta_cb( $post ) {
	wp_nonce_field( 'alien_save_tool', 'alien_tool_nonce' );

	$price  = get_post_meta( $post->ID, '_tool_price', true );
	$rating = get_post_meta( $post->ID, '_tool_rating', true );

	echo '<p><label for="tool_price">' . esc_html__( 'Price Model', 'alien-ai-tools' ) . '</label><br>';
	echo '<input type="text" id="tool_price" name="tool_price" value="' . esc_attr( $price ) . '" class="widefat"></p>';

	echo '<p><label for="tool_rating">' . esc_html__( 'Rating (0-5)', 'alien-ai-tools' ) . '</label><br>';
	echo '<input type="number" id="tool_rating" step="0.1" min="0" max="5" name="tool_rating" value="' . esc_attr( $rating ) . '" class="widefat"></p>';
}

function alien_ai_tools_save_ai_tool_meta( $post_id ) {
	if ( ! isset( $_POST['alien_tool_nonce'] ) ) {
		return;
	}

	$nonce = sanitize_text_field( wp_unslash( $_POST['alien_tool_nonce'] ) );
	if ( ! wp_verify_nonce( $nonce, 'alien_save_tool' ) ) {
		return;
	}

	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$price  = isset( $_POST['tool_price'] ) ? sanitize_text_field( wp_unslash( $_POST['tool_price'] ) ) : '';
	$rating = isset( $_POST['tool_rating'] ) ? floatval( wp_unslash( $_POST['tool_rating'] ) ) : 0;

	update_post_meta( $post_id, '_tool_price', $price );
	update_post_meta( $post_id, '_tool_rating', max( 0, min( 5, $rating ) ) );
}
add_action( 'save_post_ai_tool', 'alien_ai_tools_save_ai_tool_meta' );

/* =========================
   SHORTCODE GRID
========================= */
function alien_ai_tools_grid_shortcode( $atts ) {
	$q = new WP_Query(
		array(
			'post_type'      => 'ai_tool',
			'posts_per_page' => 6,
		)
	);

	ob_start();
	echo '<div class="tools-grid">';

	while ( $q->have_posts() ) {
		$q->the_post();
		$rating = get_post_meta( get_the_ID(), '_tool_rating', true );

		echo '<article class="tool-card">';
		if ( has_post_thumbnail() ) {
			the_post_thumbnail( 'medium' );
		}
		echo '<div class="tc-body">';
		echo '<h3><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></h3>';
		echo '<div class="tc-rating">⭐ ' . esc_html( $rating ) . '</div>';
		echo '</div></article>';
	}

	echo '</div>';
	wp_reset_postdata();

	return ob_get_clean();
}
add_shortcode( 'ai_tools_grid', 'alien_ai_tools_grid_shortcode' );

/* =========================
   AJAX RATING
========================= */
function alien_rate_tool() {
	check_ajax_referer( 'alien_nonce', 'nonce' );

	$post_id = absint( $_POST['post_id'] ?? 0 );
	$score   = isset( $_POST['score'] ) ? intval( $_POST['score'] ) : 0;
	$score   = max( 1, min( 5, $score ) );

	if ( ! $post_id ) {
		wp_send_json_error();
	}

	update_post_meta( $post_id, '_tool_rating', $score );
	wp_send_json_success( array( 'score' => $score ) );
}
add_action( 'wp_ajax_alien_rate_tool', 'alien_rate_tool' );
add_action( 'wp_ajax_nopriv_alien_rate_tool', 'alien_rate_tool' );

/* =========================
   SEO HELPERS
========================= */
function alien_ai_tools_title_separator() {
	return '|';
}
add_filter( 'document_title_separator', 'alien_ai_tools_title_separator' );

/* =========================
   ELEMENTOR COMPATIBILITY
========================= */
function alien_ai_tools_register_elementor_locations( $manager ) {
	if ( method_exists( $manager, 'register_all_core_location' ) ) {
		$manager->register_all_core_location();
	}
}
add_action( 'elementor/theme/register_locations', 'alien_ai_tools_register_elementor_locations' );