<?php
/**
 * Admin Playlist management.
 *
 * @package TheStudioPlayer
 */

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

/**
 * AJAX: Search playlists for selection.
 */
function thespl_ajax_search_playlists() {
	check_ajax_referer( 'thespl_muxer_nonce', 'nonce' );
	if ( ! thespl_current_user_can_policy( 'plugin_access' ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied', 'the-studio-player' ) ), 403 );
	}

	$term = '';
	if ( isset( $_POST['term'] ) ) {
		$term = sanitize_text_field( wp_unslash( $_POST['term'] ) );
	}

	$page = isset( $_POST['page'] ) ? absint( wp_unslash( $_POST['page'] ) ) : 1;
	if ( $page <= 0 ) {
		$page = 1;
	}

	$limit = isset( $_POST['per_page'] ) ? absint( wp_unslash( $_POST['per_page'] ) ) : 10;
	if ( $limit <= 0 ) {
		$limit = 10;
	}

	$args = array(
		'post_type'      => 'thespl_playlist',
		'post_status'    => array( 'publish', 'draft' ),
		's'              => $term,
		'posts_per_page' => $limit,
		'paged'          => $page,
		'orderby'        => 'modified',
		'order'          => 'DESC',
		'no_found_rows'  => false,
	);

	$q     = new WP_Query( $args );
	$items = array();
	if ( $q->have_posts() ) {
		foreach ( $q->posts as $p ) {
			$items[] = array(
				'id'       => (int) $p->ID,
				'title'    => get_the_title( $p ),
				'status'   => (string) $p->post_status,
				'modified' => (string) $p->post_modified,
			);
		}
	}

	$total    = (int) $q->found_posts;
	$pages    = $limit > 0 ? (int) ceil( $total / $limit ) : 1;
	$has_more = $page < $pages;

	wp_send_json_success(
		array(
			'items'   => $items,
			'page'    => $page,
			'perPage' => $limit,
			'total'   => $total,
			'more'    => $has_more,
		)
	);
}
add_action( 'wp_ajax_thespl_search_playlists', 'thespl_ajax_search_playlists' );

/**
 * AJAX: Append track to existing playlist.
 */
function thespl_ajax_append_track_to_playlist() {
	check_ajax_referer( 'thespl_muxer_nonce', 'nonce' );

	$playlist_id = isset( $_POST['playlist_id'] ) ? absint( wp_unslash( $_POST['playlist_id'] ) ) : 0;
	if ( $playlist_id <= 0 || ! current_user_can( 'edit_post', $playlist_id ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied', 'the-studio-player' ) ), 403 );
	}

	$title = '';
	if ( isset( $_POST['title'] ) ) {
		$title = sanitize_text_field( wp_unslash( $_POST['title'] ) );
	}

	$audio_id = isset( $_POST['audio_attachment_id'] ) ? absint( wp_unslash( $_POST['audio_attachment_id'] ) ) : 0;
	if ( $audio_id > 0 ) {
		$audio_file_path = get_attached_file( $audio_id );
		$audio_ext       = is_string( $audio_file_path ) ? strtolower( pathinfo( $audio_file_path, PATHINFO_EXTENSION ) ) : '';
		$audio_mime      = get_post_mime_type( $audio_id );
		$audio_mime      = is_string( $audio_mime ) ? strtolower( $audio_mime ) : '';
		$allowed_ext     = array( 'flac', 'wav' );
		$allowed_mime    = array( 'audio/flac', 'audio/x-flac', 'audio/wav', 'audio/x-wav', 'audio/wave', 'audio/vnd.wave' );
		if ( ! in_array( $audio_ext, $allowed_ext, true ) && ! in_array( $audio_mime, $allowed_mime, true ) ) {
			$audio_id = 0;
		}
	}
	$wave_id = isset( $_POST['waveform_attachment_id'] ) ? absint( wp_unslash( $_POST['waveform_attachment_id'] ) ) : 0;

	$raw     = get_post_meta( $playlist_id, '_thespl_playlist_json', true );
	$raw     = is_string( $raw ) ? $raw : '';
	$decoded = array();
	if ( '' !== $raw ) {
		$decoded = json_decode( $raw, true );
		$decoded = is_array( $decoded ) ? $decoded : array();
	}

	if ( ! isset( $decoded['tracks'] ) || ! is_array( $decoded['tracks'] ) ) {
		$decoded['tracks'] = array();
	}

	$variant_engine = thespl_get_variant_engine();
	$track_variants = $variant_engine->get_storage_fallback_variants( $decoded );

	$decoded['tracks'][] = array(
		'title'                  => $title,
		'artist'                 => '',
		'audio_attachment_id'    => $audio_id,
		'waveform_attachment_id' => $wave_id,
		'cover_attachment_id'    => 0,
		'variants'               => $track_variants,
	);

	$sanitized = thespl_sanitize_playlist_json_string( wp_json_encode( $decoded ) );
	update_post_meta( $playlist_id, '_thespl_playlist_json', $sanitized );

	wp_send_json_success( array( 'playlist_id' => $playlist_id ) );
}
add_action( 'wp_ajax_thespl_append_track_to_playlist', 'thespl_ajax_append_track_to_playlist' );

/**
 * AJAX: Create new playlist from uploaded track payload.
 */
function thespl_ajax_create_playlist_from_upload() {
	check_ajax_referer( 'thespl_muxer_nonce', 'nonce' );
	if ( ! thespl_current_user_can_policy( 'plugin_access' ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied', 'the-studio-player' ) ), 403 );
	}

	$title = '';
	if ( isset( $_POST['title'] ) ) {
		$title = sanitize_text_field( wp_unslash( $_POST['title'] ) );
	}

	$json_raw = '';
	if ( isset( $_POST['playlist_json'] ) && is_string( $_POST['playlist_json'] ) ) {
		$json_raw = sanitize_textarea_field( wp_unslash( $_POST['playlist_json'] ) );
	}
	$json = thespl_sanitize_playlist_json_string( $json_raw );

	$playlist_id = wp_insert_post(
		array(
			'post_type'   => 'thespl_playlist',
			'post_status' => 'draft',
			'post_title'  => ( '' !== $title ? $title : __( 'New Playlist', 'the-studio-player' ) ),
		)
	);
	if ( is_wp_error( $playlist_id ) ) {
		wp_send_json_error( array( 'message' => __( 'Failed to create playlist', 'the-studio-player' ) ), 500 );
	}

	if ( '' !== $json ) {
		update_post_meta( $playlist_id, '_thespl_playlist_json', $json );
	}

	wp_send_json_success( array( 'playlist_id' => (int) $playlist_id ) );
}
add_action( 'wp_ajax_thespl_create_playlist_from_upload', 'thespl_ajax_create_playlist_from_upload' );
