<?php

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

/** Resolve consultation settings without exposing Corriston links to Agency clients. */
class Content_Miner_Consultation_CTA {
	const OPTION = 'content_miner_consultation_cta';
	const DEFAULT_URL = 'https://www.corristonconsulting.com/contact/';

	/** Return tier-aware settings. @return array<string,mixed> */
	public function get_settings( $plan ) {
		$saved = get_option( self::OPTION, array() );
		$saved = is_array( $saved ) ? $saved : array();
		$is_agency = 'agency' === (string) $plan;
		return array(
			'enabled'    => array_key_exists( 'enabled', $saved ) ? ! empty( $saved['enabled'] ) : ! $is_agency,
			'custom_url' => isset( $saved['custom_url'] ) ? (string) $saved['custom_url'] : '',
			'label'      => isset( $saved['label'] ) ? (string) $saved['label'] : '',
		);
	}

	/** Save settings with Agency-safe validation. @return true|WP_Error */
	public function save_settings( $plan, $enabled, $custom_url = '', $label = '' ) {
		$is_agency = 'agency' === (string) $plan;
		$custom_url = $is_agency ? esc_url_raw( trim( (string) $custom_url ) ) : '';
		$label = $is_agency ? sanitize_text_field( $label ) : '';
		if ( $is_agency && $enabled && ( '' === $custom_url || ! wp_http_validate_url( $custom_url ) ) ) {
			return new WP_Error( 'content_miner_invalid_agency_booking_url', __( 'Enter a valid agency booking URL before enabling the consultation link.', 'content-miner' ) );
		}
		update_option(
			self::OPTION,
			array(
				'enabled'    => (bool) $enabled,
				'custom_url' => $custom_url,
				'label'      => $label,
			),
			false
		);
		return true;
	}

	/** Return display-ready CTA data, or an empty array when disabled. @return array<string,string> */
	public function get_cta( array $license_state, $analysis_context, $site_name = '' ) {
		$plan = isset( $license_state['plan'] ) ? (string) $license_state['plan'] : 'free';
		$settings = $this->get_settings( $plan );
		if ( empty( $settings['enabled'] ) ) {
			return array();
		}
		$is_agency = 'agency' === $plan;
		if ( $is_agency && '' === $settings['custom_url'] ) {
			return array();
		}
		$url = $is_agency ? $settings['custom_url'] : self::DEFAULT_URL;
		$label = $is_agency && '' !== $settings['label'] ? $settings['label'] : __( 'Want a human to walk you through this? Book a free 20-minute review.', 'content-miner' );
		$url = add_query_arg(
			array(
				'utm_source' => 'content-miner',
				'site'       => sanitize_text_field( $site_name ),
				'analysis'   => sanitize_key( $analysis_context ),
			),
			$url
		);
		return array(
			'url'    => $url,
			'label'  => $label,
			'source' => $is_agency ? 'agency' : 'corriston',
		);
	}
}
