<?php
/*
This class will: ...
Since version 13.6
How to use it:
$iump_sign_up = new \Indeed\Ihc\JoinNou();
*/
namespace Indeed\Ihc;

class JoinNow {

    /**
     * @param void
     * @return void
     */
    public function __construct() {
        if ( (int) get_option( 'ihc_smart_sign_up_enabled', 0 ) === 0 ){
            return;
        }

        // no slug set, not need to go further
        if ( self::get_slug() === '' ){
            return;
        }

        // action on init in order to check the current request, if it contains our slug, it will redirect to checkout or register
        add_action( 'init', array( $this, 'init' ) );

        // filter on save post. dont allow to save a custom with our slug .
        add_filter( 'wp_insert_post_data', array( $this, 'dont_save_our_slug' ), 10, 2 );

        // error message in case of trying to use iump slug as post slug somewhere
        add_action( 'admin_notices', array( $this, 'error_on_slug_message' ) );
    }

    /**
     * @param void
     * @return void
     */
    public function init() {
        global $current_user;
        $slug = self::get_slug();
        if ( $this->getFirstUrlSegment() !== $slug ) {
            return;
        }

        if ( isset( $current_user->ID ) && (int)$current_user->ID > 0 ) {
            // user its logged . redirect to checkout
            $this->redirect_to_checkout();
        } else {
            // user its not logged . redirect to register page
            $this->redirect_to_register();
        }
    }

    /**
     * @param void
     * @return string
     */
    private function get_current_full_url() {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'
                   || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

        $host = $_SERVER['HTTP_HOST'];
        $request_uri = $_SERVER['REQUEST_URI'];

        $full_url = $protocol . $host . $request_uri;
        return $full_url;
    }

    /**
     * @param void
     * @return string
     */
    private static function get_slug() {
        // todo make it dynamic
        return get_option( 'ihc_smart_sign_up_slug', '' );
    }

    /**
     * @param void
     * @return string
     */
    private function getFirstUrlSegment() {
        $uri = $_SERVER['REQUEST_URI'];
        $uri = trim($uri, '/');

        $segments = explode('/', $uri);

        return isset($segments[0]) ? $segments[0] : null;
    }

    /**
     * @param string
     * @return void
     */
    private function redirect_to_checkout( $membership='' ) {
        $checkout_page_id = get_option( 'ihc_checkout_page' );
    		if ( $checkout_page_id === '' || $checkout_page_id === false || (int)$checkout_page_id === -1 ){
    				return;
    		}
    		$checkout_page_url = get_permalink( $checkout_page_id );
    		if ( $checkout_page_url === '' || $checkout_page_url === false ){
    				return;
    		}
    		$checkout_page_url = $this->prepare_redirect_page_url( $checkout_page_url, true );
    		wp_safe_redirect( $checkout_page_url );
    		exit;
    }

    /**
     * @param string
     * @return void
     */
    private function redirect_to_register( $membership='' ) {
        $register_page_id = get_option( 'ihc_general_register_default_page' );
        if ( $register_page_id === '' || $register_page_id === false || (int)$register_page_id === -1 ){
            return;
        }
        $register_page_url = get_permalink( $register_page_id );
        if ( $register_page_url === '' || $register_page_url === false ){
            return;
        }
        $register_page_url = $this->prepare_redirect_page_url( $register_page_url );
        wp_safe_redirect( $register_page_url );
        exit;
    }

    /**
     * @param string
     * @return string
     */
    private function prepare_redirect_page_url( $url = '' ) {
        if ( isset( $_GET['lid'] ) && $_GET['lid'] !== '' ){
            return add_query_arg( 'lid', sanitize_text_field( $_GET['lid'] ), $url );
        } else {
            $current_url = $this->get_current_full_url();
            $possibleMembershipSlug = $this->extractMembershipFromURL( $current_url );
            if ( $possibleMembershipSlug === '' ){
                return $url;
            }
            if ( substr( $url, -1 ) === '/' ) {
                return $url . $possibleMembershipSlug  . '/';
            } else {
                return $url . '/' . $possibleMembershipSlug  . '/';
            }
        }
    }

    /**
     * @param array
     * @param array
     * @return array
     */
    public function dont_save_our_slug( $data, $postarr ) {
        $our_slug = self::get_slug();

        if ( $our_slug === '' ){
            return $data;
        }
        if (
            isset( $data['post_name'] ) &&
            isset( $data['post_type'] ) &&
            ! in_array( $data['post_status'], ['auto-draft', 'inherit'] ) &&
            ! defined( 'DOING_AUTOSAVE' )
        ) {
            $slug = strtolower( $data['post_name'] );
            if ( $slug === $our_slug ) {
                add_filter( 'redirect_post_location', function( $location ) {
                    return add_query_arg( 'error_on_slug', '1', $location );
                });

                // force post as draft.
                $data['post_status'] = 'draft';
            }
        }
        return $data;
    }

    /**
     *
     * @param void
     * @return string ( error message )
     */
    public function error_on_slug_message(){
        if ( isset( $_GET['error_on_slug'] ) && (int)$_GET['error_on_slug'] === 1 ) {
            $slug = self::get_slug();
            echo esc_ump_content('<div class="notice notice-error is-dismissible"><p>')
            . sprintf( esc_html__('Error: The slug %s is reserved by the %s plugin and cannot be assigned to a post or page. Please select a different slug.', 'ihc' ), $slug, IHC_PLUGIN_NAME ) 
            . esc_ump_content('</p></div>');
        }
    }

    /**
     *
     * @param int ( membership id )
     * @return string ( link to register/checkout page with the membership )
     */
    public static function generate_url_for_membership( $lid=0 ) {
        if ( (int)$lid === 0 ) {
            return '';
        }
        $base_url = self::get_base_site_url();
        $slug = self::get_slug();
        // return with pretty link
        $membership_slug = \Indeed\Ihc\Db\Memberships::getMembershipName( $lid );
        if ( substr( $base_url, -1 ) === '/' ) {
            return $base_url . $slug . '/' . $membership_slug  . '/';
        } else {
            return $base_url . '/' . $slug . '/' . $membership_slug  . '/';
        }
    }

    /**
     * @param void
     * @return string ( base url )
     */
    private static function get_base_site_url() {
        $parsed = wp_parse_url( home_url() );
        $base_url = $parsed['scheme'] . '://' . $parsed['host'];
        if ( isset( $parsed['port'] ) ) {
            $base_url .= ':' . $parsed['port'];
        }
        return $base_url;
    }

    public static function can_be_used() {
        if ( (int) get_option( 'ihc_smart_sign_up_enabled', 0 ) === 0 ){
            return false;
        }
        if ( get_option( 'ihc_smart_sign_up_slug'. '' ) === '' ){
            return false;
        }
        if ( get_option( 'permalink_structure' ) === '' ){
            return false;
        }
        if ( (int)get_option( 'ihc_pretty_links', 0 ) === 0 ){
            return false;
        }
        return true;
    }

    private function extractMembershipFromURL( $url = '' )
    {
    		$meta_arr = ihc_return_meta_arr('public_workflow');

    		if ( !isset( $meta_arr['ihc_pretty_links'] ) || $meta_arr['ihc_pretty_links'] == 0 ){
    				return '';
    		}

    		if ( isset( $_GET['lid'] ) ){
    				return '';
    		}

    		$levelsAll = \Indeed\Ihc\Db\Memberships::getAll();

    		if ( empty( $levelsAll ) || !is_array( $levelsAll ) || count( $levelsAll ) == 0 ){
    				return '';
    		}
    		foreach ( $levelsAll as $key=>$value ){
    				//Convert
    				$levelSlug = $value['name'];
    				if ( strpos($url, '/' .  $levelSlug . '/') !== false ){
    						$levelReturnData = \Indeed\Ihc\Db\Memberships::getOneByName($value['name']);
    						if ( empty( $levelReturnData['id'] ) ) {
    								continue;
    						}
    						return $levelSlug;
    				}
    		}
    		return '';
    }

}
