<?php
/**
 * Post View Control Frontend
 *
 * @package WPUF_Pro
 * @since 4.2.6
 */

namespace WeDevs\Wpuf\Pro\Post_View_Control;

// don't call the file directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Frontend class for Post View Control
 *
 * @since 4.2.6
 */
class Frontend {

    /**
     * Class constructor
     *
     * @since 4.2.6
     */
    public function __construct() {
        add_filter( 'the_content', [ $this, 'filter_post_content' ] );
    }

    /**
     * Filter post content for restricted posts
     *
     * @since 4.2.6
     *
     * @param string $content Post content
     * @return string Modified content
     */
    public function filter_post_content( $content ) {
        global $post;

        if ( ! $post || ! $this->has_view_control_enabled( $post ) ) {
            return $content;
        }

        if ( ! $this->user_can_view_post( $post ) ) {
            return $this->get_restricted_message( $post );
        }

        return $content;
    }

    /**
     * Check if post has view control enabled
     *
     * @since 4.2.6
     *
     * @param \WP_Post $post Post object
     * @return bool
     */
    private function has_view_control_enabled( $post ) {
        $form_id = get_post_meta( $post->ID, '_wpuf_form_id', true );

        if ( ! $form_id ) {
            return false;
        }

        $form_settings = wpuf_get_form_settings( $form_id );

        // Check if either role-based or subscription-based view control is enabled
        $role_enabled = ! empty( $form_settings['view_control_role_enabled'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['view_control_role_enabled'] );
        $subscription_enabled = ! empty( $form_settings['view_control_subscription_enabled'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['view_control_subscription_enabled'] );

        return $role_enabled || $subscription_enabled;
    }

    /**
     * Check if current user can view the post
     *
     * @since 4.2.6
     *
     * @param \WP_Post $post Post object
     * @return bool
     */
    private function user_can_view_post( $post ) {
        // Administrators always have access
        if ( current_user_can( 'administrator' ) ) {
            return true;
        }

        $form_id = get_post_meta( $post->ID, '_wpuf_form_id', true );
        $form_settings = wpuf_get_form_settings( $form_id );

        $role_enabled = ! empty( $form_settings['view_control_role_enabled'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['view_control_role_enabled'] );
        $subscription_enabled = ! empty( $form_settings['view_control_subscription_enabled'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['view_control_subscription_enabled'] );

        // If both are enabled, user must have both role AND subscription
        if ( $role_enabled && $subscription_enabled ) {
            return $this->user_has_required_role( $form_settings ) && $this->user_has_required_subscription( $form_settings );
        }

        // If only role is enabled
        if ( $role_enabled ) {
            return $this->user_has_required_role( $form_settings );
        }

        // If only subscription is enabled
        if ( $subscription_enabled ) {
            return $this->user_has_required_subscription( $form_settings );
        }

        // If neither is enabled, allow access
        return true;
    }

    /**
     * Check if user has required role
     *
     * @since 4.2.6
     *
     * @param array $form_settings Form settings
     * @return bool
     */
    private function user_has_required_role( $form_settings ) {
        if ( ! is_user_logged_in() ) {
            return false;
        }

        $allowed_roles = ! empty( $form_settings['view_control_roles'] ) ? $form_settings['view_control_roles'] : [];

        if ( empty( $allowed_roles ) ) {
            return false;
        }

        $user = wp_get_current_user();

        foreach ( $allowed_roles as $role ) {
            if ( in_array( $role, $user->roles, true ) ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if user has required subscription
     *
     * @since 4.2.6
     *
     * @param array $form_settings Form settings
     * @return bool
     */
    private function user_has_required_subscription( $form_settings ) {
        if ( ! is_user_logged_in() ) {
            return false;
        }

        $allowed_subscriptions = ! empty( $form_settings['view_control_subscriptions'] ) ? $form_settings['view_control_subscriptions'] : [];

        if ( empty( $allowed_subscriptions ) ) {
            return false;
        }

        $user_id = get_current_user_id();

        // Check if user has any of the required subscription packs
        foreach ( $allowed_subscriptions as $pack_id ) {
            if ( $this->user_has_subscription_pack( $user_id, $pack_id ) ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if user has a specific subscription pack
     *
     * @since 4.2.6
     *
     * @param int $user_id User ID
     * @param int $pack_id Subscription pack ID
     * @return bool
     */
    private function user_has_subscription_pack( $user_id, $pack_id ) {
        $subscription = null;

        // Try to get subscription instance using the same methods as Settings.php
        try {
            // Method 1: Use wpuf() container if available
            if ( function_exists( 'wpuf' ) && isset( wpuf()->subscription ) ) {
                $subscription = wpuf()->subscription;
            }
            // Method 2: Fallback to direct instantiation with namespace
            elseif ( class_exists( '\WeDevs\Wpuf\Admin\Subscription' ) ) {
                $subscription = new \WeDevs\Wpuf\Admin\Subscription();
            }
            // Method 3: Fallback to global class
            elseif ( class_exists( 'WPUF_Subscription' ) ) {
                $subscription = new \WPUF_Subscription();
            }
        } catch ( \Exception $e ) {
            return false;
        }

        if ( ! $subscription ) {
            return false;
        }

        $user_packs = $subscription->get_user_pack( $user_id );

        if ( ! $user_packs ) {
            return false;
        }

        // Handle different return formats from get_user_pack()
        // It can return a single array or an array of arrays
        if ( isset( $user_packs['pack_id'] ) ) {
            // Single pack format (as shown in debug log)
            if ( $user_packs['pack_id'] == $pack_id && $user_packs['status'] === 'completed' ) {
                return true;
            }
        } else {
            // Multiple packs format (array of arrays)
            foreach ( $user_packs as $pack ) {
                if ( isset( $pack['pack_id'] ) && $pack['pack_id'] == $pack_id && $pack['status'] === 'completed' ) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Get subscription names from subscription IDs
     *
     * @since 4.2.6
     *
     * @param array $subscription_ids Array of subscription pack IDs
     * @return string Comma-separated subscription names
     */
    private function get_subscription_names( $subscription_ids ) {
        if ( empty( $subscription_ids ) || ! is_array( $subscription_ids ) ) {
            return '';
        }

        $subscription_names = [];

        try {
            // Method 1: Use wpuf() container if available
            if ( function_exists( 'wpuf' ) && isset( wpuf()->subscription ) ) {
                $subscription = wpuf()->subscription;
            }
            // Method 2: Fallback to direct instantiation with namespace
            elseif ( class_exists( '\WeDevs\Wpuf\Admin\Subscription' ) ) {
                $subscription = new \WeDevs\Wpuf\Admin\Subscription();
            }
            // Method 3: Fallback to global class
            elseif ( class_exists( 'WPUF_Subscription' ) ) {
                $subscription = new \WPUF_Subscription();
            } else {
                return '';
            }

            foreach ( $subscription_ids as $pack_id ) {
                $pack = $subscription->get_subscription( $pack_id );
                if ( $pack && isset( $pack->post_title ) ) {
                    $subscription_names[] = $pack->post_title;
                }
            }
        } catch ( \Exception $e ) {}

        return implode( ', ', $subscription_names );
    }

    /**
     * Get restricted message
     *
     * @since 4.2.6
     *
     * @param \WP_Post $post Post object
     * @return string
     */
    private function get_restricted_message( $post ) {
        $login    = wpuf()->frontend->simple_login->get_login_url();
        $register = wpuf()->frontend->simple_login->get_registration_url();
        $form_id  = get_post_meta( $post->ID, '_wpuf_form_id', true );

        $form_settings = wpuf_get_form_settings( $form_id );
        $role_enabled  = ! empty( $form_settings['view_control_role_enabled'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['view_control_role_enabled'] );
        $subscription_enabled = ! empty( $form_settings['view_control_subscription_enabled'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['view_control_subscription_enabled'] );

        // Get subscription names if subscription control is enabled
        $subscription_names = '';
        if ( $subscription_enabled && ! empty( $form_settings['view_control_subscriptions'] ) ) {
            $subscription_names = $this->get_subscription_names( $form_settings['view_control_subscriptions'] );
        }

        // If both are enabled, show both messages
        if ( $role_enabled && $subscription_enabled ) {
            $role_message = ! empty( $form_settings['view_control_role_message'] ) ? $form_settings['view_control_role_message'] : __( 'You do not have permission to view this content.', 'wpuf-pro' );
            $subscription_message = ! empty( $form_settings['view_control_subscription_message'] ) ? $form_settings['view_control_subscription_message'] : __( 'This content requires a subscription.', 'wpuf-pro' );

            // Replace placeholders with actual links and subscription names
            $role_message = str_replace( [ '{login}', '{register}' ], [ '<a href="' . esc_url( $login ) . '">' . __( 'Login', 'wpuf-pro' ) . '</a>', '<a href="' . esc_url( $register ) . '">' . __( 'Register', 'wpuf-pro' ) . '</a>' ], $role_message );
            $subscription_message = str_replace( [ '{login}', '{register}', '{subscriptions}' ], [ '<a href="' . esc_url( $login ) . '">' . __( 'Login', 'wpuf-pro' ) . '</a>', '<a href="' . esc_url( $register ) . '">' . __( 'Register', 'wpuf-pro' ) . '</a>', esc_html( $subscription_names ) ], $subscription_message );

            return '<div class="wpuf-restricted-content">' .
                   '<p>' . $role_message . '</p>' .
                   '<p>' . $subscription_message . '</p>' .
                   '</div>';
        }

        // If only role is enabled
        if ( $role_enabled ) {
            $message = ! empty( $form_settings['view_control_role_message'] ) ? $form_settings['view_control_role_message'] : __( 'You do not have permission to view this content. Please contact the administrator.', 'wpuf-pro' );

            // Replace placeholders with actual links
            $message = str_replace( [ '{login}', '{register}' ], [ '<a href="' . esc_url( $login ) . '">' . __( 'Login', 'wpuf-pro' ) . '</a>', '<a href="' . esc_url( $register ) . '">' . __( 'Register', 'wpuf-pro' ) . '</a>' ], $message );

            return '<div class="wpuf-restricted-content"><p>' . $message . '</p></div>';
        }

        // If only subscription is enabled
        if ( $subscription_enabled ) {
            $message = ! empty( $form_settings['view_control_subscription_message'] ) ? $form_settings['view_control_subscription_message'] : __( 'This content requires a subscription. Please upgrade your account to view this content.', 'wpuf-pro' );

            // Replace placeholders with actual links and subscription names
            $message = str_replace( [ '{login}', '{register}', '{subscriptions}' ], [ '<a href="' . esc_url( $login ) . '">' . __( 'Login', 'wpuf-pro' ) . '</a>', '<a href="' . esc_url( $register ) . '">' . __( 'Register', 'wpuf-pro' ) . '</a>', esc_html( $subscription_names ) ], $message );

            return '<div class="wpuf-restricted-content"><p>' . $message . '</p></div>';
        }

        return '';
    }
}
