<?php
namespace MetForm_Pro\Core\Submission_Log;

defined( 'ABSPATH' ) || exit;

/**
 * Submission Failure Log module (Pro, Mid/Top tier).
 *
 * Records failed MetForm submissions per form when the form's
 * "Enable Submission Failure Log" setting is turned on. Decoupled from the
 * analytics module so logging keeps working regardless of the global Analytics
 * toggle.
 */
class Base {

	use \MetForm_Pro\Traits\Singleton;

	/**
	 * REST API handler.
	 *
	 * @var Api
	 */
	public $api;

	/**
	 * Register hooks and ensure the storage table exists.
	 */
	public function init() {
		// Version-guarded — cheap no-op once the table is present and current.
		Database::update_db();

		// REST endpoint used by the analytics popup to read a form's failure logs.
		$this->api = new Api();

		// Fired by MetForm free (core/entries/api.php) when a submission is rejected.
		add_action( 'metform_submission_failed', [ $this, 'on_submission_failed' ], 10, 3 );

		// Clean up a form's logs when it is permanently deleted.
		add_action( 'before_delete_post', [ $this, 'on_form_deleted' ], 10, 1 );
	}

	/**
	 * Persist a failed submission for a form when logging is enabled for it.
	 *
	 * @param int          $form_id  Form ID.
	 * @param array|string $messages Error message(s).
	 * @param array        $context  Extra context (currently unused for storage).
	 */
	public function on_submission_failed( $form_id, $messages = [], $context = [] ) {
		$form_id = intval( $form_id );

		if ( $form_id <= 0 || get_post_type( $form_id ) !== 'metform-form' ) {
			return;
		}

		if ( ! self::is_enabled_for_form( $form_id ) ) {
			return;
		}

		// Only keep unexpected failures; skip the ones that already showed the visitor a
		// clear, specific message.
		if ( ! Database::should_log( $context, $messages ) ) {
			return;
		}

		Database::insert( $form_id, $messages, is_array( $context ) ? $context : [] );
	}

	/**
	 * Whether the submission failure log is enabled for a given form.
	 *
	 * @param int $form_id Form ID.
	 * @return bool
	 */
	public static function is_enabled_for_form( $form_id ) {
		// Read the per-form settings meta directly. This is on the submission path,
		// so it deliberately avoids the heavier Forms\Action::get_all_data().
		$settings = get_post_meta( intval( $form_id ), 'metform_form__form_setting', true );

		return is_array( $settings ) && ! empty( $settings['mf_enable_submission_error_log'] );
	}

	/**
	 * Remove all logs for a form when it is permanently deleted.
	 *
	 * @param int $post_id Post ID being deleted.
	 */
	public function on_form_deleted( $post_id ) {
		if ( get_post_type( $post_id ) !== 'metform-form' ) {
			return;
		}

		Database::delete_form_logs( $post_id );
	}
}
