<?php
namespace MetForm_Pro\Core\Submission_Log;

defined( 'ABSPATH' ) || exit;

/**
 * REST API for the submission failure log.
 *
 * Route: GET metform-pro/v1/submission-log/logs?formId={id}
 * Returns: { enabled: bool, logs: [ { created_at, messages }, ... ] }
 *
 * Kept on its own REST prefix (not under analytics) so it is not gated by the
 * global analytics toggle.
 */
class Api extends \MetForm_Pro\Base\Api {

	public function config() {
		$this->prefix = 'submission-log';
		// Trailing slash optional; no extra path params needed.
		$this->param  = '/?';
	}

	/**
	 * GET metform-pro/v1/submission-log/logs
	 *
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function get_logs() {
		if ( ! wp_verify_nonce( $this->request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) {
			return new \WP_Error(
				'rest_forbidden',
				esc_html__( 'Invalid or missing nonce.', 'metform-pro' ),
				[ 'status' => 403 ]
			);
		}

		if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
			return new \WP_Error(
				'rest_forbidden',
				esc_html__( 'You do not have permission to access this resource.', 'metform-pro' ),
				[ 'status' => 403 ]
			);
		}

		$form_id = 0;
		if ( isset( $this->request['formId'] ) && $this->request['formId'] !== '' ) {
			$form_id = intval( $this->request['formId'] );
		} elseif ( isset( $this->request['form_id'] ) && $this->request['form_id'] !== '' ) {
			$form_id = intval( $this->request['form_id'] );
		}

		if ( $form_id <= 0 ) {
			return new \WP_Error(
				'invalid_form_id',
				esc_html__( 'Invalid form ID.', 'metform-pro' ),
				[ 'status' => 400 ]
			);
		}

		// Honour the per-form toggle: when disabled, report disabled and return no logs.
		$enabled = Base::is_enabled_for_form( $form_id );
		$logs    = $enabled ? Database::get_logs( $form_id ) : [];

		return rest_ensure_response( [
			'enabled' => (bool) $enabled,
			'logs'    => $logs,
		] );
	}
}
