<?php
/**
 * Admin logic for post lists and meta.
 *
 * @package TextToPDF
 */

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

/**
 * TextToPDF_Admin Class
 */
class TextToPDF_Admin {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		// Add column to posts and pages list.
		add_filter( 'manage_posts_columns', array( $this, 'add_download_column' ) );
		add_action( 'manage_posts_custom_column', array( $this, 'render_download_column' ), 10, 2 );

		add_filter( 'manage_pages_columns', array( $this, 'add_download_column' ) );
		add_action( 'manage_pages_custom_column', array( $this, 'render_download_column' ), 10, 2 );

		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
	}

	/**
	 * Enqueue scripts for WP admin.
	 *
	 * @param string $hook_suffix The current admin page.
	 */
	public function enqueue_admin_scripts( $hook_suffix ) {
		if ( 'settings_page_texttopdf-settings' === $hook_suffix ) {
			wp_enqueue_media();

			wp_enqueue_script( 'jquery' );

			$inline_js = '
				jQuery(document).ready(function($){
					var mediaUploader;
					$("#texttopdf_upload_logo_button").on("click", function(e) {
						e.preventDefault();
						if (mediaUploader) {
							mediaUploader.open();
							return;
						}
						mediaUploader = wp.media({
							title: texttopdfnet_media.title,
							button: {
								text: texttopdfnet_media.button_text
							},
							multiple: false
						});
						mediaUploader.on("select", function() {
							var attachment = mediaUploader.state().get("selection").first().toJSON();
							$("#texttopdf_watermark_logo").val(attachment.url);
						});
						mediaUploader.open();
					});
				});
			';

			wp_register_script( 'texttopdfnet-admin-media', '', array( 'jquery' ), TEXTTOPDF_VERSION, true );
			wp_localize_script( 'texttopdfnet-admin-media', 'texttopdfnet_media', array(
				'title'       => __( 'Choose Logo', 'texttopdfnet-text-web-to-pdf' ),
				'button_text' => __( 'Use this Logo', 'texttopdfnet-text-web-to-pdf' ),
			) );
			wp_enqueue_script( 'texttopdfnet-admin-media' );
			wp_add_inline_script( 'texttopdfnet-admin-media', $inline_js );
		}
	}

	/**
	 * Add "PDF Downloads" column.
	 *
	 * @param array $columns Existing columns.
	 * @return array Modified columns.
	 */
	public function add_download_column( $columns ) {
		$columns['texttopdf_downloads'] = __( 'PDF Downloads', 'texttopdfnet-text-web-to-pdf' );
		return $columns;
	}

	/**
	 * Render the data for the new column.
	 *
	 * @param string $column_name Column name.
	 * @param int    $post_id     Post ID.
	 */
	public function render_download_column( $column_name, $post_id ) {
		if ( 'texttopdf_downloads' === $column_name ) {
			$count = get_post_meta( $post_id, 'texttopdf_download_count', true );
			echo esc_html( $count ? (int) $count : '0' );
		}
	}
}
