<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class AbandonedProductOffersAbility {

	const ABILITY_NAME = 'aieo/abandoned-product-offers';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Abandoned-product offer ideas', 'ai-eshop-optimizer' ),
				'description'         => __( 'For the most-abandoned products (lost demand), returns per product: how much € + how many units/carts were lost in carts that did NOT convert, how many units/orders DID sell through checkout, and a success_rate (converted ÷ all checkout carts it appeared in, since the first captured record). Adds the current price, the shop gross margin, a margin-capped suggested_discount_pct and a max_safe_discount_pct. Use it to recommend WIN-BACK discounts or coupons: the best targets are high lost_value with a LOW success_rate; products that already convert well (high success_rate) need no discount. Never propose a discount above max_safe_discount_pct. To act, create a coupon or a scoped Product-discount rule in AI eShop Optimizer → e-shop Manager → Offers, targeting the returned product IDs. Reads wp_aieo_carts / wp_aieo_cart_items (the daily abandoned-cart capture job). Read-only.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => array(
					'type'       => 'object',
					'properties' => array(
						'limit'            => array(
							'type'        => 'integer',
							'minimum'     => 1,
							'maximum'     => 100,
							'default'     => 15,
							'description' => 'Max products to return (ranked by € lost in non-converting carts).',
						),
						'min_lost_value'   => array(
							'type'        => 'number',
							'minimum'     => 0,
							'default'     => 0,
							'description' => 'Only products that have lost at least this much € in abandoned carts.',
						),
						'max_success_rate' => array(
							'type'        => 'number',
							'minimum'     => 0,
							'maximum'     => 100,
							'default'     => 100,
							'description' => 'Only products whose checkout success rate is at or below this %% (e.g. 40 = focus on poor converters worth discounting).',
						),
					),
				),
				'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' );
	}

	public static function execute( $input ) {
		global $wpdb;
		$input        = is_array( $input ) ? $input : array();
		$limit        = isset( $input['limit'] ) ? max( 1, min( 100, (int) $input['limit'] ) ) : 15;
		$min_lost     = isset( $input['min_lost_value'] ) ? max( 0.0, (float) $input['min_lost_value'] ) : 0.0;
		$max_success  = isset( $input['max_success_rate'] ) ? max( 0.0, min( 100.0, (float) $input['max_success_rate'] ) ) : 100.0;

		$carts = $wpdb->prefix . 'aieo_carts';
		$items = $wpdb->prefix . 'aieo_cart_items';
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $carts ) ) !== $carts
			|| (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $items ) ) !== $items ) {
			return new \WP_Error( 'aieo_carts_missing', __( 'No abandoned-cart data yet — run the Saved & Abandoned Carts capture job first.', 'ai-eshop-optimizer' ) );
		}

		
		$margin_pct = 60.0;
		if ( class_exists( 'AIEO_DMM' ) && method_exists( 'AIEO_DMM', 'get_gross_margin_pct' ) ) {
			$margin_pct = (float) \AIEO_DMM::get_gross_margin_pct();
		}

		
		
		$fetch = min( 300, $limit * 3 + 10 );
		$rows  = (array) $wpdb->get_results(
			$wpdb->prepare(
				"SELECT
					ci.product_id,
					ci.variation_id,
					MAX(ci.sku)  AS sku,
					MAX(ci.name) AS name,
					COUNT(DISTINCT CASE WHEN c.outcome <> 'converted' THEN ci.cart_id END) AS carts,
					COALESCE(SUM(CASE WHEN c.outcome <> 'converted' THEN ci.quantity END),0)   AS units_abandoned,
					COALESCE(SUM(CASE WHEN c.outcome <> 'converted' THEN ci.line_total END),0)  AS lost_value,
					COUNT(DISTINCT CASE WHEN c.outcome = 'converted' THEN ci.cart_id END) AS converted_transactions,
					COALESCE(SUM(CASE WHEN c.outcome = 'converted' THEN ci.quantity END),0)     AS units_sold
				 FROM `{$items}` ci
				 JOIN `{$carts}` c ON c.id = ci.cart_id
				 WHERE c.kind='abandoned'
				 GROUP BY ci.product_id, ci.variation_id
				 HAVING carts > 0
				 ORDER BY lost_value DESC, units_abandoned DESC
				 LIMIT %d",
				$fetch
			),
			ARRAY_A
		);

		$window_start = (string) $wpdb->get_var( "SELECT MIN(created_at) FROM `{$carts}` WHERE kind='abandoned'" );
		$currency     = function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : '';

		$products = array();
		foreach ( $rows as $r ) {
			$lost = (float) $r['lost_value'];
			if ( $lost < $min_lost ) {
				continue;
			}
			$converted      = (int) $r['converted_transactions'];
			$checkout_carts = $converted + (int) $r['carts'];
			$success_rate   = $checkout_carts > 0 ? round( $converted / $checkout_carts * 100, 1 ) : 0.0;
			if ( $success_rate > $max_success ) {
				continue;
			}

			$price_id = (int) ( $r['variation_id'] ? $r['variation_id'] : $r['product_id'] );
			$product  = function_exists( 'wc_get_product' ) ? wc_get_product( $price_id ) : null;
			$price    = ( $product && '' !== $product->get_price() ) ? (float) $product->get_price() : null;

			$disc = self::suggest_discount_pct( $success_rate, $lost, $margin_pct );

			$products[] = array(
				'product_id'             => (int) $r['product_id'],
				'variation_id'           => (int) $r['variation_id'],
				'sku'                    => (string) $r['sku'],
				'name'                   => (string) $r['name'],
				'in_carts'               => (int) $r['carts'],
				'units_abandoned'        => (int) $r['units_abandoned'],
				'lost_value'             => round( $lost, 2 ),
				'checkout_carts'         => $checkout_carts,
				'converted_transactions' => $converted,
				'units_sold'             => (int) $r['units_sold'],
				'success_rate_pct'       => $success_rate,
				'current_price'          => null === $price ? null : round( $price, 2 ),
				'suggested_discount_pct' => $disc,
				'suggested_coupon_value' => ( null !== $price && $disc > 0 ) ? round( $price * $disc / 100, 2 ) : null,
				'max_safe_discount_pct'  => max( 0, (int) round( $margin_pct - 5 ) ),
			);
			if ( count( $products ) >= $limit ) {
				break;
			}
		}

		return array(
			'generated_at'     => current_time( 'mysql', true ),
			'window_start'     => $window_start ? $window_start : null,
			'currency'         => $currency,
			'gross_margin_pct' => round( $margin_pct, 1 ),
			'count'            => count( $products ),
			'note'             => __( 'success_rate_pct = converted checkout carts ÷ every checkout cart the product appeared in (since window_start). BEST win-back targets = high lost_value + LOW success_rate_pct; products with a high success_rate already close and need no discount. suggested_discount_pct is a margin-capped starting hint — never propose more than max_safe_discount_pct. To act, create a coupon or a scoped Product-discount rule in AI eShop Optimizer → e-shop Manager → Offers targeting these product IDs.', 'ai-eshop-optimizer' ),
			'products'         => $products,
		);
	}

	
	private static function suggest_discount_pct( $success_rate, $lost_value, $margin_pct ) {
		if ( $success_rate >= 60.0 ) {
			return 0;
		}
		if ( $success_rate >= 40.0 ) {
			$base = 5;
		} elseif ( $success_rate >= 20.0 ) {
			$base = 10;
		} else {
			$base = 15;
		}
		if ( $lost_value >= 500.0 ) {
			$base += 5;
		}
		$cap = max( 0, (int) round( $margin_pct - 5 ) );
		return (int) min( $base, $cap );
	}
}
