<?php
/**
 * The warranty lookup for customers with no account.
 *
 * @package WarrantyCart
 */

namespace WarrantyCart\Frontend;

use WarrantyCart\Core\Claims;
use WarrantyCart\Core\GuestAccess;

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

/**
 * `[warranty_claim]` — find cover by order number and email, then claim on it.
 *
 * A page of its own rather than a tab, because the customer this serves has no
 * account area to put a tab in. The shop links to it from the order email and
 * from wherever it explains its warranty.
 *
 * Deliberately not appended anywhere automatically. A shop that does not take
 * guest orders has no use for this page, and one that does should choose where
 * it sits.
 */
class GuestClaim {

	/**
	 * The shortcode tag.
	 */
	public const TAG = 'warranty_claim';

	/**
	 * The page the shop put the shortcode on.
	 */
	public const PAGE_OPTION = 'warranty_cart_claim_page';

	/**
	 * Where a customer with no account is told to go.
	 *
	 * Validated on every read rather than trusted, for the same reason the
	 * selector's page is: a stored ID outlives the page it points at, and a
	 * link in an email that lands on a 404 is worse than no link.
	 *
	 * @return string The page URL, or '' when unset or no longer usable.
	 */
	public static function page_url(): string {
		$page_id = (int) get_option( self::PAGE_OPTION, 0 );

		if ( $page_id <= 0 || 'publish' !== get_post_status( $page_id ) ) {
			return '';
		}

		return (string) get_permalink( $page_id );
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_shortcode( self::TAG, array( $this, 'render' ) );
	}

	/**
	 * Render the lookup form.
	 *
	 * Everything after the lookup is drawn by the frontend bundle from what the
	 * REST route returns — there is nothing to render server-side until the
	 * customer has proved which order is theirs.
	 *
	 * @return string
	 */
	public function render(): string {
		if ( ! Claims::is_enabled() ) {
			return '';
		}

		/*
		 * A signed-in customer is sent to their own account instead.
		 *
		 * Their warranties are there already, with the claim history beside
		 * them, and `GuestAccess` refuses an order that belongs to an account —
		 * so leaving the form up would offer them something guaranteed to fail.
		 */
		if ( is_user_logged_in() ) {
			return $this->account_notice();
		}

		if ( ! GuestAccess::is_enabled() ) {
			return '';
		}

		ob_start();

		wc_get_template(
			'frontend/guest-claim.php',
			array(),
			'warranty-cart',
			WARRANTY_CART_PATH . 'templates/'
		);

		return (string) ob_get_clean();
	}

	/**
	 * Point a signed-in customer at the tab that already has their cover.
	 *
	 * @return string
	 */
	private function account_notice(): string {
		return sprintf(
			'<p class="warranty-guest__signed-in"><a href="%1$s">%2$s</a></p>',
			esc_url( wc_get_account_endpoint_url( MyAccount::ENDPOINT ) ),
			esc_html__( 'Your warranties are in your account.', 'warranty-cart' )
		);
	}
}
