<?php
namespace WPKIN_SHOP_MANAGER;

if ( ! defined( 'ABSPATH' ) ) {
	wp_die( esc_html__( 'You can\'t access this page', 'shop-manager' ) );
}

/**
 * Page Template Handler Class
 *
 * @since 1.0.0
 */
class Page_Template {
    /**
     * Page template path
     *
     * @var string
     */
    private $template_path = 'templates/wpkin-sm-dashboard.php';

    /**
     * Page template name
     *
     * @var string
     */
    private $template_name = 'SM Dashboard';

    /**
     * Page title
     *
     * @var string
     */
    private $page_title = 'SM Dashboard';

    /**
     * Plugin file path
     *
     * @var string
     */
    private $plugin_file;

    /**
     * Valid routes array
     *
     * @var array
     */
    private $valid_routes = [
        'orders' => [
            'add-order',
			'details',
			'all',
			'trash',
            // status routes will be added dynamically
        ],
        'products' => [
            'add-product',
            'all',
            'categories',
            'tags',
            'brands',
            'attributes',
            'reviews',
        ],
        'customers' => [
            // customer profile IDs added dynamically
        ],
        'employees' => [
            'all',
            'roles-access',
        ],
    ];

    /**
     * Page Template class constructor
     *
     * @param string $plugin_file Main plugin file path
     * @since 1.0.0
     */
    public function __construct( $plugin_file ) {
        $this->plugin_file = $plugin_file;
        $this->wpkin_init_hooks();
    }

    /**
     * Initialize WordPress hooks
     *
     * @return void
     */
    private function wpkin_init_hooks() {
        register_activation_hook( $this->plugin_file, [ $this, 'wpkin_activate' ] );
        add_action( 'init', [ $this, 'wpkin_add_rewrite_rules' ] );
        add_action( 'init', [ $this, 'wpkin_maybe_flush_rewrite_rules' ] );
        add_filter( 'query_vars', [ $this, 'wpkin_add_query_vars' ] );
        add_filter( 'display_post_states', [ $this, 'wpkin_modify_menu_title' ], 10, 2 );
        add_filter( 'theme_page_templates', [ $this, 'wpkin_add_new_template' ] );
        add_filter( 'wp_insert_post_data', [ $this, 'wpkin_register_project_templates' ] );
        add_filter( 'template_include', [ $this, 'wpkin_view_project_template' ] );
        add_action( 'before_delete_post', [ $this, 'wpkin_prevent_page_deletion' ] );
        add_action( 'wp_trash_post', [ $this, 'wpkin_prevent_page_deletion' ] );
        add_action( 'template_redirect', [ $this, 'wpkin_handle_invalid_routes' ] );
    }

    /**
     * Add rewrite rules
     *
     * @return void
     */
    public function wpkin_add_rewrite_rules() {
		// Base dashboard
		add_rewrite_rule(
			'^sm-dashboard/?$',
			'index.php?pagename=sm-dashboard',
			'top'
		);

		// Order edit route (three-level route)
		add_rewrite_rule(
			'^sm-dashboard/orders/edit/(\d+)/?$',
			'index.php?pagename=sm-dashboard&sc_section=orders&sc_action=edit&order_id=$matches[1]',
			'top'
		);

		// Order details route (three-level route)
		add_rewrite_rule(
			'^sm-dashboard/orders/details/(\d+)/?$',
			'index.php?pagename=sm-dashboard&sc_section=orders&sc_action=details&order_id=$matches[1]',
			'top'
		);

		// Product edit route (three-level route)
		add_rewrite_rule(
			'^sm-dashboard/products/edit/(\d+)/?$',
			'index.php?pagename=sm-dashboard&sc_section=products&sc_action=edit&product_id=$matches[1]',
			'top'
		);

		// Customer profile route (customers/{id})
		add_rewrite_rule(
			'^sm-dashboard/customers/(\d+)/?$',
			'index.php?pagename=sm-dashboard&sc_section=customers&sc_action=$matches[1]',
			'top'
		);

		// Employee profile route (employees/{id})
		add_rewrite_rule(
			'^sm-dashboard/employees/(\d+)/?$',
			'index.php?pagename=sm-dashboard&sc_section=employees&sc_action=$matches[1]',
			'top'
		);

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

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

    /**
     * Add query vars
     *
     * @param array $vars
     * @return array
     */
    public function wpkin_add_query_vars( $vars ) {
        $vars[] = 'sc_section';
        $vars[] = 'sc_action';
        $vars[] = 'order_id';
        $vars[] = 'product_id';
        $vars[] = 'sm_action';
        $vars[] = 'sm_key';
        $vars[] = 'sm_login';
        return $vars;
    }

    /**
     * Handle invalid routes
     *
     * @return void
     */
    public function wpkin_handle_invalid_routes() {
		if ( ! is_page( 'sm-dashboard' ) ) {
			return;
		}

		$settings = get_option( 'wpkin_sm_admin_settings', [] );

		if ( ! $settings ) {
			return;
		}

		$section    = get_query_var( 'sc_section' );
		$action     = get_query_var( 'sc_action' );
		$order_id   = get_query_var( 'order_id' );
		$product_id = get_query_var( 'product_id' );

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

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

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

		// Validate section
		if ( ! isset( $this->valid_routes[ $section ] ) ) {
			$this->wpkin_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->wpkin_redirect_to_dashboard();
				return;
			}
			// Verify if order exists
			$order = wc_get_order( $order_id );
			if ( ! $order ) {
				$this->wpkin_redirect_to_dashboard();
				return;
			}
			return;
		}

		// Special handling for customer profile
		if ( $section === 'customers' && $action && is_numeric( $action ) ) {
			return; // valid customer profile URL — React handles rendering
		}

		// Special handling for employee profile
		if ( $section === 'employees' && $action && is_numeric( $action ) ) {
			return; // valid employee profile URL — React handles rendering
		}

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

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

    /**
     * Redirect to dashboard
     *
     * @return void
     */
    private function wpkin_redirect_to_dashboard() {
        wp_safe_redirect( home_url( '/sm-dashboard/' ) );
        exit;
    }

    /**
     * Plugin activation handler
     *
     * @return void
     */
    public function wpkin_activate() {
        $this->wpkin_create_dashboard_page();
        $this->wpkin_add_rewrite_rules();
        flush_rewrite_rules();
    }

    public function wpkin_maybe_flush_rewrite_rules() {
        if ( get_option( 'wpkin_rewrite_version' ) !== '1.1' ) {
            flush_rewrite_rules();
            update_option( 'wpkin_rewrite_version', '1.1' );
        }
    }

    /**
     * Create dashboard page
     *
     * @return void
     */
    private function wpkin_create_dashboard_page() {
        if ( $this->wpkin_page_exists() ) {
            return;
        }

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

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

    /**
     * Check if dashboard page exists
     *
     * @return bool
     */
    private function wpkin_page_exists() {
        $query = new \WP_Query(
            [
				'post_type'      => 'page',
				'post_status'    => 'publish',
				'title'          => $this->page_title,
				'posts_per_page' => 1,
			]
        );

        return $query->have_posts();
    }

    /**
     * Prevent dashboard page deletion
     *
     * @param int $post_id
     * @return void
     */
    public function wpkin_prevent_page_deletion( $post_id ) {
        if ( $post_id === get_option( 'wpkin_page_id' ) ) {
            wp_die( esc_html__( 'This page is required for the Shop Manager plugin and cannot be deleted.', 'shop-manager' ) );
        }
    }

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

    /**
     * Register project templates
     *
     * @param array $atts
     * @return array
     */
    public function wpkin_register_project_templates( $atts ) {
        $cache_key = 'wpkin_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
     *
     * @param string $template
     * @return string
     */
    public function wpkin_view_project_template( $template ) {
        global $post;

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

        return plugin_dir_path( __FILE__ ) . $this->template_path;
    }

    /**
     * Modify menu title
     *
     * @param array $post_states
     * @param \WP_Post $post
     * @return array
     */
    public function wpkin_modify_menu_title( $post_states, $post ) {
        if ( $post->ID === get_option( 'wpkin_page_id' ) ) {
            $post_states['sm_dashboard_page'] = $this->template_name;
        }
        return $post_states;
    }
}
