<?php
/**
 * Raw summary numbers and {@see LineItem} lists for an event. For theme templates, use
 * {@see PaymentSummaryView::build()} — it adds formatted rows, HTML data attributes, and payment-table context.
 *
 * @package WPEventGenius
 */

namespace WPEventGenius\Common\Services;

use WPEventGenius\Common\Event\EventPost;
use WPEventGenius\Common\Registration\Payment\Cart\LineItem;

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

class PaymentSummaryTemplateData {

	/**
	 * Everything the payment-summary and payment-table templates need.
	 *
	 * @param EventPost $event_post Event (or event-like) post.
	 * @param array     $args      Optional. Pass-through from template (e.g. initial_type_quantities, initial_subtotal, initial_fee, initial_total).
	 * @return array{
	 *   has_cost: bool,
	 *   line_items: LineItem[],
	 *   quantity_line_items: LineItem[] (unit amount 0; type id in meta),
	 *   data_attributes: array<string, string>,
	 *   show_subtotal_block: bool,
	 *   subtotal: float,
	 *   fee: float,
	 *   total: float,
	 *   event_post: EventPost
	 * }
	 */
	public static function get( EventPost $event_post, array $args = [] ) {
		$has_cost = method_exists( $event_post, 'has_potential_cost' ) && $event_post->has_potential_cost();

		$initial_type_quantities = isset( $args['initial_type_quantities'] ) && is_array( $args['initial_type_quantities'] ) ? $args['initial_type_quantities'] : array();
		$registration_data      = array( 'initial_type_quantities' => $initial_type_quantities );

		$line_items_service = new LineItemsService();
		$line_items         = $line_items_service->get_potential_line_items( $event_post, $registration_data );
		$line_items         = apply_filters( 'evge_potential_line_items', $line_items, $event_post, $registration_data );

		$line_items_for_json = array();
		foreach ( $line_items as $li ) {
			$line_items_for_json[] = $li->to_array_for_display();
		}
		$data_attributes = array(
			'payment-json'   => method_exists( $event_post, 'get_payment_json' ) ? $event_post->get_payment_json() : '',
			'cost-template' => '',
			'currency-symbol' => '',
			'type-prices'   => '',
			'line-items'    => wp_json_encode( $line_items_for_json ),
		);
		if ( $has_cost && method_exists( $event_post, 'get_cost_display_parts_for_js' ) ) {
			$parts = $event_post->get_cost_display_parts_for_js();
			$data_attributes['cost-template']   = isset( $parts['template'] ) ? $parts['template'] : '';
			$data_attributes['currency-symbol'] = isset( $parts['symbol'] ) ? $parts['symbol'] : '';
		}
		$type_prices = array();
		foreach ( $line_items as $item ) {
			$tid = $item->get_type_id();
			if ( $tid !== null && $tid > 0 ) {
				$type_prices[ $tid ] = (float) $item->get_amount();
			}
		}
		if ( ! empty( $type_prices ) ) {
			$data_attributes['type-prices'] = wp_json_encode( $type_prices );
		}

		$initial_subtotal = isset( $args['initial_subtotal'] ) ? (float) $args['initial_subtotal'] : null;
		$initial_fee      = isset( $args['initial_fee'] ) ? (float) $args['initial_fee'] : null;
		$initial_total    = isset( $args['initial_total'] ) ? (float) $args['initial_total'] : null;

		$subtotal = 0.0;
		$fee      = 0.0;
		$total    = 0.0;
		if ( $initial_subtotal !== null ) {
			$subtotal = $initial_subtotal;
			$fee      = $initial_fee !== null ? $initial_fee : 0.0;
			$total    = $initial_total !== null ? $initial_total : $subtotal;
		} elseif ( ! empty( $line_items ) ) {
			foreach ( $line_items as $item ) {
				$subtotal += $item->get_line_total();
			}
			$subtotal = round( $subtotal, 2 );
			$total    = $subtotal;
		} else {
			$cost = method_exists( $event_post, 'get_the_cost_amount' ) ? (float) $event_post->get_the_cost_amount() : 0.0;
			$subtotal = $total = $cost;
		}

		$quantity_line_items = array();
		if ( ! $has_cost ) {
			$title = method_exists( $event_post, 'get_the_title' ) ? $event_post->get_the_title() : '';
			$active_types = method_exists( $event_post, 'get_active_registration_types' ) ? $event_post->get_active_registration_types() : array();
			if ( count( $active_types ) >= 2 ) {
				foreach ( $active_types as $type ) {
					$type_id   = isset( $type['id'] ) ? (int) $type['id'] : 0;
					$type_name = isset( $type['name'] ) ? $type['name'] : '';
					if ( $type_id <= 0 ) {
						continue;
					}
					$qty = isset( $initial_type_quantities[ $type_id ] ) ? (int) $initial_type_quantities[ $type_id ] : 0;
					$quantity_line_items[] = new LineItem(
						$title . ( $type_name !== '' ? ' – ' . $type_name : '' ),
						$qty,
						0.0,
						array( 'type_id' => $type_id )
					);
				}
			} else {
				$total_qty = ! empty( $initial_type_quantities ) ? array_sum( $initial_type_quantities ) : 1;
				$quantity_line_items[] = new LineItem(
					$title,
					max( 1, (int) $total_qty ),
					0.0,
					array( 'type_id' => null )
				);
			}
		}

		return array(
			'has_cost'             => $has_cost,
			'line_items'           => $line_items,
			'quantity_line_items'   => $quantity_line_items,
			'data_attributes'      => $data_attributes,
			'show_subtotal_block'  => false,
			'subtotal'             => $subtotal,
			'fee'                  => $fee,
			'total'                => $total,
			'event_post'           => $event_post,
		);
	}
}
