<?php
/**
 * Gateways Data Store Custom Post Type
 *
 * @author    Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license   GPL-3.0-or-later
 * @package   Wpayme\WordPress\Pay\Gateways
 */

namespace Wpayme\WordPress\Pay\Gateways;

use Wpayme\WordPress\Pay\AbstractDataStoreCPT;
use Wpayme\WordPress\Pay\Core\Gateway;

/**
 * Title: Gateways data store CPT
 * Description:
 * Copyright: 2024-2025 Wpayme
 * Company: Wpayme
 *
 * @author  Reüel van der Steege
 * @version 4.0.0
 * @since   4.0.0
 */
class GatewaysDataStoreCPT extends AbstractDataStoreCPT {
	/**
	 * Gateways.
	 *
	 * @var Gateway[]
	 */
	private $gateways;

	/**
	 * Construct gateways data store CPT object.
	 */
	public function __construct() {
		$this->meta_key_prefix = '_wpayme_gateway_';

		$this->gateways = [];
	}

	/**
	 * Get gateway by ID.
	 *
	 * @param int $post_id Gateway configuration post ID.
	 * @return Gateway|null
	 */
	public function get_gateway( $post_id ) {
		if ( ! isset( $this->gateways[ $post_id ] ) ) {
			// Check post type.
			$post_type = get_post_type( $post_id );

			if ( 'wpayme_gateway' !== $post_type ) {
				return null;
			}

			// Check if trashed.
			if ( 'trash' === get_post_status( $post_id ) ) {
				return null;
			}

			// Get integration.
			$gateway_id = \get_post_meta( $post_id, '_wpayme_gateway_id', true );

			if ( empty( $gateway_id ) ) {
				return null;
			}

			$integration = wpayme_pay_plugin()->gateway_integrations->get_integration( $gateway_id );

			if ( null === $integration ) {
				return null;
			}

			// Get gateway from integration for configuration post ID.
			$gateway = $integration->get_gateway( $post_id );

			if ( null !== $gateway ) {
				$this->gateways[ $post_id ] = $gateway;
			}
		}

		return $this->gateways[ $post_id ];
	}
}
