<?php

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

class AIEO_DMM_Checkout_Timing extends AIEO_DMM_Module_Base {

	public function get_id()       { return 'checkout_timing'; }
	public function get_label()    { return __( 'Checkout Timing', 'ai-eshop-optimizer' ); }
	public function get_priority() { return 30; }
	public function get_group()    { return 'attribution'; }

	public function render_subtab() {
		$this->render_template( 'checkout-timing.php', array( 'data' => $this->get_data() ) );
	}

	
	public static function recommended_delay_seconds( $product_id = 0 ) {
		$map = get_transient( 'aieo_ct_recommended' );
		if ( false === $map || ! is_array( $map ) ) {
			$map = self::compute_recommended();
			set_transient( 'aieo_ct_recommended', $map, HOUR_IN_SECONDS );
		}
		$product_id = (int) $product_id;
		if ( $product_id > 0 && ! empty( $map['products'][ $product_id ] ) ) {
			return (int) $map['products'][ $product_id ];
		}
		return (int) ( isset( $map['overall'] ) ? $map['overall'] : 0 );
	}

	private static function compute_recommended() {
		$inst = new self();
		$data = $inst->get_data();
		$out  = array( 'overall' => 0, 'products' => array() );
		if ( empty( $data['available'] ) ) {
			return $out;
		}
		$out['overall'] = (int) ( isset( $data['baseline']['recommended'] ) ? $data['baseline']['recommended'] : 0 );
		if ( ! empty( $data['products']['available'] ) && ! empty( $data['products']['rows'] ) ) {
			foreach ( $data['products']['rows'] as $r ) {
				$out['products'][ (int) $r['product_id'] ] = (int) $r['avg_active'];
			}
		}
		return $out;
	}

	
	public function get_data() {
		global $wpdb;
		$t = $wpdb->prefix . 'aieo_checkout_timing';
		$out = array( 'available' => false, 'rows' => 0 );
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t ) ) !== $t ) {
			return $out;
		}
		
		$rows = (array) $wpdb->get_results( "SELECT active_seconds, idle_seconds, total_seconds, has_coupon FROM `{$t}`", ARRAY_A );

		$out['available'] = true;
		$out['rows']      = count( $rows );
		$out['all']       = $this->stats( $rows, false );
		$out['baseline']  = $this->stats( $rows, true ); 
		$out['products']  = $this->per_product();
		return $out;
	}

	
	private function stats( $rows, $exclude_coupon ) {
		$act = array();
		$idle = array();
		$tot = array();
		foreach ( $rows as $r ) {
			if ( $exclude_coupon && 1 === (int) $r['has_coupon'] ) {
				continue;
			}
			$act[]  = (int) $r['active_seconds'];
			$idle[] = (int) $r['idle_seconds'];
			$tot[]  = (int) $r['total_seconds'];
		}
		return array(
			'n'             => count( $act ),
			'median_active' => $this->percentile( $act, 50 ),
			'median_idle'   => $this->percentile( $idle, 50 ),
			'median_total'  => $this->percentile( $tot, 50 ),
			'p75_total'     => $this->percentile( $tot, 75 ),
			
			'recommended'   => $this->percentile( $act, 50 ),
		);
	}

	private function percentile( $a, $p ) {
		if ( empty( $a ) ) {
			return 0;
		}
		sort( $a );
		$idx = (int) floor( ( $p / 100 ) * ( count( $a ) - 1 ) );
		return (int) $a[ $idx ];
	}

	
	private function per_product() {
		global $wpdb;
		$t  = $wpdb->prefix . 'aieo_checkout_timing';
		$op = $wpdb->prefix . 'aieo_order_products_analytics';
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $op ) ) !== $op ) {
			return array( 'available' => false, 'rows' => array() );
		}
		
		$rows = (array) $wpdb->get_results(
			"SELECT op.product_id,
			        COUNT(DISTINCT ct.order_id) AS orders,
			        ROUND(AVG(ct.active_seconds)) AS avg_active,
			        ROUND(AVG(ct.idle_seconds)) AS avg_idle,
			        ROUND(AVG(ct.total_seconds)) AS avg_total
			 FROM `{$t}` ct
			 JOIN `{$op}` op ON op.order_id = ct.order_id
			 WHERE ct.has_coupon = 0
			 GROUP BY op.product_id
			 HAVING orders > 0
			 ORDER BY orders DESC
			 LIMIT 30",
			ARRAY_A
		);
		return array( 'available' => true, 'rows' => $rows );
	}
}
