<?php
/**
 * REST endpoint: `POST /trx-auto-dealer/v1/leads`.
 *
 * Per BUILD-ORDER §7. Thin delegation to `Forms\FormHandler` so the public
 * route stays in lock-step with the existing `/forms/submit` endpoint —
 * same validation, same honeypot, same nonce, same rate limit.
 *
 * Read-side (`GET /leads`) is intentionally NOT exposed in the free tier —
 * leads aren't persisted to the database in free mode (email-only
 * delivery), so there's nothing to read. Pro adds lead storage and a
 * separate Pro-tier collection endpoint.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\REST;

use ThemeREX\AutoDealer\Forms\FormHandler;
use WP_REST_Controller;
use WP_REST_Request;

class LeadsController extends WP_REST_Controller {

	public function __construct() {
		$this->namespace = TRX_AD_REST_NAMESPACE;
		$this->rest_base = 'leads';
	}

	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'create_item' ),
					'permission_callback' => '__return_true',
					'args'                => array(
						'form_id' => array(
							'type'        => 'string',
							'required'    => true,
							'description' => __( 'Form ID (inquiry, test_drive, callback, finance, trade_in).', 'trx-auto-dealer' ),
						),
						'post_id' => array(
							'type'        => 'integer',
							'required'    => false,
							'description' => __( 'Listing post ID for vehicle/dealer-pre-fill context.', 'trx-auto-dealer' ),
						),
						'fields'  => array(
							'type'        => 'object',
							'required'    => true,
							'description' => __( 'Submitted field values keyed by field id.', 'trx-auto-dealer' ),
						),
					),
				),
			)
		);
	}

	/**
	 * Delegate to the canonical form handler. Keeps validation, honeypot,
	 * nonce, rate limit, and email-send logic in one place.
	 */
	public function create_item( $request ) {
		return ( new FormHandler() )->handleSubmission( $request );
	}
}
