<?php
namespace Smart_Media_Cleanup;

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

class Orphan_Admin {

	public function __construct() {
		add_action( 'wp_ajax_smc_scan_orphans',   array( $this, 'ajax_scan' ) );
		add_action( 'wp_ajax_smc_delete_orphans', array( $this, 'ajax_delete' ) );
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		require SMC_PATH . 'admin/views/orphan-page.php';
	}

	public function ajax_scan() {
		check_ajax_referer( 'smc_orphan', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'smart-media-cleanup' ) ), 403 );
		}

		$offset = absint( $_POST['offset'] ?? 0 );
		$limit  = absint( $_POST['limit']  ?? 50 );

		$scanner = Plugin::instance()->orphan_scanner;
		$result  = $scanner->scan( $offset, $limit );

		wp_send_json_success( array(
			'orphans' => $result['items'],
			'offset'  => $offset,
			'limit'   => $limit,
			'total'   => $result['total'],
			'done'    => ( $offset + $limit ) >= $result['total'],
		) );
	}

	public function ajax_delete() {
		check_ajax_referer( 'smc_orphan', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'smart-media-cleanup' ) ), 403 );
		}

		$raw_ids = isset( $_POST['ids'] ) ? array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['ids'] ) ) : array();
		$ids     = array_map( 'absint', $raw_ids );
		$ids     = array_filter( $ids );

		if ( empty( $ids ) ) {
			wp_send_json_error( array( 'message' => __( 'No attachment IDs provided.', 'smart-media-cleanup' ) ) );
		}

		$result = Plugin::instance()->orphan_scanner->delete_batch( $ids );

		wp_send_json_success( $result );
	}
}
