<?php
/**
 * Setup Wizard REST API Controller.
 *
 * Handles saving all wizard settings in a single request.
 *
 * @package Ugcify\Admin\API
 */

namespace Ugcify\Admin\API;

use Ugcify\Email\EmailSettings;
use Ugcify\Migration\ReviewMigrationService;
use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class SetupWizardAPI
 */
class SetupWizardAPI extends WP_REST_Controller {

	/**
	 * Namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'ugcify/v1';

	/**
	 * Rest base.
	 *
	 * @var string
	 */
	protected $rest_base = 'setup-wizard';

	/**
	 * Register routes.
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/complete',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'complete' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);
	}

	/**
	 * Permission callback — requires manage_options.
	 *
	 * @return bool|WP_Error
	 */
	public function check_permission() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				'rest_forbidden',
				__( 'Sorry, you are not allowed to access this resource.', 'ugcify' ),
				array( 'status' => 403 )
			);
		}
		return true;
	}

	/**
	 * Handle setup wizard completion.
	 *
	 * Saves all wizard data to the appropriate WordPress options
	 * and optionally starts a review migration job.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function complete( $request ) {
		$params = $request->get_json_params();

		if ( empty( $params ) ) {
			return new WP_Error(
				'invalid_data',
				__( 'Invalid wizard data.', 'ugcify' ),
				array( 'status' => 400 )
			);
		}

		// 1. Save consent / opt-in data.
		$this->save_consent( $params );

		// 2. Save review template settings (enable/disable widget).
		$this->save_review_template_settings( $params );

		// 3. Save template customization (colors, widgetType).
		$this->save_template_customization( $params );

		// 4. Save email global settings (logo).
		$this->save_email_logo( $params );

		// 5. Save reward settings.
		$this->save_reward_settings( $params );

		// 6. Mark wizard as completed.
		update_option( 'ugcify_setup_wizard_completed', true );

		// 7. Start migration if requested.
		$migration_job_id = null;
		if ( ! empty( $params['wantToMigrate'] ) ) {
			$migration_job_id = $this->start_migration();
		}

		$response_data = array(
			'message' => __( 'Setup wizard completed successfully.', 'ugcify' ),
		);

		if ( $migration_job_id ) {
			$response_data['migration_job_id'] = $migration_job_id;
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => $response_data,
			)
		);
	}

	/**
	 * Save consent/opt-in data.
	 *
	 * @param array $params Wizard parameters.
	 */
	private function save_consent( $params ) {
		$consent = array(
			'opt_in'      => ! empty( $params['optIn'] ),
			'admin_name'  => sanitize_text_field( $params['adminName'] ?? '' ),
			'admin_email' => sanitize_email( $params['adminEmail'] ?? '' ),
			'site_url'    => esc_url_raw( $params['siteUrl'] ?? '' ),
			'created_at'  => current_time( 'mysql' ),
		);

		update_option( 'ugcify_consent', $consent );
	}

	/**
	 * Save review template settings.
	 *
	 * @param array $params Wizard parameters.
	 */
	private function save_review_template_settings( $params ) {
		$enable_widget = ! empty( $params['enableWidget'] );
		$widget_type   = isset( $params['widgetType'] ) ? sanitize_text_field( $params['widgetType'] ) : 'masonry';
		$is_reels      = 'reels' === $widget_type;

		$active_id = '';
		if ( $enable_widget ) {
			$active_id = $is_reels ? 'reels' : 'minimal_grid';
		}

		$settings = array(
			'version'          => 1,
			'activeTemplateId' => $active_id,
			'templates'        => array(
				'minimal_grid' => array(
					'enabled' => $enable_widget && ! $is_reels,
				),
				'reels'        => array(
					'enabled' => $enable_widget && $is_reels,
				),
			),
		);

		update_option( 'ugcify_review_template_settings', $settings );
	}

	/**
	 * Save template customization settings (colors, widget type).
	 *
	 * @param array $params Wizard parameters.
	 */
	private function save_template_customization( $params ) {
		$current = get_option( 'ugcify_template_customization', array() );

		$updates = array();

		if ( isset( $params['enableWidget'] ) ) {
			$updates['enableWidget'] = ! empty( $params['enableWidget'] );
		}

		if ( isset( $params['primaryColor'] ) ) {
			$color = sanitize_hex_color( $params['primaryColor'] );
			if ( $color ) {
				$updates['primaryColor'] = $color;
			}
		}

		if ( isset( $params['ratingColor'] ) ) {
			$color = sanitize_hex_color( $params['ratingColor'] );
			if ( $color ) {
				$updates['ratingColor'] = $color;
			}
		}

		if ( isset( $params['titleColor'] ) ) {
			$color = sanitize_hex_color( $params['titleColor'] );
			if ( $color ) {
				$updates['titleColor'] = $color;
			}
		}

		if ( isset( $params['widgetType'] ) ) {
			$allowed_types = array( 'grid', 'list', 'masonry', 'reels', 'slider' );
			$type          = sanitize_text_field( $params['widgetType'] );
			if ( in_array( $type, $allowed_types, true ) ) {
				$updates['widgetType'] = $type;
				if ( 'grid' === $type ) {
					$updates['gridStyle'] = 'uniform_grid';
				} elseif ( 'masonry' === $type ) {
					$updates['gridStyle'] = 'masonry';
				}
			}
		}

		if ( ! empty( $updates ) ) {
			$new_settings = array_merge(
				is_array( $current ) ? $current : array(),
				$updates
			);
			update_option( 'ugcify_template_customization', $new_settings );
		}
	}

	/**
	 * Save logo to email global settings.
	 *
	 * @param array $params Wizard parameters.
	 */
	private function save_email_logo( $params ) {
		if ( ! isset( $params['logoUrl'] ) ) {
			return;
		}

		require_once UGCIFY_PATH . 'includes/Email/EmailSettings.php';

		$current              = EmailSettings::get_global_settings();
		$current['header_logo'] = esc_url_raw( $params['logoUrl'] );

		EmailSettings::save_global_settings( $current );
	}

	/**
	 * Save reward/discount settings.
	 *
	 * @param array $params Wizard parameters.
	 */
	private function save_reward_settings( $params ) {
		$enabled = ! empty( $params['enableDiscount'] );

		// Map wizard discount type to WooCommerce coupon type.
		$coupon_type_map = array(
			'flat'       => 'fixed_cart',
			'percentage' => 'percent',
		);

		$discount_type = isset( $params['discountType'] ) ? $params['discountType'] : 'flat';
		$coupon_type   = isset( $coupon_type_map[ $discount_type ] ) ? $coupon_type_map[ $discount_type ] : 'fixed_cart';

		$settings = array(
			'enabled'      => $enabled,
			'reward_type'  => 'coupon',
			'coupon_type'  => $coupon_type,
			'coupon_value' => isset( $params['discountValue'] ) ? abs( floatval( $params['discountValue'] ) ) : 0,
		);

		update_option( 'ugcify_reward_settings', $settings, true );
	}

	/**
	 * Start review migration from WooCommerce to UGC.
	 *
	 * @return int|null Migration job ID, or null on failure.
	 */
	private function start_migration() {
		try {
			require_once UGCIFY_PATH . 'includes/Review/ReviewMeta.php';
			require_once UGCIFY_PATH . 'includes/Migration/ReviewMigrationService.php';

			$service = new ReviewMigrationService();
			$result  = $service->start_job( 'wc_to_ugc' );

			if ( is_wp_error( $result ) ) {
				return null;
			}

			// Process the first batch immediately.
			if ( isset( $result['id'] ) ) {
				$service->process_job( $result['id'] );
				return $result['id'];
			}

			return null;
		} catch ( \Exception $e ) {
			return null;
		}
	}
}
