<?php
/**
 * Email Settings REST API Controller.
 *
 * @package Ugcify\Admin\API
 */

namespace Ugcify\Admin\API;

use Ugcify\Email\EmailSettings;
use Ugcify\Email\ReviewRequestSettings;
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 EmailSettingsAPI
 */
class EmailSettingsAPI extends WP_REST_Controller {

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

	/**
	 * Rest base.
	 *
	 * @var string
	 */
	protected $rest_base = 'settings/email';

	/**
	 * Register routes.
	 */
	public function register_routes() {
		// Get all email types.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/types',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_email_types' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);

		// Update a single email type.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/types/(?P<type>[a-z_]+)',
			array(
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_email_type' ),
					'permission_callback' => array( $this, 'check_permission' ),
					'args'                => array(
						'type' => array(
							'required'          => true,
							'validate_callback' => function ( $param ) {
								return is_string( $param ) && ! empty( $param );
							},
						),
					),
				),
			)
		);

		// Toggle email type enabled/disabled.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/types/(?P<type>[a-z_]+)/toggle',
			array(
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'toggle_email_type' ),
					'permission_callback' => array( $this, 'check_permission' ),
					'args'                => array(
						'type' => array(
							'required'          => true,
							'validate_callback' => function ( $param ) {
								return is_string( $param ) && ! empty( $param );
							},
						),
					),
				),
			)
		);

		// Get global email settings.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/global',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_global_settings' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_global_settings' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);

		// Review request scheduler settings.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/review-request',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_review_request_settings' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_review_request_settings' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);
	}

	/**
	 * Check permission — 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;
	}

	/**
	 * Get all email types with their configuration.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_email_types( $request ) {
		$types = EmailSettings::get_email_types();

		// Add available placeholders to each type.
		$result = array();
		foreach ( $types as $key => $type ) {
			$type['key']          = $key;
			$type['placeholders'] = EmailSettings::get_available_placeholders( $key );
			$result[]             = $type;
		}

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

	/**
	 * Update a single email type (subject and body).
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_email_type( $request ) {
		$type   = $request->get_param( 'type' );
		$params = $request->get_json_params();

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

		// Verify the email type exists.
		$existing = EmailSettings::get_email_type( $type );
		if ( ! $existing ) {
			return new WP_Error(
				'invalid_type',
				__( 'Invalid email type.', 'ugcify' ),
				array( 'status' => 404 )
			);
		}

		$result = EmailSettings::save_email_type( $type, $params );

		if ( ! $result ) {
			return new WP_Error(
				'update_failed',
				__( 'Failed to update email settings.', 'ugcify' ),
				array( 'status' => 500 )
			);
		}

		$updated = EmailSettings::get_email_type( $type );
		$updated['key']          = $type;
		$updated['placeholders'] = EmailSettings::get_available_placeholders( $type );

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => __( 'Email settings saved.', 'ugcify' ),
				'data'    => $updated,
			)
		);
	}

	/**
	 * Toggle email type enabled/disabled.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function toggle_email_type( $request ) {
		$type   = $request->get_param( 'type' );
		$params = $request->get_json_params();

		$enabled = isset( $params['enabled'] ) ? (bool) $params['enabled'] : false;

		$existing = EmailSettings::get_email_type( $type );
		if ( ! $existing ) {
			return new WP_Error(
				'invalid_type',
				__( 'Invalid email type.', 'ugcify' ),
				array( 'status' => 404 )
			);
		}

		$result = EmailSettings::toggle_email_type( $type, $enabled );

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => $enabled
					? __( 'Email enabled.', 'ugcify' )
					: __( 'Email disabled.', 'ugcify' ),
				'data'    => array(
					'type'    => $type,
					'enabled' => $enabled,
				),
			)
		);
	}

	/**
	 * Get global email settings.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_global_settings( $request ) {
		$settings = EmailSettings::get_global_settings();

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

	/**
	 * Update global email settings.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_global_settings( $request ) {
		$params = $request->get_json_params();

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

		$result = EmailSettings::save_global_settings( $params );

		if ( ! $result ) {
			return new WP_Error(
				'update_failed',
				__( 'Failed to save global settings.', 'ugcify' ),
				array( 'status' => 500 )
			);
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => __( 'Global email settings saved.', 'ugcify' ),
				'data'    => EmailSettings::get_global_settings(),
			)
		);
	}

	/**
	 * Get review request scheduler settings.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_review_request_settings( $request ) {
		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => ReviewRequestSettings::get(),
			)
		);
	}

	/**
	 * Update review request scheduler settings.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_review_request_settings( $request ) {
		$params = $request->get_json_params();

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

		$result = ReviewRequestSettings::save( $params );

		if ( ! $result ) {
			return new WP_Error(
				'update_failed',
				__( 'Failed to save review request settings.', 'ugcify' ),
				array( 'status' => 500 )
			);
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'message' => __( 'Review request settings saved.', 'ugcify' ),
				'data'    => ReviewRequestSettings::get(),
			)
		);
	}
}
