<?php

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

class AIEO_Order_Facts {

	
	private static $l1 = array();

	
	public static function get( $order_id ) {
		$order_id = (int) $order_id;
		if ( $order_id <= 0 ) {
			return self::blank();
		}
		if ( isset( self::$l1[ $order_id ] ) ) {
			return self::$l1[ $order_id ];
		}

		global $wpdb;
		$f = self::blank();

		
		
		$stats = $wpdb->prefix . 'aieo_order_stats';
		$row   = $wpdb->get_row( $wpdb->prepare(
			"SELECT orderspend, totalshipping, netspendonproducts FROM `{$stats}` WHERE orderid = %d LIMIT 1",
			$order_id
		) );
		if ( $row ) {
			$f['gross']    = ( $row->orderspend !== null ) ? (float) $row->orderspend : null;
			$f['shipping'] = ( $row->totalshipping !== null ) ? (float) $row->totalshipping : null;
			$f['net']      = ( $row->netspendonproducts !== null ) ? (float) $row->netspendonproducts : null;
		}

		
		$attr = $wpdb->prefix . 'aieo_order_attribution';
		$a    = $wpdb->get_row( $wpdb->prepare(
			"SELECT channel, utm_source, utm_medium, utm_campaign FROM `{$attr}` WHERE order_id = %d LIMIT 1",
			$order_id
		) );
		if ( $a ) {
			$f['channel']      = ( $a->channel !== null && $a->channel !== '' ) ? $a->channel : null;
			$f['utm_source']   = $a->utm_source;
			$f['utm_medium']   = $a->utm_medium;
			$f['utm_campaign'] = $a->utm_campaign;
		}

		
		
		
		if ( null === $f['channel'] ) {
			$sess = $wpdb->prefix . 'aieo_sessions_statics';
			$ch   = $wpdb->get_var( $wpdb->prepare(
				"SELECT NULLIF(entry_channel,'') FROM `{$sess}`
				 WHERE order_id = %d ORDER BY last_timestamp DESC, id DESC LIMIT 1",
				$order_id
			) );
			if ( null !== $ch && '' !== $ch ) {
				$f['channel'] = $ch;
			}
		}

		self::$l1[ $order_id ] = $f;
		return $f;
	}

	
	public static function revenue( $order_id, $type = 'gross' ) {
		$f   = self::get( $order_id );
		$key = in_array( $type, array( 'gross', 'net', 'shipping' ), true ) ? $type : 'gross';
		return $f[ $key ];
	}

	
	public static function channel( $order_id ) {
		$f = self::get( $order_id );
		return $f['channel'];
	}

	
	public static function get_batch( array $order_ids ) {
		$out = array();
		foreach ( $order_ids as $oid ) {
			$oid = (int) $oid;
			if ( $oid > 0 ) {
				$out[ $oid ] = self::get( $oid );
			}
		}
		return $out;
	}

	
	public static function flush_cache() {
		self::$l1 = array();
	}

	private static function blank() {
		return array(
			'gross'        => null,
			'shipping'     => null,
			'net'          => null,
			'channel'      => null,
			'utm_source'   => null,
			'utm_medium'   => null,
			'utm_campaign' => null,
		);
	}
}
