<?php
/**
 * REST API — PRO license (newsroom-os/v1).
 *
 * @package Newsroom_AI_Assistant
 */

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

add_action( 'rest_api_init', 'newsai_register_pro_rest_routes' );

if ( ! function_exists( 'newsai_register_pro_rest_routes' ) ) {
	function newsai_register_pro_rest_routes() {
		register_rest_route(
			'newsroom-os/v1',
			'/pro',
			[
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => 'newsai_rest_get_pro',
				'permission_callback' => 'newsai_rest_pro_can_view',
			]
		);
		register_rest_route(
			'newsroom-os/v1',
			'/pro/action',
			[
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => 'newsai_rest_pro_license_action',
				'permission_callback' => 'newsai_rest_pro_can_manage',
			]
		);
	}
}

if ( ! function_exists( 'newsai_rest_pro_can_view' ) ) {
	function newsai_rest_pro_can_view() {
		return current_user_can( 'edit_posts' );
	}
}

if ( ! function_exists( 'newsai_rest_pro_can_manage' ) ) {
	function newsai_rest_pro_can_manage() {
		return current_user_can( 'manage_options' );
	}
}

if ( ! function_exists( 'newsai_rest_get_pro' ) ) {
	function newsai_rest_get_pro() {
		if ( ! function_exists( 'newsai_pro_registry_payload' ) ) {
			return new WP_REST_Response( [ 'error' => 'registry_missing' ], 500 );
		}
		return new WP_REST_Response( newsai_pro_registry_payload(), 200 );
	}
}

if ( ! function_exists( 'newsai_pro_registry_handle_action' ) ) {
	/**
	 * @param string $action activate|refresh|deactivate
	 * @param array  $input  key, email
	 * @return array{success:bool,message:string,payload?:array}
	 */
	function newsai_pro_registry_handle_action( $action, $input = [] ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return [
				'success' => false,
				'message' => __( 'Forbidden.', 'newsroom-ai-assistant' ),
			];
		}
		$action = sanitize_key( (string) $action );
		if ( $action === 'activate' && function_exists( 'newsai_pro_activate_license' ) ) {
			$key = isset( $input['key'] ) ? (string) $input['key'] : '';
			$em  = isset( $input['email'] ) ? sanitize_email( (string) $input['email'] ) : '';
			$res = newsai_pro_activate_license( $key, $em );
			return [
				'success' => ! empty( $res['success'] ),
				'message' => (string) ( $res['message'] ?? '' ),
				'payload' => function_exists( 'newsai_pro_registry_payload' ) ? newsai_pro_registry_payload() : [],
			];
		}
		if ( $action === 'refresh' && function_exists( 'newsai_pro_refresh_license' ) ) {
			$res = newsai_pro_refresh_license();
			return [
				'success' => ! empty( $res['success'] ),
				'message' => (string) ( $res['message'] ?? __( 'License verified.', 'newsroom-ai-assistant' ) ),
				'payload' => function_exists( 'newsai_pro_registry_payload' ) ? newsai_pro_registry_payload() : [],
			];
		}
		if ( $action === 'deactivate' && function_exists( 'newsai_pro_deactivate_license' ) ) {
			$res = newsai_pro_deactivate_license();
			return [
				'success' => ! empty( $res['success'] ),
				'message' => (string) ( $res['message'] ?? __( 'License deactivated.', 'newsroom-ai-assistant' ) ),
				'payload' => function_exists( 'newsai_pro_registry_payload' ) ? newsai_pro_registry_payload() : [],
			];
		}
		return [
			'success' => false,
			'message' => __( 'Unknown action.', 'newsroom-ai-assistant' ),
		];
	}
}

if ( ! function_exists( 'newsai_rest_pro_license_action' ) ) {
	function newsai_rest_pro_license_action( WP_REST_Request $request ) {
		$action = sanitize_key( (string) $request->get_param( 'license_action' ) );
		$input  = [
			'key'   => (string) $request->get_param( 'key' ),
			'email' => (string) $request->get_param( 'email' ),
		];
		$result = newsai_pro_registry_handle_action( $action, $input );
		if ( empty( $result['success'] ) ) {
			return new WP_REST_Response( $result, 400 );
		}
		return new WP_REST_Response( $result, 200 );
	}
}

add_action( 'wp_ajax_newsai_pro_registry_get', 'newsai_ajax_pro_registry_get' );
add_action( 'wp_ajax_newsai_pro_license_action', 'newsai_ajax_pro_license_action' );

if ( ! function_exists( 'newsai_ajax_pro_registry_get' ) ) {
	function newsai_ajax_pro_registry_get() {
		check_ajax_referer( 'newsai_ajax_nonce', 'nonce' );
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( [ 'message' => __( 'Forbidden.', 'newsroom-ai-assistant' ) ], 403 );
		}
		if ( ! function_exists( 'newsai_pro_registry_payload' ) ) {
			wp_send_json_error( [ 'message' => 'registry_missing' ], 500 );
		}
		wp_send_json_success( newsai_pro_registry_payload() );
	}
}

if ( ! function_exists( 'newsai_ajax_pro_license_action' ) ) {
	function newsai_ajax_pro_license_action() {
		check_ajax_referer( 'newsai_pro_license_save', 'license_nonce' );
		$action = isset( $_POST['license_action'] ) ? sanitize_key( wp_unslash( (string) $_POST['license_action'] ) ) : '';
		$input  = [
			'key'   => isset( $_POST['key'] ) ? wp_unslash( (string) $_POST['key'] ) : '',
			'email' => isset( $_POST['email'] ) ? wp_unslash( (string) $_POST['email'] ) : '',
		];
		$result = newsai_pro_registry_handle_action( $action, $input );
		if ( empty( $result['success'] ) ) {
			wp_send_json_error( [ 'message' => $result['message'] ?? 'error' ] );
		}
		wp_send_json_success( $result );
	}
}
