<?php
class kavehpageHandler {

    public $options;
    
    public function __construct() {

        if ( class_exists( 'woocommerce' )){
            $guest_checkout_enabled = get_option('woocommerce_enable_guest_checkout');
            add_action('after_setup_theme', array($this, 'createLoginPage'));
            add_filter('page_template', array($this, 'setLoginPageTemplate'));
            $this->options = kaveh_get_options();
            if($this->options['kaveh_login_redirect'] === '1'){    
                add_action('template_redirect', array($this, 'redirectToLoginPage'));
                add_action('template_redirect', array($this, 'redirect_klogin'));
                if(!empty($guest_checkout_enabled) && $guest_checkout_enabled === 'no'){
                    add_action('template_redirect', array($this, 'redirectToLoginPagefromCheckout'));
                }
            }
        }
    }

    public function createLoginPage() {
        $slug = 'klogin';
        $page = get_page_by_path($slug);

        if (!$page) {
            $page_data = array(
                'post_title' => __('Login to Site', 'kavehTheme'),
                'post_name' => $slug,
                'post_status' => 'publish',
                'post_type' => 'page'
            );
            wp_insert_post($page_data);
        }
    }

    public function setLoginPageTemplate($page_template) {
        if (is_page('klogin')) {
            $page_template = KAVEH_TEMPLATE_PATH . '/page-login.php';
        }
        return $page_template;
    }

    public function redirect_klogin() {
        if (is_user_logged_in() && is_page('klogin')) {
            $url = get_permalink( get_option('woocommerce_myaccount_page_id') );
            wp_safe_redirect( $url);
        }
    }

    public function redirectToLoginPage() {
        if (!is_user_logged_in() && (is_account_page() || is_page('dashboard'))) {
            $panel_url = add_query_arg( 'redirect_to_panel', 'true', get_permalink( get_option('woocommerce_myaccount_page_id') ) );
            wp_redirect( home_url( 'klogin?redirect_to=' . urlencode( $panel_url ) ) );
            exit;
        }
    }

    public function redirectToLoginPagefromCheckout() {
        if ( ! is_user_logged_in() && is_checkout() )  {
            $checkout_url = add_query_arg( 'redirect_to_checkout', 'true', wc_get_checkout_url() );
            wp_redirect( home_url( 'klogin?redirect_to=' . urlencode( $checkout_url ) ) );
            exit;
        }
    }
    
}