<?php
class kavehboardpages
{
    public $dashboard_page_id;
    public $woo_redirect;

    public function __construct()
    {
        // Extract page IDs from options
        $options = get_option('kavehboard_options');
        $this->dashboard_page_id = isset($options['kavehboard_page']) ? $options['kavehboard_page'] : '';
        $this->woo_redirect = isset($options['kavehboard_woo_redirect']) ? $options['kavehboard_woo_redirect'] : false;
        // Only add filters/actions if required pages are set
        if ($this->validateRequiredPages()) {
            add_action('template_redirect', array($this, 'redirect_from_dash'));
            add_action('template_redirect', array($this, 'redirect_from_woo_my_account'));
        }
    }
    
    /**
     * Validate that required pages are set and exist
     * @return boolean
     */
    private function validateRequiredPages()
    {
        // Check if page IDs are set
        if (
            empty($this->dashboard_page_id)
        ) {
            return false;
        }
        // Verify pages exist
        $dash_page = get_post($this->dashboard_page_id);
        return ($dash_page && 'page' === $dash_page->post_type);
    }

    public function redirect_from_dash()
    {
        if (!$this->validateRequiredPages())
            return;

        // Don't redirect if user is accessing admin area
        if (is_admin() || wp_doing_ajax()) {
            return;
        }

        if (!is_user_logged_in() && is_page($this->dashboard_page_id)) {
            $url = get_permalink($this->login_page_id);
            if ($url) {
                wp_safe_redirect($url);
                exit;
            }
        }
    }

    public function redirect_from_woo_my_account()
    {
        if (!$this->validateRequiredPages())
            return;

        // Don't redirect if user is accessing admin area
        if (is_admin() || wp_doing_ajax()) {
            return;
        }

        if (
            $this->woo_redirect === '1' &&
            is_page(get_option('woocommerce_myaccount_page_id'))
        ) {
            $url = get_permalink($this->dashboard_page_id);
            if ($url) {
                wp_safe_redirect($url);
                exit;
            }
        }
    }
}