<?php
/**
 * @fs_premium_only
 *
 * Pro — Lead-capture form on the single vehicle page.
 *
 * Replaces the free "Contact Dealer" mailto button (via the afi_vehicle_cta
 * filter) with an inline inquiry form carrying the vehicle's context. Submits
 * over admin-ajax with client + server validation and emails the dealer.
 *
 * @since 2.6.0
 * @package AutomotiveFeedImport
 */

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

class AFI_Lead_Form {

	/** @var AutomotiveFeedImport */
	private $afi;

	/**
	 * @param AutomotiveFeedImport $afi Main plugin instance.
	 */
	public function __construct($afi) {
		$this->afi = $afi;
		add_filter('afi_vehicle_cta', array($this, 'render'), 10, 3);
		add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
		add_action('wp_ajax_afi_lead_submit', array($this, 'ajax_submit'));
		add_action('wp_ajax_nopriv_afi_lead_submit', array($this, 'ajax_submit'));
	}

	/**
	 * Render the lead form in place of the free CTA.
	 *
	 * @param string $cta     Default CTA HTML.
	 * @param int    $post_id Vehicle post ID.
	 * @param array  $detail  Detail data.
	 * @return string
	 */
	public function render($cta, $post_id, $detail) {
		$stock = trim((string) get_post_meta($post_id, 'stock_number', true));
		ob_start();
		?>
		<form class="aii-leadform aii-leadform--inline" id="afi-leadform" data-vehicle="<?php echo esc_attr($post_id); ?>" novalidate>
			<div class="aii-leadform__body">
				<div class="aii-leadform__heading"><?php esc_html_e('Ask about this vehicle', 'automotive-feed-import'); ?></div>

				<div class="aii-leadform__row">
					<div class="aii-field" data-validate="name">
						<label class="aii-label" for="afi-lead-name"><?php esc_html_e('Full name', 'automotive-feed-import'); ?> <span class="aii-label__req">*</span></label>
						<input class="aii-input" type="text" id="afi-lead-name" name="name" autocomplete="name" required aria-required="true">
						<span class="aii-field__error"><svg aria-hidden="true" focusable="false"><use href="#i-alert"></use></svg><?php esc_html_e('Please enter your name', 'automotive-feed-import'); ?></span>
					</div>
					<div class="aii-field">
						<label class="aii-label" for="afi-lead-phone"><?php esc_html_e('Phone', 'automotive-feed-import'); ?></label>
						<input class="aii-input" type="tel" id="afi-lead-phone" name="phone" autocomplete="tel" placeholder="(555) 123-4567">
					</div>
				</div>

				<div class="aii-field" data-validate="email">
					<label class="aii-label" for="afi-lead-email"><?php esc_html_e('Email', 'automotive-feed-import'); ?> <span class="aii-label__req">*</span></label>
					<input class="aii-input" type="email" id="afi-lead-email" name="email" autocomplete="email" placeholder="you@email.com" required aria-required="true">
					<span class="aii-field__error"><svg aria-hidden="true" focusable="false"><use href="#i-alert"></use></svg><?php esc_html_e('Enter a valid email address', 'automotive-feed-import'); ?></span>
				</div>

				<div class="aii-field">
					<label class="aii-label" for="afi-lead-message"><?php esc_html_e('Message', 'automotive-feed-import'); ?></label>
					<textarea class="aii-textarea" id="afi-lead-message" name="message" rows="3"><?php
						/* translators: %s: vehicle title. */
						echo esc_textarea(sprintf(__('Is this %s still available? I\'d like to know more.', 'automotive-feed-import'), $detail['title']));
					?></textarea>
				</div>

				<label class="aii-check">
					<input type="checkbox" name="financing" value="1">
					<span class="aii-check__box"><svg aria-hidden="true" focusable="false"><use href="#i-check"></use></svg></span>
					<span class="aii-check__text"><?php esc_html_e('I\'m interested in financing', 'automotive-feed-import'); ?><small><?php esc_html_e('A finance specialist will include payment options in their reply.', 'automotive-feed-import'); ?></small></span>
				</label>

				<button class="aii-btn aii-btn--primary aii-btn--lg aii-btn--block" type="submit"><?php esc_html_e('Send inquiry', 'automotive-feed-import'); ?></button>
				<p class="aii-leadform__fineprint"><?php esc_html_e('By submitting you agree to be contacted about this vehicle.', 'automotive-feed-import'); ?></p>
			</div>

			<div class="aii-leadform__success" aria-live="polite">
				<div class="aii-leadform__check"><svg aria-hidden="true" focusable="false"><use href="#i-check"></use></svg></div>
				<h4><?php esc_html_e('Inquiry sent!', 'automotive-feed-import'); ?></h4>
				<p><?php
					echo esc_html(
						'' !== $stock
							/* translators: 1: vehicle title, 2: stock number. */
							? sprintf(__('Thanks — the team has your message about the %1$s (Stock #%2$s) and will reply shortly.', 'automotive-feed-import'), $detail['title'], $stock)
							/* translators: %s: vehicle title. */
							: sprintf(__('Thanks — the team has your message about the %s and will reply shortly.', 'automotive-feed-import'), $detail['title'])
					);
				?></p>
				<button class="aii-btn aii-btn--secondary" type="button" data-leadreset><?php esc_html_e('Send another', 'automotive-feed-import'); ?></button>
			</div>
		</form>
		<?php
		return ob_get_clean();
	}

	/**
	 * AJAX: validate + email a vehicle inquiry.
	 *
	 * @return void
	 */
	public function ajax_submit() {
		check_ajax_referer('afi_lead', 'nonce');

		$post_id = isset($_POST['vehicle_id']) ? absint($_POST['vehicle_id']) : 0;
		$name    = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
		$email   = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
		$phone   = isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '';
		$message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '';
		$finance = ! empty($_POST['financing']);

		$errors = array();
		if ('' === $name) {
			$errors['name'] = __('Please enter your name', 'automotive-feed-import');
		}
		if ('' === $email || ! is_email($email)) {
			$errors['email'] = __('Enter a valid email address', 'automotive-feed-import');
		}
		if (! $post_id || 'vehicles' !== get_post_type($post_id)) {
			$errors['form'] = __('Something went wrong. Please try again.', 'automotive-feed-import');
		}
		if ($errors) {
			wp_send_json_error(array('errors' => $errors));
		}

		$title = $this->afi->normalize_title_display(get_the_title($post_id));
		$stock = trim((string) get_post_meta($post_id, 'stock_number', true));
		$price = trim((string) get_post_meta($post_id, 'special_web_price', true));
		$to    = sanitize_email((string) get_option('admin_email'));

		$lines = array();
		/* translators: %s: vehicle title. */
		$lines[] = sprintf(__('New inquiry about: %s', 'automotive-feed-import'), $title);
		if ('' !== $stock) {
			$lines[] = sprintf(__('Stock #: %s', 'automotive-feed-import'), $stock);
		}
		$lines[] = __('Vehicle: ', 'automotive-feed-import') . get_permalink($post_id);
		$lines[] = '';
		$lines[] = sprintf(__('Name: %s', 'automotive-feed-import'), $name);
		$lines[] = sprintf(__('Email: %s', 'automotive-feed-import'), $email);
		if ('' !== $phone) {
			$lines[] = sprintf(__('Phone: %s', 'automotive-feed-import'), $phone);
		}
		$lines[] = sprintf(__('Interested in financing: %s', 'automotive-feed-import'), $finance ? __('Yes', 'automotive-feed-import') : __('No', 'automotive-feed-import'));
		if ('' !== $message) {
			$lines[] = '';
			$lines[] = __('Message:', 'automotive-feed-import');
			$lines[] = $message;
		}

		/* translators: 1: vehicle title, 2: stock number suffix. */
		$subject = sprintf(__('Vehicle inquiry: %1$s%2$s', 'automotive-feed-import'), $title, '' !== $stock ? ' (#' . $stock . ')' : '');
		$headers = array('Reply-To: ' . $name . ' <' . $email . '>');

		$sent = $to ? wp_mail($to, $subject, implode("\n", $lines), $headers) : false;

		/**
		 * Fires after a vehicle lead is submitted (for CRM/webhook integrations).
		 *
		 * @param array $lead    Sanitized lead fields.
		 * @param int   $post_id Vehicle post ID.
		 * @param bool  $sent    Whether the notification email was sent.
		 */
		do_action('afi_lead_submitted', compact('name', 'email', 'phone', 'message', 'finance'), $post_id, $sent);

		wp_send_json_success(array('sent' => (bool) $sent));
	}

	/**
	 * Enqueue the lead-form script on single vehicle pages.
	 *
	 * @return void
	 */
	public function enqueue_assets() {
		if (! is_singular('vehicles')) {
			return;
		}
		$ver = defined('AFI_VERSION') ? AFI_VERSION : '2.6.0';
		wp_enqueue_script(
			'aii-lead-form',
			plugins_url('assets/aii-lead-form.js', __FILE__),
			array(),
			$ver,
			true
		);
		wp_localize_script('aii-lead-form', 'aiiLead', array(
			'ajaxUrl' => admin_url('admin-ajax.php'),
			'nonce'   => wp_create_nonce('afi_lead'),
			'i18n'    => array(
				'sending' => __('Sending…', 'automotive-feed-import'),
				'send'    => __('Send inquiry', 'automotive-feed-import'),
				'error'   => __('Something went wrong. Please try again.', 'automotive-feed-import'),
			),
		));
	}
}
