<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class CartAddsBySourceAbility {

	const ABILITY_NAME = 'aieo/cart-adds-by-source';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Cart adds by source', 'ai-eshop-optimizer' ),
				'description'         => __( 'Count add-to-cart events grouped by `source` (archive, single_product, product_needs, sticky_atc, sidecart_*, …) for a period. The starting point for any attribution conversation.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => self::input_schema(),
				'output_schema'       => array( 'type' => 'object' ),
				'execute_callback'    => array( __CLASS__, 'execute' ),
				'permission_callback' => array( __CLASS__, 'permission_check' ),
				'meta'                => array(
					'annotations'  => array(
						'readonly'   => true,
						'idempotent' => true,
					),
					'show_in_rest' => true,
				),
			)
		);
	}

	public static function permission_check( $input = null ) {
		unset( $input );
		return current_user_can( 'manage_woocommerce' );
	}

	private static function input_schema() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'period' => array(
					'type'        => 'string',
					'default'     => 'last_7_days',
					'enum'        => PeriodHelper::ALLOWED,
				),
			),
		);
	}

	public static function execute( $input ) {
		global $wpdb;
		$input  = is_array( $input ) ? $input : array();
		$period = PeriodHelper::resolve( $input['period'] ?? 'last_7_days' );
		$table  = $wpdb->prefix . 'aieo_addcart_events';

		$exists = (int) $wpdb->get_var( $wpdb->prepare(
			"SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s",
			$table
		) );
		if ( ! $exists ) {
			return array( 'period' => $period, 'rows' => array(), 'note' => __( 'wp_aieo_addcart_events not installed.', 'ai-eshop-optimizer' ) );
		}

		
		$rows = $wpdb->get_results( $wpdb->prepare(
			"SELECT source,
			        COUNT(*)                                                       AS cart_adds,
			        SUM(quantity)                                                  AS units,
			        SUM(unit_price * quantity)                                     AS revenue,
			        COUNT(DISTINCT session_id)                                     AS sessions,
			        SUM(order_id > 0)                                              AS converted,
			        COUNT(DISTINCT product_id)                                     AS distinct_products
			   FROM {$table}
			  WHERE ts_added BETWEEN %s AND %s
			  GROUP BY source
			  ORDER BY cart_adds DESC",
			$period['since'], $period['until']
		), ARRAY_A );

		$out = array();
		foreach ( (array) $rows as $r ) {
			$cart_adds = (int) $r['cart_adds'];
			$converted = (int) $r['converted'];
			$out[] = array(
				'source'            => (string) $r['source'],
				'cart_adds'         => $cart_adds,
				'units'             => (int) $r['units'],
				'revenue'           => (float) $r['revenue'],
				'sessions'          => (int) $r['sessions'],
				'distinct_products' => (int) $r['distinct_products'],
				'converted_adds'    => $converted,
				'conversion_rate'   => $cart_adds > 0 ? round( $converted / $cart_adds, 4 ) : 0.0,
			);
		}
		return array(
			'period' => $period,
			'rows'   => $out,
		);
	}
}
