<?php
/**
 * File Path: includes/admin/class-mbs-buy-link-analytics.php
 *
 * Buy-Link Analytics Admin Report -- INSIGHTS-1
 *
 * Registers "My Books > Buy Link Analytics" sub-menu page and renders
 * a report table: Book Title | Retailer | Clicks (all time) | Clicks (30d) | Last Click.
 * Requires manage_options capability. PRO-gated: FREE tier sees upgrade CTA.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

/**
 * Class MBS_Buy_Link_Analytics
 *
 * @since 1.0.0
 */
// phpcs:disable WordPress.Security.NonceVerification -- nonce verified in parent class verify_save() / check_admin_referer() before $_POST access; PHPCS cannot trace cross-method nonce verification
class MBS_Buy_Link_Analytics {

	/**
	 * Register the admin sub-menu page.
	 *
	 * @return void
	 */
	public static function register(): void {
		add_action( 'admin_menu', array( static::class, 'add_menu' ) );
	}

	/**
	 * Add the sub-menu page under the MBS parent.
	 *
	 * @return void
	 */
	public static function add_menu(): void {
		// Removed from sidebar -- accessible via dashboard quick-action tile.
		add_submenu_page(
			null,
			__( 'Buy Link Analytics', 'my-book-showroom' ),
			__( 'Buy Link Analytics', 'my-book-showroom' ),
			'manage_options',
			'mbs-buy-link-analytics',
			array( static::class, 'render_page' )
		);
	}

	/**
	 * Render the analytics report page.
	 *
	 * @return void
	 */
	public static function render_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to view this page.', 'my-book-showroom' ) );
		}
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Buy Link Analytics', 'my-book-showroom' ); ?></h1>

			<?php if ( ! mbs_is_pro() ) : ?>
			<div class="notice notice-info">
				<p>
					<?php esc_html_e( 'Buy Link Analytics click recording requires a PRO license. Upgrade to track clicks and view reports.', 'my-book-showroom' ); ?>
				</p>
			</div>
			<?php return; endif; ?>

			<?php
			// Date range filter.
			$range = isset( $_GET['mbs_range'] ) ? sanitize_key( wp_unslash( $_GET['mbs_range'] ) ) : 'all';
			$allowed_ranges = array( 'all', '30d', '7d' );
			if ( ! in_array( $range, $allowed_ranges, true ) ) {
				$range = 'all';
			}
			$rows = self::get_report_data( $range );
			?>
			<form method="get" style="margin-bottom:1rem;">
				<input type="hidden" name="page" value="mbs-buy-link-analytics">
				<label for="mbs_range"><?php esc_html_e( 'Date range:', 'my-book-showroom' ); ?></label>
				<select id="mbs_range" name="mbs_range">
					<option value="all"<?php selected( $range, 'all' ); ?>><?php esc_html_e( 'All time', 'my-book-showroom' ); ?></option>
					<option value="30d"<?php selected( $range, '30d' ); ?>><?php esc_html_e( 'Last 30 days', 'my-book-showroom' ); ?></option>
					<option value="7d"<?php selected( $range, '7d' ); ?>><?php esc_html_e( 'Last 7 days', 'my-book-showroom' ); ?></option>
				</select>
				<button type="submit" class="button"><?php esc_html_e( 'Filter', 'my-book-showroom' ); ?></button>
			</form>

			<?php if ( empty( $rows ) ) : ?>
			<p><?php esc_html_e( 'No click data found for the selected range.', 'my-book-showroom' ); ?></p>
			<?php else : ?>
			<table class="wp-list-table widefat fixed striped">
				<thead>
					<tr>
						<th><?php esc_html_e( 'Book', 'my-book-showroom' ); ?></th>
						<th><?php esc_html_e( 'Retailer', 'my-book-showroom' ); ?></th>
						<th><?php esc_html_e( 'Clicks (all time)', 'my-book-showroom' ); ?></th>
						<th><?php esc_html_e( 'Clicks (30 days)', 'my-book-showroom' ); ?></th>
						<th><?php esc_html_e( 'Last Click', 'my-book-showroom' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $rows as $row ) :
						$title = $row->post_id ? get_the_title( (int) $row->post_id ) : '—';
						$edit  = $row->post_id ? get_edit_post_link( (int) $row->post_id ) : '';
					?>
					<tr>
						<td>
							<?php if ( $edit ) : ?>
								<a href="<?php echo esc_url( $edit ); ?>"><?php echo esc_html( $title ); ?></a>
							<?php else : ?>
								<?php echo esc_html( $title ); ?>
							<?php endif; ?>
						</td>
						<td><?php echo esc_html( $row->retailer_key ?: '—' ); ?></td>
						<td><?php echo (int) $row->total_clicks; ?></td>
						<td><?php echo (int) $row->clicks_30d; ?></td>
						<td><?php echo esc_html( $row->last_click ?? '—' ); ?></td>
					</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Query click data grouped by link, with all-time and 30-day counts.
	 *
	 * @param string $range 'all' | '30d' | '7d'.
	 * @return object[]
	 */
	private static function get_report_data( string $range ): array {
		return MBS_Buy_Link_Clicks_DAO::get_report_data( $range );
	}
}
