<?php
/**
 * 条件分岐ロジック
 *
 * @package CF7MasterPro\Form
 */

namespace CF7MasterPro\Form;

defined( 'ABSPATH' ) || exit;

/**
 * 条件分岐（show/hide 等・ルール数は無制限）
 */
class ConditionalLogic {

	/**
	 * 登録
	 */
	public function register() {
		add_filter( 'wpcf7_form_elements', array( $this, 'inject_conditional_data' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	/**
	 * フォームHTMLに条件データを埋込
	 *
	 * @param string $form HTML.
	 * @return string
	 */
	public function inject_conditional_data( $form ) {
		global $wpdb;
		$form_id = $this->get_form_id();
		if ( ! $form_id ) {
			return $form;
		}
		$table    = $wpdb->prefix . CF7MP_DB_PREFIX . 'form_settings';
		$settings = $wpdb->get_var( $wpdb->prepare( "SELECT settings FROM {$table} WHERE form_id = %d", $form_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table; name from trusted prefix; value prepared.
		if ( ! $settings ) {
			return $form;
		}
		$config = json_decode( $settings, true );
		if ( empty( $config['conditional_rules'] ) ) {
			return $form;
		}

		$rules = $config['conditional_rules'];

		$json = wp_json_encode( array_values( $rules ) );
		return str_replace(
			'<form ',
			'<form data-cf7mp-conditional="' . esc_attr( $json ) . '" ',
			$form
		);
	}

	/**
	 * フォームID取得
	 *
	 * @return int
	 */
	private function get_form_id() {
		if ( function_exists( 'wpcf7_get_current_contact_form' ) ) {
			$cf7 = wpcf7_get_current_contact_form();
			return $cf7 ? $cf7->id() : 0;
		}
		return 0;
	}

	/**
	 * JS読込
	 */
	public function enqueue() {
		// メインアセットで一括読込
	}
}
