<?php
namespace WPEventGenius\Common\Registration\Payment\Cart;

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

class LineItem extends Item {

	/**
	 * Registration type id when present (potential/cart meta uses type_id or event_registration_type_id).
	 *
	 * @return int|null
	 */
	public function get_type_id() {
		$meta = $this->get_meta();
		if ( ! is_array( $meta ) ) {
			return null;
		}
		if ( ! empty( $meta['type_id'] ) ) {
			return (int) $meta['type_id'];
		}
		if ( isset( $meta['event_registration_type_id'] ) && (int) $meta['event_registration_type_id'] > 0 ) {
			return (int) $meta['event_registration_type_id'];
		}
		return null;
	}

	/**
	 * Line total in dollars (uses meta line_total when set, e.g. pre-rounded potential totals).
	 */
	public function get_line_total() {
		$meta = $this->get_meta();
		if ( is_array( $meta ) && isset( $meta['line_total'] ) ) {
			return (float) $meta['line_total'];
		}
		return (float) $this->get_calculated_amount();
	}

	/**
	 * Shape used by payment-table markup, JSON data attributes, and front-end scripts.
	 *
	 * @return array{label: string, quantity: int, unit_price: float, line_total: float, type_id: int|null}
	 */
	public function to_array_for_display() {
		return array(
			'label'      => $this->get_label(),
			'quantity'   => (int) $this->get_quantity(),
			'unit_price' => (float) $this->get_amount(),
			'line_total' => round( $this->get_line_total(), 2 ),
			'type_id'    => $this->get_type_id(),
		);
	}
}