<?php
/**
 * AdminSaveHook class.
 *
 * Registers save_post hook for PowerWidget CPT and dispatches form handlers.
 *
 * @package Ilabs\Firevert\Modules\PowerWidget\Hooks\Admin
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\PowerWidget\Hooks\Admin;

use Ilabs\Firevert\Core\Form\FormHandler;
use Ilabs\Firevert\Modules\PowerWidget\Services\Type\ModuleType;
use Ilabs\Firevert\Modules\PowerWidget\Services\Type\SectionType;

/**
 * Class AdminSaveHook
 *
 * Saves data from all module forms on CPT save.
 */
final class AdminSaveHook {

	/**
	 * Registers the hook to handle save_post.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action(
			'admin_post_firevert_save_power_widget',
			array( $this, 'handle_save' ),
			10,
			2
		);
	}

	/**
	 * Calls all form handlers on post save.
	 *
	 * @return void
	 */
	public function handle_save(): void {
		if (
			! isset( $_POST['firevert_power_widget_nonce'] ) ||
			! wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_POST['firevert_power_widget_nonce'] ) ),
				'firevert_power_widget_save'
			)
		) {
			wp_die( esc_html__( 'Security check failed.', 'firevert' ) );
		}

		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'firevert' ) );
		}

		$post_id = isset( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : 0;

		if ( $post_id <= 0 ) {
			wp_die( esc_html__( 'Invalid or missing post ID.', 'firevert' ) );
		}

		$post = get_post( $post_id );

		if ( ! $post || ModuleType::MODULE_CPT !== $post->post_type ) {
			wp_die( esc_html__( 'Invalid post type.', 'firevert' ) );
		}

		$section = isset( $_POST['section'] ) ? sanitize_key( wp_unslash( $_POST['section'] ) ) : SectionType::SETTINGS;

		$handler_class = SectionType::get_handler( $section );

		if ( $handler_class && class_exists( $handler_class ) ) {
			/**
			 * Form Handler Class
			 *
			 * @var FormHandler $handler
			 */
			$handler = new $handler_class( $post );
			$handler->save();
		}

		wp_safe_redirect(
			add_query_arg(
				array(
					'page'    => 'firevert',
					'tab'     => 'modules',
					'module'  => ModuleType::MODULE_SLUG,
					'section' => $section,
					'saved'   => '1',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}
}
