<?php
/**
 * Post Meta box handling for static exclusions.
 * 
 * @package WPStaticHTMLPages
 */

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

class WPSH_Meta {

	/**
	 * Initialize meta box hooks.
	 */
	public function init() {
		add_action( 'add_meta_boxes', array( $this, 'register_meta_boxes' ) );
		add_action( 'save_post', array( $this, 'save_meta_box_data' ) );
		
		// Columns in list table.
		add_action( 'init', array( $this, 'init_columns' ) );
	}

	/**
	 * Register the meta box.
	 */
	public function register_meta_boxes() {
		$public_types = get_post_types( array( 'public' => true ) );
		foreach ( $public_types as $type ) {
			add_meta_box(
				'wpsh_settings',
				'Static HTML Settings',
				array( $this, 'render_meta_box' ),
				$type,
				'side'
			);
		}
	}

	/**
	 * Render the meta box content.
	 */
	public function render_meta_box( $post ) {
		wp_nonce_field( 'wpsh_meta_save', 'wpsh_meta_nonce' );
		$val = get_post_meta( $post->ID, '_wpsh_exclude', true );
		?>
		<p>
			<label>
				<input type="checkbox" name="wpsh_exclude" value="1" <?php checked( $val, '1' ); ?>> 
				Exclude from Static HTML Cache
			</label>
		</p>
		<p class="description">If checked, this page will not be cached as static HTML and will always be served dynamically.</p>
		<?php
	}

	/**
	 * Save meta box data.
	 */
	public function save_meta_box_data( $post_id ) {
		if ( ! isset( $_POST['wpsh_meta_nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['wpsh_meta_nonce'] ) ), 'wpsh_meta_save' ) ) return;
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
		if ( ! current_user_can( 'edit_post', $post_id ) ) return;

		$exclude = isset( $_POST['wpsh_exclude'] ) ? '1' : '0';
		update_post_meta( $post_id, '_wpsh_exclude', $exclude );
		
		if ( $exclude === '1' ) {
			$core = new WPSH_Core();
			$url  = get_permalink( $post_id );
			$path = $core->get_static_path_from_url( $url );
			$post_type = get_post_type( $post_id );

			global $wp_filesystem;
			if ( empty( $wp_filesystem ) ) {
				require_once ABSPATH . 'wp-admin/includes/file.php';
				WP_Filesystem();
			}

			if ( $path && $wp_filesystem->exists( $path ) ) {
				WPSH_Logger::deleted(
					'Static file removed due to exclusion (Post Type: ' . $post_type . ')',
					array(
						'path'   => $path,
						'post_id'=> $post_id,
						'url'    => $url,
						'reason' => 'post_excluded',
					)
				);
				$wp_filesystem->delete( $path );
			}
		}
	}

	/**
	 * Initialize table columns.
	 */
	public function init_columns() {
		$public_types = get_post_types( array( 'public' => true ) );
		foreach ( $public_types as $type ) {
			add_filter( "manage_{$type}_posts_columns", array( $this, 'add_columns' ) );
			add_action( "manage_{$type}_posts_custom_column", array( $this, 'render_columns' ), 10, 2 );
		}
	}

	public function add_columns( $columns ) {
		$new_columns = array();
		foreach ( $columns as $key => $value ) {
			if ( $key === 'date' ) {
				$new_columns['wpsh_status'] = 'Static HTML';
			}
			$new_columns[$key] = $value;
		}
		return $new_columns;
	}

	public function render_columns( $column, $post_id ) {
		if ( $column !== 'wpsh_status' ) return;

		$core = new WPSH_Core();
		$url = get_permalink( $post_id );
		$path = $core->get_static_path_from_url( $url );

		if ( $path && file_exists( $path ) ) {
			$mtime = filemtime( $path );
			echo sprintf(
				'<span class="wpsh-badge wpsh-badge-success" title="%s"><span class="dashicons dashicons-yes-alt" style="font-size: 15px; width: 15px; height: 15px; margin-right: 3px; vertical-align: text-bottom;"></span>%s<br><small style="margin-left: 21px;">%s</small></span>',
				esc_attr( 'Static file exists' ),
				'Generated',
				esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $mtime ) )
			);
		} else {
			echo '<span class="wpsh-badge wpsh-badge-none"><span class="dashicons dashicons-warning" style="font-size: 15px; width: 15px; height: 15px; margin-right: 3px; vertical-align: text-bottom;"></span>Not Cached</span>';
		}
	}
}
