<?php
/**
 * Log AJAX handlers — list, download, delete, settings.
 *
 * @package CoffeeWP_Media_Cleanup
 */

namespace CWPM\Ajax;

use CWPM\Core\Logger;

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified centrally in BaseHandler::verify_request().

class LogHandler extends BaseHandler {

	/**
	 * Constructor — register AJAX actions.
	 */
	public function __construct() {
		add_action( 'wp_ajax_cwpm_log_list', array( $this, 'log_list' ) );
		add_action( 'wp_ajax_cwpm_log_download', array( $this, 'log_download' ) );
		add_action( 'wp_ajax_cwpm_log_delete', array( $this, 'log_delete' ) );
		add_action( 'wp_ajax_cwpm_save_log_settings', array( $this, 'save_log_settings' ) );
	}

	/**
	 * List all log files.
	 */
	public function log_list() {
		check_ajax_referer( 'cwpm_nonce', 'nonce' );
		$this->verify_request();

		$logs = Logger::list_logs();

		wp_send_json_success(
			array(
				'results' => $logs,
				'total'   => count( $logs ),
			)
		);
	}

	/**
	 * Download a log file.
	 *
	 * Contents are base64-encoded in the JSON response to prevent any
	 * injection vector if a log line ever contained user-controlled HTML.
	 */
	public function log_download() {
		check_ajax_referer( 'cwpm_nonce', 'nonce' );
		$this->verify_request();

		$filename = isset( $_POST['filename'] ) ? sanitize_file_name( wp_unslash( $_POST['filename'] ) ) : '';
		$path     = Logger::get_log_path( $filename );

		if ( false === $path ) {
			wp_send_json_error( 'Log file not found.', 404 );
		}

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		$contents = file_get_contents( $path );

		if ( false === $contents ) {
			wp_send_json_error( 'Failed to read log file.', 500 );
		}

		wp_send_json_success(
			array(
				'filename' => $filename,
				'encoding' => 'base64',
				// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- binary-safe transport over JSON; client decodes for download.
				'contents' => base64_encode( $contents ),
			)
		);
	}

	/**
	 * Delete a log file.
	 */
	public function log_delete() {
		check_ajax_referer( 'cwpm_nonce', 'nonce' );
		$this->verify_request();

		$filename = isset( $_POST['filename'] ) ? sanitize_file_name( wp_unslash( $_POST['filename'] ) ) : '';
		$success  = Logger::delete_log( $filename );

		if ( ! $success ) {
			wp_send_json_error( 'Failed to delete log file.' );
		}

		wp_send_json_success( array( 'filename' => $filename ) );
	}

	/**
	 * Save log auto-delete setting.
	 */
	public function save_log_settings() {
		check_ajax_referer( 'cwpm_nonce', 'nonce' );
		$this->verify_request();

		$auto_delete = filter_var(
			isset( $_POST['auto_delete_logs'] ) ? wp_unslash( $_POST['auto_delete_logs'] ) : false,
			FILTER_VALIDATE_BOOLEAN
		);

		update_option( 'cwpm_auto_delete_logs', $auto_delete );

		wp_send_json_success( array( 'auto_delete_logs' => $auto_delete ) );
	}
}
