<?php
/**
 * Admin Forms handler.
 *
 * @package GoValid_QR
 */

defined( 'ABSPATH' ) || exit;

class GoValid_Admin_Forms {

	/**
	 * Register hooks.
	 */
	public function register(): void {
		add_action( 'admin_post_govalid_save_form', array( $this, 'handle_save_form' ) );
		add_action( 'admin_post_govalid_delete_form', array( $this, 'handle_delete_form' ) );
	}

	/**
	 * Handle form save (admin_post).
	 */
	public function handle_save_form(): void {
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_die( esc_html__( 'Unauthorized', 'govalid-qr-validator' ), 403 );
		}

		check_admin_referer( 'govalid_save_form' );

		$form_id = absint( $_POST['form_id'] ?? 0 );
		$title   = sanitize_text_field( wp_unslash( $_POST['form_title'] ?? '' ) );
		$status  = sanitize_key( $_POST['form_status'] ?? 'draft' );

		$data = array(
			'title'  => $title,
			'status' => $status,
		);

		if ( $form_id ) {
			GoValid_Form_Model::update_form( $form_id, $data );
		} else {
			// Enforce form limit for free users.
			if ( $this->is_form_limit_reached() ) {
				wp_safe_redirect( add_query_arg( array(
					'page'  => 'govalid-qr-forms',
					'error' => 'form_limit',
							'_wpnonce' => wp_create_nonce( 'govalid-admin' ),
		), admin_url( 'admin.php' ) ) );
				exit;
			}
			$form_id = GoValid_Form_Model::create_form( $data );
		}

		wp_safe_redirect( add_query_arg( array(
			'page'    => 'govalid-qr-form-builder',
			'form_id' => $form_id,
			'saved'   => 1,
					'_wpnonce' => wp_create_nonce( 'govalid-admin' ),
		), admin_url( 'admin.php' ) ) );
		exit;
	}

	/**
	 * Check if form creation limit is reached.
	 *
	 * @return bool True if limit reached (free user with 1+ forms).
	 */
	private function is_form_limit_reached(): bool {
		$count = GoValid_Form_Model::count_forms();
		if ( $count < 1 ) {
			return false;
		}

		if ( ! GoValid_QR::is_connected() ) {
			return true;
		}

		$api    = new GoValid_QR_API();
		$result = $api->get_subscription();
		if ( is_wp_error( $result ) ) {
			return true;
		}

		$data = $result['data'] ?? $result;
		$sub  = $data['subscription'] ?? array();
		$plan = $sub['plan'] ?? array();
		$tier = $plan['tier'] ?? 'FREE';

		return 'FREE' === $tier;
	}

	/**
	 * Handle form delete (admin_post).
	 */
	public function handle_delete_form(): void {
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_die( esc_html__( 'Unauthorized', 'govalid-qr-validator' ), 403 );
		}

		// form_id must be read before check_admin_referer because it is part of the nonce action name.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified on the next line using this value.
		$form_id = absint( $_GET['form_id'] ?? 0 );
		check_admin_referer( 'govalid_delete_form_' . $form_id );

		if ( $form_id ) {
			GoValid_Form_Model::delete_form( $form_id );
		}

		wp_safe_redirect( add_query_arg( array(
			'page'    => 'govalid-qr-forms',
			'deleted' => 1,
					'_wpnonce' => wp_create_nonce( 'govalid-admin' ),
		), admin_url( 'admin.php' ) ) );
		exit;
	}
}
