<?php
/**
 * Dynamic Form Settings
 *
 * @package Replyan_AI
 */

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

class Replyan_AI_Form_Settings {

	/**
	 * Get settings for a specific form.
	 *
	 * @param int $form_id The form ID.
	 * @return array
	 */
	public static function get_settings( int $form_id ): array {
		global $wpdb;
		$table = $wpdb->prefix . 'replyan_form_settings';

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
		$results = $wpdb->get_results( $wpdb->prepare( "SELECT setting_key, setting_value FROM {$table} WHERE form_id = %d", $form_id ) );

		$settings = array();
		if ( $results ) {
			foreach ( $results as $row ) {
				$settings[ $row->setting_key ] = maybe_unserialize( $row->setting_value );
			}
		}

		return $settings;
	}

	/**
	 * Save settings for a specific form.
	 *
	 * @param int   $form_id The form ID.
	 * @param array $settings The settings array (key => value).
	 */
	public static function save_settings( int $form_id, array $settings ): void {
		global $wpdb;
		$table = $wpdb->prefix . 'replyan_form_settings';

		foreach ( $settings as $key => $value ) {
			// Check if setting exists
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
			$exists = $wpdb->get_var( $wpdb->prepare( "SELECT form_id FROM {$table} WHERE form_id = %d AND setting_key = %s", $form_id, $key ) );

			$serialized_value = is_array( $value ) || is_object( $value ) ? serialize( $value ) : $value;

			if ( $exists ) {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$wpdb->update(
					$table,
					array( 'setting_value' => $serialized_value ),
					array(
						'form_id'     => $form_id,
						'setting_key' => $key,
					)
				);
			} else {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$wpdb->insert(
					$table,
					array(
						'form_id'       => $form_id,
						'setting_key'   => $key,
						'setting_value' => $serialized_value,
					)
				);
			}
		}
	}
}
