<?php
namespace ShopExplorer;

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

/**
 * Frontend Dashboard Handler Class
 */
class FrontendDashboard {
	/**
	 * Page template path
	 */
	private $template_path = 'templates/shop-explorer-dashboard.php';

	/**
	 * Page template name
	 */
	private $template_name = 'Shop Explorer Dashboard';

	/**
	 * Page title
	 */
	private $page_title = 'Shop Explorer Dashboard';

	/**
	 * Plugin file path
	 */
	private $plugin_file;

	/**
	 * Valid routes array
	 */
	private $valid_routes = [
		'orders' => [
			'add-order',
			'details',
			'all',
			'trash',
		],
		'products' => [
			'add-product',
			'all',
			'categories',
			'tags',
			'brands',
			'attributes',
			'reviews',
		],
	];

	/**
	 * Constructor
	 */
	public function __construct( $plugin_file ) {
		$this->plugin_file = $plugin_file;
		$this->init_hooks();
	}

	/**
	 * Initialize WordPress hooks
	 */
	private function init_hooks() {
		register_activation_hook( $this->plugin_file, [ $this, 'activate' ] );
		add_action( 'init', [ $this, 'add_rewrite_rules' ] );
		add_filter( 'query_vars', [ $this, 'add_query_vars' ] );
		add_filter( 'display_post_states', [ $this, 'modify_menu_title' ], 10, 2 );
		add_filter( 'theme_page_templates', [ $this, 'add_new_template' ] );
		add_filter( 'wp_insert_post_data', [ $this, 'register_project_templates' ] );
		add_filter( 'template_include', [ $this, 'view_project_template' ] );
		add_action( 'before_delete_post', [ $this, 'prevent_page_deletion' ] );
		add_action( 'wp_trash_post', [ $this, 'prevent_page_deletion' ] );
		add_action( 'template_redirect', [ $this, 'handle_invalid_routes' ] );
		add_action( 'wp_nav_menu_items', [ $this, 'add_dashboard_menu_item' ], 10, 2 );
		add_filter( 'show_admin_bar', [ $this, 'hide_admin_bar_on_dashboard' ] );
	}

	/**
	 * Add rewrite rules
	 */
	public function add_rewrite_rules() {
		// Base dashboard
		add_rewrite_rule(
			'^shop-explorer-dashboard/?$',
			'index.php?pagename=shop-explorer-dashboard',
			'top'
		);

		// Order edit route
		add_rewrite_rule(
			'^shop-explorer-dashboard/orders/edit/(\d+)/?$',
			'index.php?pagename=shop-explorer-dashboard&se_section=orders&se_action=edit&order_id=$matches[1]',
			'top'
		);

		// Order details route
		add_rewrite_rule(
			'^shop-explorer-dashboard/orders/details/(\d+)/?$',
			'index.php?pagename=shop-explorer-dashboard&se_section=orders&se_action=details&order_id=$matches[1]',
			'top'
		);

		// Product edit route
		add_rewrite_rule(
			'^shop-explorer-dashboard/products/edit/(\d+)/?$',
			'index.php?pagename=shop-explorer-dashboard&se_section=products&se_action=edit&product_id=$matches[1]',
			'top'
		);

		// Two-level routes (section/action)
		add_rewrite_rule(
			'^shop-explorer-dashboard/([^/]+)/([^/]+)/?$',
			'index.php?pagename=shop-explorer-dashboard&se_section=$matches[1]&se_action=$matches[2]',
			'top'
		);

		// Single level routes
		add_rewrite_rule(
			'^shop-explorer-dashboard/([^/]+)/?$',
			'index.php?pagename=shop-explorer-dashboard&se_section=$matches[1]',
			'top'
		);
	}

	/**
	 * Add query vars
	 */
	public function add_query_vars( $vars ) {
		$vars[] = 'se_section';
		$vars[] = 'se_action';
		$vars[] = 'order_id';
		$vars[] = 'product_id';
		return $vars;
	}

	/**
	 * Handle invalid routes
	 */
	public function handle_invalid_routes() {
		if ( ! is_page( 'shop-explorer-dashboard' ) ) {
			return;
		}

		$section    = get_query_var( 'se_section' );
		$action     = get_query_var( 'se_action' );
		$order_id   = get_query_var( 'order_id' );
		$product_id = get_query_var( 'se_product_id' );

		// If no section, it's dashboard
		if ( ! $section ) {
			return;
		}

		// Add order statuses to valid routes
		$order_statuses = wc_get_order_statuses();
		foreach ( $order_statuses as $key => $_ ) {
			$status = str_replace( 'wc-', '', $key );
			$this->valid_routes['orders'][] = $status;
		}

		// Add edit and details as valid actions
		$this->valid_routes['orders'][] = 'edit';
		$this->valid_routes['orders'][] = 'details';

		// Validate section
		if ( ! isset( $this->valid_routes[ $section ] ) ) {
			$this->redirect_to_dashboard();
			return;
		}

		// Special handling for order edit and details
		if ( $section === 'orders' && ( $action === 'edit' || $action === 'details' ) ) {
			if ( ! $order_id || ! is_numeric( $order_id ) ) {
				$this->redirect_to_dashboard();
				return;
			}
			$order = wc_get_order( $order_id );
			if ( ! $order ) {
				$this->redirect_to_dashboard();
				return;
			}
			return;
		}

		// Special handling for product edit
		if ( $section === 'products' && $action === 'edit' ) {
			if ( ! $product_id || ! is_numeric( $product_id ) ) {
				$this->redirect_to_dashboard();
				return;
			}
			$product = wc_get_product( $product_id );
			if ( ! $product ) {
				$this->redirect_to_dashboard();
				return;
			}
			return;
		}

		// Validate action if present
		if ( $action && ! in_array( $action, $this->valid_routes[ $section ], true ) ) {
			$this->redirect_to_dashboard();
			return;
		}
	}

	/**
	 * Redirect to dashboard
	 */
	private function redirect_to_dashboard() {
		wp_safe_redirect( home_url( '/shop-explorer-dashboard/' ) );
		exit;
	}

	/**
	 * Plugin activation handler
	 */
	public function activate() {
		$this->create_dashboard_page();
		$this->add_rewrite_rules();
		flush_rewrite_rules();
	}

	/**
	 * Create dashboard page
	 */
	private function create_dashboard_page() {
		if ( $this->page_exists() ) {
			return;
		}

		$page_id = wp_insert_post(
			[
				'post_title'    => $this->page_title,
				'post_content'  => '',
				'post_status'   => 'publish',
				'post_type'     => 'page',
				'post_name'     => 'shop-explorer-dashboard',
				'meta_input'    => [
					'_wp_page_template' => $this->template_path,
				],
			]
		);

		if ( ! is_wp_error( $page_id ) ) {
			update_option( 'shop_explorer_dashboard_page_id', $page_id );
		}
	}

	/**
	 * Check if dashboard page exists
	 */
	private function page_exists() {
		// First check if we have a stored page ID
		$page_id = get_option( 'shop_explorer_dashboard_page_id' );

		if ( $page_id ) {
			$page = get_post( $page_id );
			// If page exists and is published, we're good
			if ( $page && $page->post_status === 'publish' ) {
				return true;
			}
			// Page was deleted or trashed, clear the option
			delete_option( 'shop_explorer_dashboard_page_id' );
		}

		// Check if a page with this title exists
		$query = new \WP_Query(
			[
				'post_type'      => 'page',
				'post_status'    => 'publish',
				'title'          => $this->page_title,
				'posts_per_page' => 1,
			]
		);

		if ( $query->have_posts() ) {
			// Update the stored page ID
			$posts = $query->get_posts();
			update_option( 'shop_explorer_dashboard_page_id', $posts[0]->ID );
			return true;
		}

		return false;
	}

	/**
	 * Prevent dashboard page deletion
	 */
	public function prevent_page_deletion( $post_id ) {
		if ( $post_id === get_option( 'shop_explorer_dashboard_page_id' ) ) {
			wp_die( esc_html__( 'This page is required for the Shop Explorer plugin and cannot be deleted.', 'shop-explorer' ) );
		}
	}

	/**
	 * Add new template to the page attributes dropdown
	 */
	public function add_new_template( $posts_templates ) {
		$posts_templates[ $this->template_path ] = $this->template_name;
		return $posts_templates;
	}

	/**
	 * Register project templates
	 */
	public function register_project_templates( $atts ) {
		$cache_key = 'shop_explorer_page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
		$templates = wp_cache_get( $cache_key, 'themes' );
		if ( false === $templates ) {
			$templates = [];
		}

		wp_cache_delete( $cache_key, 'themes' );
		$templates = array_merge( $templates, [ $this->template_path => $this->template_name ] );
		wp_cache_set( $cache_key, $templates, 'themes', 1800 );

		return $atts;
	}

	/**
	 * Load the custom template file
	 */
	public function view_project_template( $template ) {
		global $post;

		if ( ! $post || get_page_template_slug( $post->ID ) !== $this->template_path ) {
			return $template;
		}

		return SHOPEX_PATH . 'inc/' . $this->template_path;
	}

	/**
	 * Modify menu title
	 */
	public function modify_menu_title( $post_states, $post ) {
		if ( $post->ID === get_option( 'shop_explorer_dashboard_page_id' ) ) {
			$post_states['shop_explorer_dashboard_page'] = $this->template_name;
		}
		return $post_states;
	}

	/**
	 * Add dashboard menu item to navigation menus
	 */
	public function add_dashboard_menu_item( $items, $args ) {
		// Only add for logged in users with proper permissions
		if ( ! is_user_logged_in() ) {
			return $items;
		}

		$user = wp_get_current_user();
		$roles_to_check = [ 'administrator', 'shop_manager', 'editor' ];
		$has_permission = false;

		foreach ( $roles_to_check as $check_role ) {
			if ( in_array( $check_role, $user->roles, true ) ) {
				$has_permission = true;
				break;
			}
		}

		if ( ! $has_permission ) {
			return $items;
		}

		// Check if frontend dashboard is enabled
		$settings = get_option( 'shop_explorer_frontend_settings', [] );
		if ( empty( $settings['orders_management']['enabled'] ) && empty( $settings['products_management']['enabled'] ) ) {
			return $items;
		}

		// Add dashboard menu item
		$dashboard_url = home_url( '/shop-explorer-dashboard/' );
		$menu_item = '<li class="menu-item menu-item-shop-explorer-dashboard">';
		$menu_item .= '<a href="' . esc_url( $dashboard_url ) . '">' . esc_html__( '📊 Dashboard', 'shop-explorer' ) . '</a>';
		$menu_item .= '</li>';

		// Add to the end of the menu
		$items .= $menu_item;

		return $items;
	}

	/**
	 * Hide admin bar on frontend dashboard
	 */
	public function hide_admin_bar_on_dashboard( $show ) {
		// Hide admin bar on frontend dashboard page
		if ( is_page( 'shop-explorer-dashboard' ) ) {
			return false;
		}

		return $show;
	}
}
