<?php
namespace ActirisePublic\Includes;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

use Actirise\Includes\Helpers;
use Actirise\Includes\Options;
use ActiriseAdmin\Includes\View;

/**
 * Actirise NoPub
 *
 * @link       https://actirise.com
 * @since      2.0.0
 * @package    actirise
 * @subpackage actirise/public/includes
 * @author     actirise <wordpress@actirise.com>
 */
final class NoPub {
	/**
	 * The unique identifier of this plugin.
	 *
	 * @since    2.0.0
	 * @access   protected
	 * @var      string    $plugin_name    The string used to uniquely identify this plugin.
	 */
	protected $plugin_name;

	/**
	 * View manager
	 *
	 * @since    3.2.0
	 * @access   private
	 * @var      View    $views    View manager instance
	 */
	private $views;

	/**
	 * NoPub constructor.
	 *
	 * @since    2.0.0
	 * @param    string $plugin_name The name of this plugin.
	 */
	public function __construct( $plugin_name ) {
		$this->plugin_name = $plugin_name;
		$this->views       = new View();
	}

	/**
	 * Register meta box hooks
	 *
	 * @since 3.2.0
	 * @return void
	 */
	public function register_meta_box() {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
		add_action( 'save_post', array( $this, 'save_meta_box' ) );
	}

	/**
	 * Get page type
	 *
	 * @return string
	 * @since 2.0.0
	 */
	public function get_page_type() {
		$page_type = '';

		if ( is_page() ) {
			$page_type = 'page';
		} elseif ( is_single() ) {
			$page_type = 'post';
		} elseif ( is_category() ) {
			$page_type = 'category';
		} elseif ( is_tag() ) {
			$page_type = 'post_tag';
		}

		return $page_type;
	}

	/**
	 * Add meta box for Actirise Ad Control
	 *
	 * @since 3.2.0
	 * @return void
	 */
	public function add_meta_box() {
		if ( ! Helpers::is_user_authenticated() ) {
			return;
		}

		$post_types = get_post_types( array( 'public' => true ) );

		if ( isset( $post_types['attachment'] ) ) {
			unset( $post_types['attachment'] );
		}

		foreach ( $post_types as $post_type ) {
			add_meta_box(
				'actirise-ad-control',
				__( 'Actirise', 'actirise' ),
				array( $this, 'render_meta_box' ),
				$post_type,
				'side',
				'low'
			);
		}
	}

	/**
	 * Render the meta box content using template
	 *
	 * @since 3.2.0
	 * @param \WP_Post $post The post object.
	 * @return void
	 */
	public function render_meta_box( $post ) {
		$ads_enabled = $this->ads_enabled( $post->ID );

		$this->views->render(
			'meta-box-ad-control',
			array(
				'post_id'     => $post->ID,
				'ads_enabled' => $ads_enabled,
			)
		);
	}

	/**
	 * Save meta box data
	 *
	 * @since 3.2.0
	 * @param int $post_id The post ID.
	 * @return void
	 */
	public function save_meta_box( $post_id ) {
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! isset( $_POST['actirise_ad_control_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['actirise_ad_control_nonce'] ) ), 'actirise_ad_control_nonce' ) ) {
			return;
		}

		$ads_enabled = isset( $_POST['actirise_ads_enabled'] ) ? sanitize_text_field( wp_unslash( $_POST['actirise_ads_enabled'] ) ) : '0';

		$post = get_post( $post_id );
		if ( ! $post ) {
			return;
		}

		if ( $ads_enabled === '0' ) {
			$this->add_to_nopub( $post );
		} else {
			$this->remove_from_nopub( $post_id );
		}
	}

	/**
	 * Add a post to the nopub list
	 *
	 * @since 3.2.0
	 * @param \WP_Post $post The post object.
	 * @return void
	 */
	private function add_to_nopub( $post ) {
		$no_pub = Options::get( 'nopub', array() );

		if ( ! is_array( $no_pub ) ) {
			$no_pub = array();
		}

		if ( ! $this->ads_enabled( $post->ID ) ) {
			return;
		}

		$thumbnail_url = get_the_post_thumbnail_url( $post->ID, 'thumbnail' );

		$new_entry = (object) array(
			'id'            => $post->ID,
			'title'         => $post->post_title,
			'url'           => get_permalink( $post->ID ),
			'type'          => $post->post_type === 'page' ? 'page' : 'post',
			'summary'       => substr( $post->post_content, 0, 100 ),
			'publishedDate' => $post->post_date,
			'createdAt'     => current_time( 'mysql' ),
			'image'         => $thumbnail_url ? $thumbnail_url : '',
		);

		$no_pub[] = $new_entry;
		Options::update( 'nopub', $no_pub );
	}

	/**
	 * Remove a post from the nopub list
	 *
	 * @since 3.2.0
	 * @param int $post_id The post ID.
	 * @return void
	 */
	private function remove_from_nopub( $post_id ) {
		$no_pub = Options::get( 'nopub', array() );

		if ( ! is_array( $no_pub ) ) {
			return;
		}

		$no_pub = array_filter(
			$no_pub,
			function ( $item ) use ( $post_id ) {
				return ! ( is_object( $item ) && property_exists( $item, 'id' ) && is_numeric( $item->id ) && (int) $item->id === $post_id );
			}
		);

		$no_pub = array_values( $no_pub );
		Options::update( 'nopub', $no_pub );
	}

	/**
	 * Check if ads are enabled for a post or current page
	 *
	 * @since 3.2.0
	 * @param int|null $post_id The post ID. If null, checks current page context.
	 * @return bool True if ads are enabled, false otherwise.
	 */
	public function ads_enabled( $post_id = null ) {
		/** @var mixed $no_pub */
		$no_pub = Options::get( 'nopub', array() );

		if ( ! is_array( $no_pub ) || count( $no_pub ) === 0 ) {
			return true;
		}

		if ( $post_id !== null ) {
			foreach ( $no_pub as $item ) {
				if ( is_object( $item ) && property_exists( $item, 'id' ) && is_numeric( $item->id ) && (int) $item->id === $post_id ) {
					return false;
				}
			}
			return true;
		}

		$page_type = $this->get_page_type();

		if ( $page_type === '' ) {
			return true;
		}

		$no_pub = array_filter(
			$no_pub,
			function ( $item ) use ( $page_type ) {
				return is_object( $item ) && isset( $item->type ) && $item->type === $page_type;
			}
		);

		$queried_object_id = get_queried_object_id();

		$no_pub = array_filter(
			$no_pub,
			function ( $item ) use ( $queried_object_id ) {
				return isset( $item->id ) && $item->id === $queried_object_id;
			}
		);

		return count( $no_pub ) === 0;
	}
}
