<?php

namespace HulkPlugins\Woo\AccountPages\Admin\Controllers;

use HulkPlugins\Woo\AccountPages\Admin\Services\AccountPagesService;
use HulkPlugins\Woo\AccountPages\Core\BaseController;
use HulkPlugins\Woo\AccountPages\Core\SingletonTrait;
use WP_Post;

defined( 'ABSPATH' ) || exit;

class AccountPagesController extends BaseController {

	use SingletonTrait;

	protected AccountPagesService $service;

	public function init_hooks(): void {
		$this->service = AccountPagesService::getInstance();

        add_action( 'init', [ $this, 'cpt_init' ] );
		add_action( 'init', [ $this, 'maybe_flush_on_init' ], 999 );
		add_filter( "manage_{$this->service->post_type}_posts_columns", [ $this, 'manage_posts_columns' ] );
		add_filter( "manage_edit-{$this->service->post_type}_sortable_columns", [ $this, 'manage_sortable_columns' ] );
		add_action( "manage_{$this->service->post_type}_posts_custom_column", [ $this, 'manage_posts_custom_column' ], 10, 2 );
		add_action( "save_post_{$this->service->post_type}", [ $this, 'refresh_permalinks' ] );
		add_filter( 'page_row_actions', [ $this, 'row_actions' ], 10, 2 );
		add_filter( 'post_row_actions', [ $this, 'row_actions' ], 10, 2 );
	}

	// Register post type
	public function cpt_init(): void {
		register_post_type(
			$this->service->post_type,
			[
				'labels'            => [
					'name'                     => esc_attr__( 'Woo Account Pages', 'hulk-account-pages-for-woocommerce' ),
					'singular_name'            => esc_attr__( 'Page', 'hulk-account-pages-for-woocommerce' ),
					'add_new'                  => esc_attr__( 'Add Page', 'hulk-account-pages-for-woocommerce' ),
					'add_new_item'             => esc_attr__( 'Add Page', 'hulk-account-pages-for-woocommerce' ),
					'edit_item'                => esc_attr__( 'Edit Page', 'hulk-account-pages-for-woocommerce' ),
					'new_item'                 => esc_attr__( 'New Page', 'hulk-account-pages-for-woocommerce' ),
					'view_item'                => esc_attr__( 'View Page', 'hulk-account-pages-for-woocommerce' ),
					'view_items'               => esc_attr__( 'View Pages', 'hulk-account-pages-for-woocommerce' ),
					'search_items'             => esc_attr__( 'Search Pages', 'hulk-account-pages-for-woocommerce' ),
					'not_found'                => esc_attr__( 'No pages found', 'hulk-account-pages-for-woocommerce' ),
					'not_found_in_trash'       => esc_attr__( 'No pages found in Trash', 'hulk-account-pages-for-woocommerce' ),
					'parent_item_colon'        => esc_attr__( 'Parent Page:', 'hulk-account-pages-for-woocommerce' ),
					'all_items'                => esc_attr__( 'All Pages', 'hulk-account-pages-for-woocommerce' ),
					'archives'                 => esc_attr__( 'Page Archives', 'hulk-account-pages-for-woocommerce' ),
					'attributes'               => esc_attr__( 'Page Attributes', 'hulk-account-pages-for-woocommerce' ),
					'insert_into_item'         => esc_attr__( /** @lang text */ 'Insert into page', 'hulk-account-pages-for-woocommerce' ),
					'uploaded_to_this_item'    => esc_attr__( 'Uploaded to this page', 'hulk-account-pages-for-woocommerce' ),
					'filter_items_list'        => esc_attr__( 'Filter pages list', 'hulk-account-pages-for-woocommerce' ),
					'items_list_navigation'    => esc_attr__( 'Pages list navigation', 'hulk-account-pages-for-woocommerce' ),
					'items_list'               => esc_attr__( 'Pages list', 'hulk-account-pages-for-woocommerce' ),
					'item_published'           => esc_attr__( 'Page published.', 'hulk-account-pages-for-woocommerce' ),
					'item_published_privately' => esc_attr__( 'Page published privately.', 'hulk-account-pages-for-woocommerce' ),
					'item_reverted_to_draft'   => esc_attr__( 'Page reverted to draft.', 'hulk-account-pages-for-woocommerce' ),
					'item_trashed'             => esc_attr__( 'Page trashed.', 'hulk-account-pages-for-woocommerce' ),
					'item_scheduled'           => esc_attr__( 'Page scheduled.', 'hulk-account-pages-for-woocommerce' ),
					'item_updated'             => esc_attr__( 'Page updated.', 'hulk-account-pages-for-woocommerce' ),
					'item_link'                => esc_attr__( 'Page link', 'hulk-account-pages-for-woocommerce' ),
					'item_link_description'    => esc_attr__( 'A link to a page.', 'hulk-account-pages-for-woocommerce' ),
				],
				'public'            => false,
				'hierarchical'      => false,
				'show_ui'           => true,
				'show_in_nav_menus' => false,
				'supports'          => [
					'title',
					'editor',
					'author',
					'thumbnail',
					'excerpt',
					'page-attributes',
					'revisions',
					'custom-fields',
				],
				'has_archive'       => false,
				'rewrite'           => true,
				'query_var'         => true,
				'menu_position'     => null,
				'show_in_rest'      => true,
				'capability_type'   => 'page',
				'menu_icon'         => 'dashicons-admin-page',
			]
		);
	}

	// Check for the flag on the next 'init' and flush once.
	public function maybe_flush_on_init(): void {
		if ( get_option( 'hulk_woo_ap_needs_flush' ) ) {
            flush_rewrite_rules();
			delete_option( 'hulk_woo_ap_needs_flush' );
		}
	}

	// Add sortable columns for menu order
	public function manage_posts_columns( $columns ): array {
		$new_columns = [];
		foreach ( $columns as $key => $value ) {
			// Add everything except date first
			if ( $key !== 'date' ) {
				$new_columns[ $key ] = $value;
			}
			// Insert menu_order column before date
			if ( $key === 'date' ) {
				$new_columns['menu_order'] = esc_attr__( 'Order', 'hulk-account-pages-for-woocommerce' );
				$new_columns[ $key ] = $value; // add date after
			}
		}
		return $new_columns;
	}

	// Make the order column sortable
	public function manage_sortable_columns( $columns ) {
		$columns['menu_order'] = 'menu_order';
		return $columns;
	}

	// Display the menu order value in the column
	public function manage_posts_custom_column( $column, $post_id ): void {
		if ( $column === 'menu_order' ) {
			echo esc_html( get_post_field( 'menu_order', $post_id ) );
		}
	}

	// Refresh permalinks after save
	public function refresh_permalinks( $post_id ): void {
		if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
			return;
		}

		update_option( 'hulk_woo_ap_needs_flush', 1 );
	}

	// Add a new "view" action
	public function row_actions( $actions, $post ) {
		/** @var WP_Post $post */
		if (
			( $post->post_type === $this->service->post_type ) &&
			( $post->post_status === 'publish' )
		) {
			$actions['view'] = $this->service->get_permalink( $post );
		}
		return $actions;
	}
}
