<?php

namespace MDCE\Admin;

use MDCE\PostTypes;

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

class Columns {

	private PostTypes $post_types;

	public function __construct( PostTypes $post_types ) {
		$this->post_types = $post_types;
	}

	public function register(): void {
		foreach ( $this->post_types->get_supported() as $post_type ) {
			add_filter( "manage_{$post_type}_posts_columns",         [ $this, 'add_column' ] );
			add_action( "manage_{$post_type}_posts_custom_column",   [ $this, 'render_column' ], 10, 2 );
			add_filter( "manage_edit-{$post_type}_sortable_columns", [ $this, 'make_sortable' ] );
		}
		add_action( 'quick_edit_custom_box',  [ $this, 'quick_edit_fields' ], 10, 2 );
		add_action( 'pre_get_posts',          [ $this, 'sort_query' ] );
		add_action( 'admin_enqueue_scripts',  [ $this, 'enqueue_assets' ] );
	}

	public function enqueue_assets( string $hook ): void {
		if ( 'edit.php' !== $hook ) {
			return;
		}
		$screen = get_current_screen();
		if ( ! $screen || ! $this->post_types->is_supported( $screen->post_type ) ) {
			return;
		}

		$vendor = MDCE_PLUGIN_URL . 'assets/vendor/flatpickr/';
		wp_enqueue_style( 'flatpickr',  $vendor . 'flatpickr.min.css', [], '4.6.13' );
		wp_enqueue_script( 'flatpickr', $vendor . 'flatpickr.min.js', [], '4.6.13', true );

		wp_enqueue_style( 'mdce-admin',   MDCE_PLUGIN_URL . 'assets/css/admin.css',   [ 'flatpickr' ], MDCE_VERSION );
		wp_enqueue_style( 'mdce-columns', MDCE_PLUGIN_URL . 'assets/css/columns.css', [], MDCE_VERSION );
		wp_enqueue_script( 'mdce-admin',  MDCE_PLUGIN_URL . 'assets/js/admin.js',     [ 'flatpickr', 'inline-edit-post' ], MDCE_VERSION, true );
	}

	public function add_column( array $columns ): array {
		$columns['spe_expiration'] = __( 'Expires', 'monkeydesign-content-expiry' );
		return $columns;
	}

	public function render_column( string $column, int $post_id ): void {
		if ( 'spe_expiration' !== $column ) {
			return;
		}

		$timestamp  = (int) get_post_meta( $post_id, '_mdce_expiration_date', true );
		$action     = (string) get_post_meta( $post_id, '_mdce_expiration_action', true );
		$date_value = $timestamp ? wp_date( 'Y-m-d H:i', $timestamp ) : '';

		if ( ! $timestamp ) {
			printf(
				'<div class="spe-col" data-spe-enabled="0" data-spe-date="" data-spe-action="">—</div>'
			);
			return;
		}

		$date_format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
		$formatted   = wp_date( $date_format, $timestamp );
		$now         = time();
		$is_past     = $timestamp < $now;
		$is_soon     = ! $is_past && ( $timestamp - $now ) <= DAY_IN_SECONDS;
		$urgent      = $is_past || $is_soon;

		$label = match ( $action ) {
			'draft'    => __( 'Change to Draft', 'monkeydesign-content-expiry' ),
			'trash'    => __( 'Move to Trash', 'monkeydesign-content-expiry' ),
			'private'  => __( 'Make Private', 'monkeydesign-content-expiry' ),
			'delete'   => __( 'Delete permanently', 'monkeydesign-content-expiry' ),
			'category' => __( 'Change category', 'monkeydesign-content-expiry' ),
			'title'    => __( 'Change title', 'monkeydesign-content-expiry' ),
			'redirect' => __( 'Redirect to URL', 'monkeydesign-content-expiry' ),
			'replace'  => __( 'Replace content', 'monkeydesign-content-expiry' ),
			default    => $action,
		};

		printf(
			'<div class="spe-col%s" data-spe-enabled="1" data-spe-date="%s" data-spe-action="%s" title="%s"><span class="spe-col__action">%s</span><br><span class="spe-col__date">%s</span></div>',
			$urgent ? ' spe-col--urgent' : '',
			esc_attr( $date_value ),
			esc_attr( $action ),
			esc_attr( wp_date( 'c', $timestamp ) ),
			esc_html( $label ),
			esc_html( $formatted )
		);
	}

	public function quick_edit_fields( string $column, string $post_type ): void {
		if ( 'spe_expiration' !== $column ) {
			return;
		}
		if ( ! $this->post_types->is_supported( $post_type ) ) {
			return;
		}
		wp_nonce_field( 'spe_save_expiration', 'spe_nonce' );
		?>
		<fieldset class="spe-qe-fieldset">
			<legend><span class="title"><?php esc_html_e( 'Expiration', 'monkeydesign-content-expiry' ); ?></span></legend>
			<div class="spe-qe-row">

				<input
					type="checkbox"
					id="spe-qe-enabled"
					name="spe_enabled"
					value="1"
					class="spe-qe-row__check"
				>

				<div class="spe-input-wrap spe-input-wrap--icon spe-qe-row__date-wrap">
					<input
						type="text"
						id="spe-qe-date"
						name="spe_expiration_date"
						class="spe-input spe-datetime-input"
						placeholder="<?php esc_attr_e( 'Date & time…', 'monkeydesign-content-expiry' ); ?>"
					>
					<span class="spe-input-icon" aria-hidden="true">
						<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
							<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
							<line x1="16" y1="2" x2="16" y2="6"></line>
							<line x1="8" y1="2" x2="8" y2="6"></line>
							<line x1="3" y1="10" x2="21" y2="10"></line>
						</svg>
					</span>
				</div>

				<div class="spe-qe-row__select-wrap">
					<select id="spe-qe-action" name="spe_expiration_action" class="spe-qe-select">
						<option value="draft"><?php esc_html_e( 'Change to Draft', 'monkeydesign-content-expiry' ); ?></option>
						<option value="private"><?php esc_html_e( 'Make Private', 'monkeydesign-content-expiry' ); ?></option>
						<option value="trash"><?php esc_html_e( 'Move to Trash', 'monkeydesign-content-expiry' ); ?></option>
						<option value="delete"><?php esc_html_e( 'Delete permanently', 'monkeydesign-content-expiry' ); ?></option>
						<option value="category"><?php esc_html_e( 'Change category', 'monkeydesign-content-expiry' ); ?></option>
						<option value="title"><?php esc_html_e( 'Change title', 'monkeydesign-content-expiry' ); ?></option>
						<optgroup label="✦ PRO">
							<?php if ( defined( 'MDCE_PRO_VERSION' ) ) : ?>
								<?php do_action( 'mdce_expiration_action_options', '' ); ?>
							<?php else : ?>
								<option value="" disabled><?php esc_html_e( 'Redirect to URL', 'monkeydesign-content-expiry' ); ?></option>
								<option value="" disabled><?php esc_html_e( 'Replace content', 'monkeydesign-content-expiry' ); ?></option>
							<?php endif; ?>
						</optgroup>
					</select>
				</div>

			</div><!-- .spe-qe-row -->
		</fieldset><!-- .spe-qe-fieldset -->
		<?php
	}

	public function make_sortable( array $columns ): array {
		$columns['spe_expiration'] = 'spe_expiration';
		return $columns;
	}

	public function sort_query( \WP_Query $query ): void {
		if ( ! is_admin() || ! $query->is_main_query() ) {
			return;
		}
		if ( 'spe_expiration' !== $query->get( 'orderby' ) ) {
			return;
		}
		$query->set( 'meta_key', '_mdce_expiration_date' );
		$query->set( 'orderby', 'meta_value_num' );
	}
}
