<?php

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

class MFP_Media_Query {

	public function register(): void {
		add_filter( 'ajax_query_attachments_args', [ $this, 'filter_by_folder' ] );
		add_action( 'add_attachment', [ $this, 'assign_folder_on_upload' ] );
	}

	/**
	 * Assign folder to attachment during upload if mfp_folder_id is in POST data.
	 * This runs server-side during async-upload.php, so no race condition.
	 */
	public function assign_folder_on_upload( int $attachment_id ): void {
		if ( empty( $_POST['mfp_folder_id'] ) ) {
			return;
		}

		$folder_id = (int) $_POST['mfp_folder_id'];
		if ( $folder_id <= 0 ) {
			return;
		}

		wp_set_object_terms( $attachment_id, [ $folder_id ], MFP_Taxonomy::TAXONOMY );
	}

	/**
	 * Inject tax_query into media grid AJAX queries when media_folder param is present.
	 *
	 * @param array $query WP_Query args for attachment query.
	 * @return array Modified query args.
	 */
	public function filter_by_folder( array $query ): array {
		if ( empty( $_REQUEST['query']['media_folder'] ) ) {
			return $query;
		}

		$folder_id = (int) $_REQUEST['query']['media_folder'];

		if ( ! isset( $query['tax_query'] ) ) {
			$query['tax_query'] = [];
		}

		if ( $folder_id === -1 ) {
			// Uncategorized: media without any folder.
			$query['tax_query'][] = [
				'taxonomy' => MFP_Taxonomy::TAXONOMY,
				'operator' => 'NOT EXISTS',
			];
		} elseif ( $folder_id > 0 ) {
			$query['tax_query'][] = [
				'taxonomy' => MFP_Taxonomy::TAXONOMY,
				'terms'    => [ $folder_id ],
				'field'    => 'term_id',
			];
		}

		return $query;
	}
}
