<?php
/**
 * WP-CLI commands for IGIT Related Posts With Thumb.
 *
 * Registered only when WP-CLI is active. Provides three sub-commands:
 *
 *   wp igit-rpwt flush-cache [--post-id=<id>]
 *   wp igit-rpwt stats        [--days=<n>]    [--limit=<n>]
 *   wp igit-rpwt create-table
 *
 * @package IGIT_RPWT
 */

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

/**
 * Manage the IGIT Related Posts With Thumb plugin from the command line.
 */
class IGIT_RPWT_CLI extends WP_CLI_Command {

	// ── flush-cache ──────────────────────────────────────────────────────────

	/**
	 * Flush the related-posts transient cache.
	 *
	 * Clears all cached related-posts results, or just the cache for a
	 * single post when --post-id is supplied.
	 *
	 * ## OPTIONS
	 *
	 * [--post-id=<id>]
	 * : Flush only the cache for this post ID. Omit to flush everything.
	 *
	 * ## EXAMPLES
	 *
	 *     # Flush all caches
	 *     wp igit-rpwt flush-cache
	 *
	 *     # Flush a single post cache
	 *     wp igit-rpwt flush-cache --post-id=42
	 *
	 * @subcommand flush-cache
	 *
	 * @param array $args       Positional arguments (unused).
	 * @param array $assoc_args Named arguments.
	 */
	public function flush_cache( $args, $assoc_args ) {
		$post_id = isset( $assoc_args['post-id'] ) ? absint( $assoc_args['post-id'] ) : 0;

		if ( $post_id ) {
			IGIT_RPWT_Query::flush_post_cache( $post_id );
			WP_CLI::success( sprintf( 'Cache cleared for post #%d.', $post_id ) );
		} else {
			IGIT_RPWT_Query::flush_all_cache();
			WP_CLI::success( 'All related-posts caches cleared.' );
		}
	}

	// ── stats ────────────────────────────────────────────────────────────────

	/**
	 * Display click-tracking statistics.
	 *
	 * Requires the Pro add-on and "Enable Click Tracking" in plugin settings.
	 * Results are printed as a formatted table.
	 *
	 * ## OPTIONS
	 *
	 * [--days=<n>]
	 * : How many days back to include. Default: 30. Use 0 for all time.
	 *
	 * [--limit=<n>]
	 * : Maximum number of posts to list. Default: 20.
	 *
	 * ## EXAMPLES
	 *
	 *     # Show top posts for the last 30 days
	 *     wp igit-rpwt stats
	 *
	 *     # Last 7 days, top 10
	 *     wp igit-rpwt stats --days=7 --limit=10
	 *
	 *     # All-time stats
	 *     wp igit-rpwt stats --days=0
	 *
	 * @subcommand stats
	 *
	 * @param array $args       Positional arguments (unused).
	 * @param array $assoc_args Named arguments.
	 */
	public function stats( $args, $assoc_args ) {
		if ( ! class_exists( 'IGIT_RPWT_Analytics' ) ) {
			WP_CLI::error( 'Analytics requires the IGIT Related Posts Pro add-on to be installed and active.' );
		}

		if ( ! IGIT_RPWT_Settings::get( 'enable_click_tracking' ) ) {
			WP_CLI::warning( 'Click tracking is currently disabled in plugin settings. Data may be absent.' );
		}

		$days  = isset( $assoc_args['days'] )  ? max( 0, absint( $assoc_args['days'] ) )  : 30;
		$limit = isset( $assoc_args['limit'] ) ? max( 1, absint( $assoc_args['limit'] ) ) : 20;

		$total     = IGIT_RPWT_Analytics::get_total_clicks( $days );
		$top_posts = IGIT_RPWT_Analytics::get_top_posts( $days, $limit );

		$period_label = $days > 0
			? sprintf( 'last %d day(s)', $days )
			: 'all time';

		WP_CLI::log( sprintf( 'Total clicks (%s): %s', $period_label, number_format( $total ) ) );
		WP_CLI::log( '' );

		if ( empty( $top_posts ) ) {
			WP_CLI::log( 'No click data found for the selected period.' );
			return;
		}

		// Build table rows.
		$rows = array();
		foreach ( $top_posts as $row ) {
			$rows[] = array(
				'Post ID' => $row['target_post_id'],
				'Title'   => get_the_title( (int) $row['target_post_id'] ),
				'URL'     => get_permalink( (int) $row['target_post_id'] ),
				'Clicks'  => number_format( (int) $row['total_clicks'] ),
			);
		}

		WP_CLI\Utils\format_items( 'table', $rows, array( 'Post ID', 'Title', 'URL', 'Clicks' ) );
	}

	// ── create-table ─────────────────────────────────────────────────────────

	/**
	 * Create (or verify/upgrade) the click-tracking database table.
	 *
	 * Uses dbDelta so it is safe to run on an existing installation —
	 * missing columns will be added, no existing data is removed.
	 *
	 * ## EXAMPLES
	 *
	 *     wp igit-rpwt create-table
	 *
	 * @subcommand create-table
	 *
	 * @param array $args       Positional arguments (unused).
	 * @param array $assoc_args Named arguments (unused).
	 */
	public function create_table( $args, $assoc_args ) {
		if ( ! class_exists( 'IGIT_RPWT_Analytics' ) ) {
			WP_CLI::error( 'Analytics requires the IGIT Related Posts Pro add-on to be installed and active.' );
		}
		IGIT_RPWT_Analytics::create_table();
		WP_CLI::success( 'Analytics table created / verified.' );
	}
}
