<?php
/**
 * Live settings foundation (preview-ready, not implemented).
 *
 * @package Kutby
 * @since   2.5.0
 */

declare(strict_types=1);

namespace Kutby\Live;

use Kutby\Design\Tokens;
use Kutby\ThemeOptions\FieldRegistry;
use Kutby\ThemeOptions\Manager;

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

/**
 * Class SettingsBridge
 *
 * Prepares AJAX endpoints for future live preview / AJAX save.
 */
final class SettingsBridge {

	/**
	 * Register AJAX routes (infrastructure only).
	 *
	 * @return void
	 */
	public static function register(): void {
		add_action( 'wp_ajax_kutby_regenerate_css', array( self::class, 'ajax_regenerate_css' ) );
		add_action( 'wp_ajax_kutby_save_options_ajax', array( self::class, 'ajax_save_options' ) );
	}

	/**
	 * Return dynamic CSS variables JSON for future live preview.
	 *
	 * @return void
	 */
	public static function ajax_regenerate_css(): void {
		check_ajax_referer( 'kutby_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'غير مصرح.' ), 403 );
		}

		wp_send_json_success(
			array(
				'css'    => Tokens::to_css(),
				'tokens' => Tokens::resolved(),
			)
		);
	}

	/**
	 * AJAX save — same FieldRegistry::store() path as Admin forms.
	 *
	 * @return void
	 */
	public static function ajax_save_options(): void {
		check_ajax_referer( 'kutby_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'غير مصرح.' ), 403 );
		}

		$raw     = isset( $_POST['kutby'] ) && is_array( $_POST['kutby'] ) ? wp_unslash( $_POST['kutby'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$current = Manager::all();
		$groups  = array();

		foreach ( $raw as $group => $fields ) {
			if ( ! is_array( $fields ) ) {
				continue;
			}
			$group_key             = sanitize_key( (string) $group );
			$current[ $group_key ] = $fields;
			$groups[]              = $group_key;
		}

		$result = FieldRegistry::store( $current, $groups, array( 'via' => 'ajax' ) );
		if ( is_array( $result ) ) {
			wp_send_json_error(
				array(
					'message' => implode( ' ', $result ),
					'errors'  => $result,
				),
				422
			);
		}

		wp_send_json_success(
			array(
				'message' => 'تم حفظ الإعدادات بنجاح.',
				'css'     => Tokens::to_css(),
			)
		);
	}
}
