<?php
namespace Smart_Media_Cleanup;

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

class Cleanup_On_Delete {

	private $settings;

	public function __construct() {
		$this->settings = Plugin::instance()->get_settings()->get();

		if ( empty( $this->settings['enabled'] ) || empty( $this->settings['post_types'] ) ) {
			return;
		}

		add_action( 'before_delete_post', array( $this, 'on_delete' ), 10, 2 );

		if ( 'both' === $this->settings['trigger'] ) {
			add_action( 'wp_trash_post', array( $this, 'on_trash' ) );
		}
	}

	public function on_delete( $post_id, $post = null ) {
		if ( ! $post ) {
			$post = get_post( $post_id );
		}

		if ( ! $post || 'attachment' === $post->post_type ) {
			return;
		}

		if ( ! $this->is_monitored( $post->post_type ) ) {
			return;
		}

		$this->process( $post_id, 'delete_on_post' );
	}

	public function on_trash( $post_id ) {
		$post = get_post( $post_id );

		if ( ! $post || 'attachment' === $post->post_type ) {
			return;
		}

		if ( ! $this->is_monitored( $post->post_type ) ) {
			return;
		}

		$this->process( $post_id, 'delete_on_post' );
	}

	/**
	 * Returns true if the post type should trigger attachment cleanup.
	 * product_variation is included automatically when WooCommerce is active
	 * and the parent product type is monitored — no settings change required.
	 */
	private function is_monitored( $post_type ) {
		$monitored = (array) $this->settings['post_types'];

		if ( in_array( $post_type, $monitored, true ) ) {
			return true;
		}

		if ( 'product_variation' === $post_type
			&& ( class_exists( 'WooCommerce', false ) || defined( 'WC_VERSION' ) )
			&& in_array( 'product', $monitored, true )
		) {
			return true;
		}

		return false;
	}

	private function process( $post_id, $event_type ) {
		$attachment_ids = $this->collect_attachments( $post_id );

		if ( empty( $attachment_ids ) ) {
			return;
		}

		$logger = Plugin::instance()->get_logger();

		foreach ( $attachment_ids as $attachment_id ) {
			if ( ! empty( $this->settings['check_usage'] ) ) {
				if ( Attachment_Usage::is_used_elsewhere( $attachment_id, $post_id ) ) {
					continue;
				}
			}

			$deleted = wp_delete_attachment( $attachment_id, true );

			if ( $deleted ) {
				$logger->log( $event_type, $attachment_id, $post_id, 'Deleted on post deletion.' );
			} else {
				$logger->log( 'error', $attachment_id, $post_id, 'Failed to delete attachment.' );
			}
		}
	}

	private function collect_attachments( $post_id ) {
		$ids = array();

		if ( ! empty( $this->settings['delete_featured'] ) ) {
			$featured_id = get_post_thumbnail_id( $post_id );
			if ( $featured_id ) {
				$ids[] = (int) $featured_id;
			}
		}

		if ( ! empty( $this->settings['delete_attached'] ) ) {
			$children = get_children( array(
				'post_parent' => $post_id,
				'post_type'   => 'attachment',
				'fields'      => 'ids',
			) );
			if ( ! empty( $children ) ) {
				$ids = array_merge( $ids, array_map( 'intval', $children ) );
			}
		}

		if ( ! empty( $this->settings['delete_meta_galleries'] ) ) {
			$meta_keys = array_filter( (array) $this->settings['meta_keys'] );
			foreach ( $meta_keys as $key ) {
				$raw  = get_post_meta( $post_id, $key, true );
				$more = $this->parse_meta_value( $raw );
				if ( ! empty( $more ) ) {
					$ids = array_merge( $ids, $more );
				}
			}
		}

		return array_values( array_unique( array_filter( $ids ) ) );
	}

	private function parse_meta_value( $raw ) {
		if ( empty( $raw ) ) {
			return array();
		}

		$ids = array();

		// Already an array.
		if ( is_array( $raw ) ) {
			foreach ( $raw as $item ) {
				if ( is_numeric( $item ) ) {
					$ids[] = (int) $item;
				} elseif ( is_array( $item ) ) {
					// Array of arrays with 'id' key.
					if ( isset( $item['id'] ) ) {
						$ids[] = (int) $item['id'];
					} elseif ( isset( $item['url'] ) ) {
						$id = attachment_url_to_postid( $item['url'] );
						if ( $id ) {
							$ids[] = $id;
						}
					}
				}
			}
			return array_filter( $ids );
		}

		// JSON string.
		if ( is_string( $raw ) && 0 === strpos( trim( $raw ), '[' ) ) {
			$decoded = json_decode( $raw, true );
			if ( is_array( $decoded ) ) {
				return $this->parse_meta_value( $decoded );
			}
		}

		// Comma-separated IDs.
		if ( is_string( $raw ) && false !== strpos( $raw, ',' ) ) {
			$parts = explode( ',', $raw );
			foreach ( $parts as $part ) {
				$part = trim( $part );
				if ( is_numeric( $part ) ) {
					$ids[] = (int) $part;
				}
			}
			return array_filter( $ids );
		}

		// Single numeric ID.
		if ( is_numeric( $raw ) ) {
			return array( (int) $raw );
		}

		// Single URL.
		if ( is_string( $raw ) && filter_var( $raw, FILTER_VALIDATE_URL ) ) {
			$id = attachment_url_to_postid( $raw );
			if ( $id ) {
				return array( $id );
			}
		}

		return array();
	}
}
