<?php

defined( 'ABSPATH' ) || exit;

class Radio_Player_Ajax {

	private static $instance = null;

	public function __construct() {

		// Register all AJAX endpoints
		add_action( 'wp_ajax_rp_get_players', [ $this, 'get_players' ] );
		add_action( 'wp_ajax_rp_update_player', [ $this, 'update_player' ] );
		add_action( 'wp_ajax_rp_delete_player', [ $this, 'delete_player' ] );
		add_action( 'wp_ajax_rp_update_settings', [ $this, 'update_settings' ] );
		add_action( 'wp_ajax_rp_get_export_data', [ $this, 'export_data' ] );
		add_action( 'wp_ajax_rp_import_data', [ $this, 'import_data' ] );
		add_action( 'wp_ajax_rp_get_pages', [ $this, 'get_pages' ] );
		add_action( 'wp_ajax_rp_create_page', [ $this, 'create_page' ] );
		add_action( 'wp_ajax_radio_player_hide_review_notice', [ $this, 'hide_review_notice' ] );
		add_action( 'wp_ajax_radio_player_review_feedback', [ $this, 'handle_review_feedback' ] );
		add_action( 'wp_ajax_radio_player_get_streams_data', [ $this, 'get_streams_data' ] );
		add_action( 'wp_ajax_nopriv_radio_player_get_streams_data', [ $this, 'get_streams_data' ] );
	}

	/*--------------------------------------------------------------
	# PAGE CREATION
	--------------------------------------------------------------*/
	public function create_page() {
		check_ajax_referer( 'radio-player', 'nonce' );

		if ( ! current_user_can( 'edit_pages' ) ) {
			wp_send_json_error( esc_html__( 'Permission denied.', 'radio-player' ) );
		}

		$title     = sanitize_text_field( $_POST['title'] ?? '' );
		$player_id = absint( $_POST['id'] ?? 0 );

		$post_type = 'page';
		$content   = function_exists( 'use_block_editor_for_post_type' ) && use_block_editor_for_post_type( $post_type )
			? sprintf( '<!-- wp:radio-player/radio-player {"id":%d} /-->', $player_id )
			: sprintf( '[radio_player id="%d"]', $player_id );

		$page_id = wp_insert_post( [
			'post_title'   => $title,
			'post_content' => $content,
			'post_status'  => 'draft',
			'post_type'    => $post_type,
		] );

		is_wp_error( $page_id )
			? wp_send_json_error( $page_id->get_error_message() )
			: wp_send_json_success( [ 'id' => $page_id, 'title' => $title ] );
	}

	/*--------------------------------------------------------------
	# GET PAGES
	--------------------------------------------------------------*/
	public function get_pages() {
		check_ajax_referer( 'radio-player', 'nonce' );

		$pages = get_posts( [
			'post_type'      => 'page',
			'post_status'    => 'publish',
			'posts_per_page' => 999,
			'fields'         => [ 'ID', 'post_title' ],
		] );

		if ( empty( $pages ) ) {
			wp_send_json_success( [] );
		}

		$formatted = array_map(
			function ( $page ) {
				return [ 'id' => $page->ID, 'title' => esc_html( $page->post_title ) ];
			},
			$pages
		);

		wp_send_json_success( $formatted );
	}

	public function get_streams_data() {
		check_ajax_referer( 'radio-player', 'nonce' );

		$streams = ! empty( $_REQUEST['streams'] )
			? array_filter( array_map( 'sanitize_text_field', wp_unslash( (array) $_REQUEST['streams'] ) ) )
			: [];

		if ( empty( $streams ) ) {
			wp_send_json_error( esc_html__( 'No URL provided!', 'radio-player' ) );
		}

		$data = [];
		foreach ( $streams as $stream ) {
			$instance        = new Radio_Player_Stream_Data( $stream );
			$data[ $stream ] = $instance->get_stream_data();
		}

		wp_send_json_success( $data );
	}

	/*--------------------------------------------------------------
	# REVIEW FEEDBACK
	--------------------------------------------------------------*/
	public function hide_review_notice() {
		check_ajax_referer( 'radio-player', 'nonce' );
		update_option( 'radio_player_rating_notice', 'off' );
	}

	public function handle_review_feedback() {
		check_ajax_referer( 'radio-player', 'nonce' );

		$feedback = sanitize_textarea_field( $_POST['feedback'] ?? '' );
		if ( empty( $feedback ) ) {
			wp_send_json_error();
		}

		$website_url = get_bloginfo( 'url' );
		$body        = sprintf(
		               /* translators: Site URL */
			               esc_html__( 'Feedback: %s', 'radio-player' ), $feedback ) . '<br>';
		$body        .= sprintf(
		/* translators: Site URL */
			esc_html__( 'Website URL: %s', 'radio-player' ), $website_url );

		$subject = sprintf(
		/* translators: Plugin Name */
			esc_html__( 'Feedback for %s', 'radio-player' ), 'Radio Player' );
		$headers = [
			'Content-Type: text/html; charset=UTF-8',
			'From: ' . get_bloginfo( 'name' ) . ' <' . get_bloginfo( 'admin_email' ) . '>',
		];

		wp_mail( 'israilahmed5@gmail.com', $subject, $body, $headers );
		$this->hide_review_notice();
		wp_send_json_success();
	}

	/*--------------------------------------------------------------
	# IMPORT / EXPORT (SAFE FOR CROSS-SITE)
	--------------------------------------------------------------*/
	public function import_data() {
		check_ajax_referer( 'radio-player', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( __( 'You do not have permission to import data', 'radio-player' ) );
		}

		$post_data       = isset( $_POST['data'] ) ? radio_player_sanitize_array( $_POST['data'] ) : [];
		$import_settings = ! empty( $post_data['settings'] ) ? radio_player_sanitize_array( $post_data['settings'] ) : [];
		$import_players  = ! empty( $post_data['players'] ) ? radio_player_sanitize_array( $post_data['players'] ) : [];

		/*--------------------------------------------------------------
		# MERGE SETTINGS
		--------------------------------------------------------------*/
		if ( ! empty( $import_settings ) ) {
			$current_settings = get_option( 'radio_player_settings', [] );

			$merged_settings = array_merge(
				is_array( $current_settings ) ? $current_settings : [],
				$import_settings
			);

			update_option( 'radio_player_settings', $merged_settings );
		}

		/*--------------------------------------------------------------
		# IMPORT PLAYERS — ALWAYS INSERT NEW PLAYERS
		   Because imported IDs may conflict with existing IDs.
		--------------------------------------------------------------*/
		if ( ! empty( $import_players ) ) {

			foreach ( $import_players as $player ) {
				if ( ! is_array( $player ) ) {
					continue;
				}

				// Remove ID to force insert as a fresh new player
				unset( $player['id'] );
				if ( isset( $player['config']['id'] ) ) {
					unset( $player['config']['id'] );
				}

				// Insert new player
				$this->update_player( $player );
			}
		}

		wp_send_json_success();
	}


	public function export_data() {
		check_ajax_referer( 'radio-player', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to export data', 'radio-player' ) );
		}

		$type = ! empty( $_POST['type'] ) ? sanitize_text_field( $_POST['type'] ) : 'all';

		$data = [];

		if ( 'all' === $type || 'settings' === $type ) {
			$data['settings'] = radio_player_get_settings();
		}

		if ( 'all' === $type || 'players' === $type ) {
			$data['players'] = radio_player_get_players();
		}

		wp_send_json_success( $data );
	}

	/*--------------------------------------------------------------
	# GET PLAYERS
	--------------------------------------------------------------*/
	public function get_players() {
		check_ajax_referer( 'radio-player', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to get players', 'radio-player' ) );
		}

		$page     = absint( $_POST['page'] ?? 1 );
		$per_page = absint( $_POST['per_page'] ?? 999 );
		$order_by = sanitize_key( $_POST['sort_by'] ?? 'created_at' );
		$order    = sanitize_key( $_POST['sort_order'] ?? 'desc' );

		$offset = max( 0, ( $page - 1 ) * $per_page );

		global $wpdb;
		$table = $wpdb->prefix . 'radio_player_players';

		// Safe SQL query with placeholders
		$sql = $wpdb->prepare(
			"SELECT * FROM `{$table}` ORDER BY {$order_by} {$order} LIMIT %d, %d",
			$offset,
			$per_page
		);

		$players   = $wpdb->get_results( $sql, ARRAY_A );
		$formatted = array_map( 'radio_player_get_formatted_player', $players ?? [] );

		$total = count( $formatted );

		wp_send_json_success( [
			'players' => $formatted,
			'total'   => $total,
		] );
	}

	/*--------------------------------------------------------------
	# UPDATE / DELETE PLAYER
	--------------------------------------------------------------*/
	public function update_player( $data = null ) {
		check_ajax_referer( 'radio-player', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to update this player', 'radio-player' ) );
		}

		if ( ! $data ) {
			$posted = isset( $_POST['data'] )
				? radio_player_sanitize_array( json_decode( base64_decode( sanitize_text_field( $_POST['data'] ) ), true ) )
				: [];
		} else {
			$posted = $data;
		}

		$id     = absint( $posted['id'] ?? 0 );
		$title  = sanitize_text_field( $posted['title'] ?? '' );
		$status = ! empty( $posted['status'] ) ? 1 : 0;
		$config = $posted['config'] ?? $posted;

		global $wpdb;
		$table = $wpdb->prefix . 'radio_player_players';

		$insert_data = [
			'title'  => $title,
			'status' => $status,
			'config' => maybe_serialize( $config ),
		];

		if ( $id > 0 ) {
			$wpdb->update( $table, $insert_data, [ 'id' => $id ], [ '%s', '%d', '%s' ], [ '%d' ] );
		} else {
			$wpdb->insert( $table, $insert_data, [ '%s', '%d', '%s' ] );
			$id = $wpdb->insert_id;
		}

		$insert_data['id']     = $id;
		$insert_data['config'] = $config;

		return $data ? $insert_data : wp_send_json_success( $insert_data );
	}

	public function delete_player() {
		check_ajax_referer( 'radio-player', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to delete this player', 'radio-player' ) );
		}

		$player_id = absint( $_POST['id'] ?? 0 );

		global $wpdb;
		$table = $wpdb->prefix . 'radio_player_players';
		$wpdb->delete( $table, [ 'id' => $player_id ], [ '%d' ] );

		wp_send_json_success( [ 'success' => true ] );
	}

	/*--------------------------------------------------------------
	# SETTINGS
	--------------------------------------------------------------*/
	public function update_settings() {
		check_ajax_referer( 'radio-player', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You do not have permission to update settings', 'radio-player' ) );
		}

		$data = isset( $_POST['data'] ) ? radio_player_sanitize_array( $_POST['data'] ) : [];
		update_option( 'radio_player_settings', $data );

		wp_send_json_success( [ 'success' => true ] );
	}

	/*--------------------------------------------------------------
	# SINGLETON
	--------------------------------------------------------------*/
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}
}

Radio_Player_Ajax::instance();
