<?php

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

class MFP_Ajax_Handler {

	private MFP_Taxonomy $taxonomy;

	public function __construct( MFP_Taxonomy $taxonomy ) {
		$this->taxonomy = $taxonomy;
	}

	public function register_hooks(): void {
		$actions = [
			'mfp_create_folder',
			'mfp_rename_folder',
			'mfp_delete_folder',
			'mfp_move_folder',
			'mfp_get_folders',
			'mfp_assign_media',
			'mfp_upload_to_folder',
		];

		foreach ( $actions as $action ) {
			add_action( "wp_ajax_{$action}", [ $this, $action ] );
		}
	}

	private function verify_request(): void {
		check_ajax_referer( 'mfp_nonce', 'nonce' );

		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( [ 'message' => __( 'Brak uprawnień.', 'media-folder-pro' ) ], 403 );
		}
	}

	public function mfp_create_folder(): void {
		$this->verify_request();

		$name      = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );
		$parent_id = (int) ( $_POST['parent_id'] ?? 0 );

		if ( empty( $name ) ) {
			wp_send_json_error( [ 'message' => __( 'Nazwa folderu jest wymagana.', 'media-folder-pro' ) ] );
		}

		$result = wp_insert_term( $name, MFP_Taxonomy::TAXONOMY, [
			'parent' => $parent_id,
		] );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		$term = get_term( $result['term_id'], MFP_Taxonomy::TAXONOMY );

		wp_send_json_success( [
			'folder' => [
				'id'       => $term->term_id,
				'name'     => $term->name,
				'slug'     => $term->slug,
				'parent'   => $term->parent,
				'count'    => 0,
				'children' => [],
			],
		] );
	}

	public function mfp_rename_folder(): void {
		$this->verify_request();

		$folder_id = (int) ( $_POST['folder_id'] ?? 0 );
		$name      = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );

		if ( ! $folder_id || empty( $name ) ) {
			wp_send_json_error( [ 'message' => __( 'ID folderu i nowa nazwa są wymagane.', 'media-folder-pro' ) ] );
		}

		$result = wp_update_term( $folder_id, MFP_Taxonomy::TAXONOMY, [
			'name' => $name,
		] );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		$term = get_term( $result['term_id'], MFP_Taxonomy::TAXONOMY );

		wp_send_json_success( [
			'folder' => [
				'id'   => $term->term_id,
				'name' => $term->name,
				'slug' => $term->slug,
			],
		] );
	}

	public function mfp_delete_folder(): void {
		$this->verify_request();

		$folder_id = (int) ( $_POST['folder_id'] ?? 0 );

		if ( ! $folder_id ) {
			wp_send_json_error( [ 'message' => __( 'ID folderu jest wymagane.', 'media-folder-pro' ) ] );
		}

		if ( $this->taxonomy->folder_has_children( $folder_id ) ) {
			wp_send_json_error( [
				'message' => __( 'Folder nie jest pusty. Usuń najpierw zawartość i podfoldery.', 'media-folder-pro' ),
				'code'    => 'not_empty',
			] );
		}

		$result = wp_delete_term( $folder_id, MFP_Taxonomy::TAXONOMY );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		wp_send_json_success();
	}

	public function mfp_move_folder(): void {
		$this->verify_request();

		$folder_id     = (int) ( $_POST['folder_id'] ?? 0 );
		$new_parent_id = (int) ( $_POST['new_parent_id'] ?? 0 );

		if ( ! $folder_id ) {
			wp_send_json_error( [ 'message' => __( 'ID folderu jest wymagane.', 'media-folder-pro' ) ] );
		}

		if ( $this->taxonomy->would_create_cycle( $folder_id, $new_parent_id ) ) {
			wp_send_json_error( [
				'message' => __( 'Nie można przenieść folderu do samego siebie lub swojego podfolderu.', 'media-folder-pro' ),
			] );
		}

		$result = wp_update_term( $folder_id, MFP_Taxonomy::TAXONOMY, [
			'parent' => $new_parent_id,
		] );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		$term = get_term( $result['term_id'], MFP_Taxonomy::TAXONOMY );

		wp_send_json_success( [
			'folder' => [
				'id'     => $term->term_id,
				'name'   => $term->name,
				'parent' => $term->parent,
			],
		] );
	}

	public function mfp_assign_media(): void {
		$this->verify_request();

		$attachment_ids = array_map( 'intval', (array) ( $_POST['attachment_ids'] ?? [] ) );
		$folder_id      = (int) ( $_POST['folder_id'] ?? 0 );

		if ( empty( $attachment_ids ) ) {
			wp_send_json_error( [ 'message' => __( 'Brak wybranych mediów.', 'media-folder-pro' ) ] );
		}

		$count = 0;
		foreach ( $attachment_ids as $id ) {
			if ( $id <= 0 ) {
				continue;
			}
			if ( get_post_type( $id ) !== 'attachment' ) {
				continue;
			}

			$terms = $folder_id > 0 ? [ $folder_id ] : [];
			$result = wp_set_object_terms( $id, $terms, MFP_Taxonomy::TAXONOMY );

			if ( ! is_wp_error( $result ) ) {
				$count++;
			}
		}

		// Return updated folder counts.
		$all_terms = get_terms( [
			'taxonomy'   => MFP_Taxonomy::TAXONOMY,
			'hide_empty' => false,
			'fields'     => 'all',
		] );

		$folder_counts = [];
		if ( ! is_wp_error( $all_terms ) ) {
			foreach ( $all_terms as $term ) {
				$folder_counts[ $term->term_id ] = (int) $term->count;
			}
		}

		wp_send_json_success( [
			'count'         => $count,
			'folder_counts' => $folder_counts,
		] );
	}

	public function mfp_upload_to_folder(): void {
		$this->verify_request();

		$attachment_id = (int) ( $_POST['attachment_id'] ?? 0 );
		$folder_id     = (int) ( $_POST['folder_id'] ?? 0 );

		if ( ! $attachment_id || ! $folder_id ) {
			wp_send_json_error( [ 'message' => __( 'ID załącznika i folderu są wymagane.', 'media-folder-pro' ) ] );
		}

		if ( get_post_type( $attachment_id ) !== 'attachment' ) {
			wp_send_json_error( [ 'message' => __( 'Nieprawidłowy załącznik.', 'media-folder-pro' ) ] );
		}

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

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		wp_send_json_success();
	}

	public function mfp_get_folders(): void {
		$this->verify_request();

		wp_send_json_success( [
			'folders' => $this->taxonomy->get_folder_tree(),
		] );
	}
}
