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

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

add_action( 'rest_api_init', 'newsai_register_dashboard_rest_routes' );

if ( ! function_exists( 'newsai_register_dashboard_rest_routes' ) ) {
	function newsai_register_dashboard_rest_routes() {
		register_rest_route(
			'newsroom-os/v1',
			'/dashboard',
			[
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => 'newsai_rest_get_dashboard',
				'permission_callback' => 'newsai_rest_dashboard_can_view',
			]
		);
	}
}

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

if ( ! function_exists( 'newsai_rest_get_dashboard' ) ) {
	function newsai_rest_get_dashboard() {
		if ( ! function_exists( 'newsai_dashboard_registry_payload' ) ) {
			return new WP_REST_Response( [ 'error' => 'registry_missing' ], 500 );
		}
		try {
			return new WP_REST_Response( newsai_dashboard_registry_payload(), 200 );
		} catch ( \Throwable $e ) {
			return new WP_REST_Response(
				[
					'code'    => 'payload_error',
					'message' => $e->getMessage() . ' @ ' . basename( $e->getFile() ) . ':' . $e->getLine(),
				],
				500
			);
		}
	}
}

add_action( 'wp_ajax_newsai_dashboard_registry_get', 'newsai_ajax_dashboard_registry_get' );

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

add_action( 'wp_ajax_newsai_dashboard_radar_trends', 'newsai_ajax_dashboard_radar_trends' );

if ( ! function_exists( 'newsai_ajax_dashboard_radar_trends' ) ) {
	function newsai_ajax_dashboard_radar_trends() {
		check_ajax_referer( 'newsai_ajax_nonce', 'nonce' );
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( [ 'message' => __( 'Forbidden.', 'newsroom-ai-assistant' ) ], 403 );
		}
		$geo = isset( $_POST['geo'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['geo'] ) ) : '';
		if ( ! function_exists( 'newsai_dashboard_registry_radar_trends' ) ) {
			wp_send_json_error( [ 'message' => 'unavailable' ], 500 );
		}
		wp_send_json_success( newsai_dashboard_registry_radar_trends( $geo ) );
	}
}

add_action( 'wp_ajax_newsai_dashboard_radar_news', 'newsai_ajax_dashboard_radar_news' );

if ( ! function_exists( 'newsai_ajax_dashboard_radar_news' ) ) {
	function newsai_ajax_dashboard_radar_news() {
		check_ajax_referer( 'newsai_ajax_nonce', 'nonce' );
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( [ 'message' => __( 'Forbidden.', 'newsroom-ai-assistant' ) ], 403 );
		}
		$geo = isset( $_POST['geo'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['geo'] ) ) : '';
		if ( $geo === '' && function_exists( 'newsai_get_target_geo' ) ) {
			$geo = newsai_get_target_geo();
		}
		$cache_key = 'nros_news_json_' . sanitize_key( $geo );
		$cached    = get_transient( $cache_key );
		if ( is_array( $cached ) ) {
			wp_send_json_success( $cached );
		}
		if ( ! function_exists( 'newsai_google_news_get_sidebar_html' ) ) {
			wp_send_json_error( [ 'message' => __( 'News module unavailable.', 'newsroom-ai-assistant' ) ], 500 );
		}
		$result = newsai_google_news_get_sidebar_html( $geo );
		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}
		$html = is_array( $result ) ? (string) ( $result['html'] ?? '' ) : (string) $result;
		$items = [];
		if ( preg_match_all( '/<a[^>]+href=["\']([^"\']+)["\'][^>]*>([^<]+)<\/a>/i', $html, $m, PREG_SET_ORDER ) ) {
			foreach ( array_slice( $m, 0, 8 ) as $match ) {
				$items[] = [
					'title' => wp_strip_all_tags( $match[2] ),
					'url'   => esc_url_raw( $match[1] ),
				];
			}
		}
		$payload = [ 'items' => $items, 'stale' => ! empty( $result['stale'] ) ];
		set_transient( $cache_key, $payload, 5 * MINUTE_IN_SECONDS );
		wp_send_json_success( $payload );
	}
}

if ( ! function_exists( 'newsai_ajax_dashboard_registry_get' ) ) {
	function newsai_ajax_dashboard_registry_get() {
		newsai_ajax_dashboard_registry_verify();
		if ( ! function_exists( 'newsai_dashboard_registry_payload' ) ) {
			wp_send_json_error( [ 'message' => 'registry_missing' ], 500 );
		}
		try {
			wp_send_json_success( newsai_dashboard_registry_payload() );
		} catch ( \Throwable $e ) {
			wp_send_json_error(
				[ 'message' => $e->getMessage() . ' @ ' . basename( $e->getFile() ) . ':' . $e->getLine() ],
				500
			);
		}
	}
}

add_action( 'wp_ajax_newsai_save_editorial_task', 'newsai_ajax_save_editorial_task' );
add_action( 'wp_ajax_newsai_delete_editorial_task', 'newsai_ajax_delete_editorial_task' );

if ( ! function_exists( 'newsai_ajax_save_editorial_task' ) ) {
	function newsai_ajax_save_editorial_task() {
		check_ajax_referer( 'newsai_add_alert_action', 'task_nonce' );
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( [ 'message' => __( 'Forbidden.', 'newsroom-ai-assistant' ) ], 403 );
		}
		if ( ! function_exists( 'newsai_dashboard_save_task' ) ) {
			wp_send_json_error( [ 'message' => 'unavailable' ], 500 );
		}
		$input = [
			'task_id'    => isset( $_POST['task_id'] ) ? (int) wp_unslash( $_POST['task_id'] ) : 0,
			'title'      => isset( $_POST['title'] ) ? wp_unslash( (string) $_POST['title'] ) : '',
			'keyword'    => isset( $_POST['keyword'] ) ? wp_unslash( (string) $_POST['keyword'] ) : '',
			'notes'      => isset( $_POST['notes'] ) ? wp_unslash( (string) $_POST['notes'] ) : '',
			'ref_link'   => isset( $_POST['ref_link'] ) ? wp_unslash( (string) $_POST['ref_link'] ) : '',
			'task_date'  => isset( $_POST['task_date'] ) ? wp_unslash( (string) $_POST['task_date'] ) : '',
			'author_id'  => isset( $_POST['author_id'] ) ? (int) wp_unslash( $_POST['author_id'] ) : 0,
			'lead_days'  => isset( $_POST['lead_days'] ) ? (int) wp_unslash( $_POST['lead_days'] ) : 7,
			'recurrence' => isset( $_POST['recurrence'] ) ? wp_unslash( (string) $_POST['recurrence'] ) : 'yearly',
		];
		$result = newsai_dashboard_save_task( $input );
		if ( empty( $result['success'] ) ) {
			wp_send_json_error( [ 'message' => $result['message'] ?? 'error' ] );
		}
		$payload = function_exists( 'newsai_dashboard_registry_payload' ) ? newsai_dashboard_registry_payload() : [];
		wp_send_json_success(
			[
				'message' => $result['message'],
				'taskId'  => (int) ( $result['task_id'] ?? 0 ),
				'tasks'   => $payload['tasks'] ?? [],
			]
		);
	}
}

if ( ! function_exists( 'newsai_ajax_delete_editorial_task' ) ) {
	function newsai_ajax_delete_editorial_task() {
		check_ajax_referer( 'newsai_add_alert_action', 'task_nonce' );
		$task_id = isset( $_POST['task_id'] ) ? (int) wp_unslash( $_POST['task_id'] ) : 0;
		if ( ! function_exists( 'newsai_dashboard_delete_task' ) ) {
			wp_send_json_error( [ 'message' => 'unavailable' ], 500 );
		}
		$result = newsai_dashboard_delete_task( $task_id );
		if ( empty( $result['success'] ) ) {
			wp_send_json_error( [ 'message' => $result['message'] ?? 'error' ] );
		}
		$payload = function_exists( 'newsai_dashboard_registry_payload' ) ? newsai_dashboard_registry_payload() : [];
		wp_send_json_success(
			[
				'message' => $result['message'],
				'tasks'   => $payload['tasks'] ?? [],
			]
		);
	}
}
