<?php
    /**
     * Includes: Metaboxes

     */
    if (! defined('ABSPATH')) {
        die('Sorry, you cannot access this page.');
    }

    function chama_comments_restrict_replying($comments, $post_id)
    {
        global $chama_closed_comments;
        global $chama_request_email_verification;
        global $current_user;

        $chama_closed_comments            = false;
        $chama_request_email_verification = false;

        if (empty($comments)) {
            return $comments; // If comments are empty or closed, then we don't need to check.
        }

        // Show for administrators
        if (current_user_can('manage_options')) {
            return $comments;
        }

        //check if content is protected
        $protection_data = chama_get_protection_data($post_id);
        $is_protected    = $protection_data['is_protected'];
        $post_level      = $protection_data['post_level'];

        $require_membership = get_option('chama_require_mebership_for_comments');
        //not protected and comments not protected
        if (! $is_protected && ! $require_membership) {
            return $comments;
        }

        //if post is not protected, but comments are protected, check if user is has verified email
        if (! empty($current_user->ID)) {
            if (! $is_protected && $require_membership) {
                if (($current_user && in_array('chama_complimentary', (array) $current_user->roles)) || ($current_user && in_array('chama_member', (array) $current_user->roles))) {
                    return $comments;
                }
                $is_email_verified = get_user_meta($current_user->ID, 'is_email_verified', true);
                if (! $is_email_verified) {
                    if (is_array($comments)) {
                        return []; // In comments_array filter.
                    } else {
                        $chama_request_email_verification = true;
                        return false; // In comments_open filter.
                    }
                }
            }
        }

        //if we have reached this point, post is protected and we need to check access level
        // Check if the current user can access the comment
        if (empty($current_user->ID) || ! chama_can_user_access_post($post_level, $current_user->ID)) {
            if (is_array($comments)) {
                return []; // In comments_array filter.
            } else {
                $chama_closed_comments = true;
                return false; // In comments_open filter.
            }
        }

        return $comments;
    }
    add_filter("comments_array", "chama_comments_restrict_replying", 10, 2);
    add_filter('comments_open', 'chama_comments_restrict_replying', 20, 2);
    add_filter('pings_open', 'chama_comments_restrict_replying', 20, 2);
    function chama_remove_theme_string($translation, $text, $domain)
    {
        global $chama_closed_comments;
        global $chama_request_email_verification;
        if (is_admin()) {
            return $translation;
        }

        $translations = &get_translations_for_domain($domain);
        if ('Comments are closed.' === $text) {
            if ($chama_closed_comments) {
                if (is_user_logged_in()) {
                    return esc_html(apply_filters('chama_comments_restriction_message_non_members', '&#x1F464;' . __('Comments are restricted for your membership level.', 'chama')));
                } else {
                    return esc_html(apply_filters('chama_comments_restriction_message_logged_out', '&#x1F512;' . __('You must be logged in to view the comments.', 'chama')));
                }

            }
            if ($chama_request_email_verification) {
                if (is_user_logged_in()) {
                    return esc_html(apply_filters('chama_comments_restriction_message_email_not_verified', '&#x2709; ' . __('You must verify your email address to comment.', 'chama')));
                }
            }
        }

        return $translation;
    }
    add_filter('gettext', 'chama_remove_theme_string', 20, 3);

    function chama_get_protection_data($post_id)
    {

        //check post
        $post_level = get_post_meta($post_id, 'chama_tier_level', true);
        $protected  = $post_level === '0' ? true : $post_level;
        if ($protected) {
            return [
                'post_level'   => $post_level,
                'is_protected' => true,
            ];
        }

        //check taxonomy/category
        $post_type = get_post_type($post_id);

        if ($post_type === 'post') {
            $categories = get_the_category($post_id);
            if (! is_array($categories)) {
                return [
                    'post_level'   => false,
                    'is_protected' => false,
                ];
            }
            foreach ($categories as $category) {
                $post_level = get_term_meta($category->term_id, 'chama_tier_level', true);
                $protected  = $post_level === '0' ? true : $post_level;
                if ($protected) {
                    return [
                        'post_level'   => $post_level,
                        'is_protected' => true,
                    ];
                }
                if ($category->parent !== 0) {
                    $parent_ids = get_ancestors($category->term_id, 'category');
                    foreach ($parent_ids as $parent_id) {
                        $post_level = get_term_meta($parent_id, 'chama_tier_level', true);
                        $protected  = $post_level === '0' ? true : $post_level;
                        if ($protected) {
                            return [
                                'post_level'   => $post_level,
                                'is_protected' => true,
                            ];
                        }
                    }
                }

            }

        } else if (! in_array($post_type, ['post', 'page'], true)) {
            $parent_id = wp_get_post_parent_id($post_id);
            if ($parent_id) {
                $parent_level = get_post_meta($parent_id, 'chama_tier_level', true);
                $protected    = $parent_level === '0' ? true : $parent_level;
                if ($protected) {
                    return [
                        'post_level'   => $parent_level,
                        'is_protected' => true,
                    ];
                }
            }
        } else if ($post_type === 'page') {
            return [
                'post_level'   => false,
                'is_protected' => false,
            ];
        } else {
            //get all post terms
            $cpt_taxonomies = get_post_taxonomies($post_id);
            $post_term_ids  = [];
            foreach ($cpt_taxonomies as $cpt_taxonomy) {
                // retrieve all available terms, including those not yet used
                $terms_by_id = get_the_terms($post_id, $cpt_taxonomy);

                if (is_array($terms_by_id) && $terms_by_id) {
                    foreach ($terms_by_id as $term) {
                        $post_term_ids[] = [$term->term_id, $term->parent, $term->taxonomy];
                    }

                }
            }
            foreach ($post_term_ids as $post_term_id) {
                $post_level = get_term_meta($post_term_id[0], 'chama_tier_level', true);
                $protected  = $post_level === '0' ? true : $post_level;
                if ($protected) {
                    return [
                        'post_level'   => $post_level,
                        'is_protected' => true,
                    ];
                }
                if ($post_term_id[1] !== 0) {
                    $parent_ids = get_ancestors($post_term_id[0], $post_term_id[2]);
                    foreach ($parent_ids as $parent_id) {
                        $post_level = get_term_meta($parent_id, 'chama_tier_level', true);
                        $protected  = $post_level === '0' ? true : $post_level;
                        if ($protected) {
                            return [
                                'post_level'   => $post_level,
                                'is_protected' => true,
                            ];
                        }

                    }
                }
            }

        }

        //check global restriction
        $post_option       = 'chama_' . $post_type . '_post_type';
        $global_post_level = get_option($post_option);
        $protected         = $global_post_level === '0' ? true : $global_post_level;
        if ($protected) {
            return [
                'post_level'   => $global_post_level,
                'is_protected' => true,
            ];
        }

        return [
            'post_level'   => false,
            'is_protected' => false,
        ];
    }

    function chama_can_user_access_post($post_level, $user_id)
    {

        if ($user_id) {
            //check if complimentary
            // Always get the correct user object (even if logged in as someone else)
            $user_info = null;
            if (get_current_user_id() === intval($user_id)) {
                // Use global if we're checking the logged-in user
                global $current_user;
                wp_get_current_user();
                $user_info = $current_user;
            } else {
                // Otherwise, load user by ID
                $user_info = get_userdata($user_id);
            }

            // Complimentary role check
            if ($user_info && in_array('chama_complimentary', (array) $user_info->roles)) {
                return true;
            }

            $require_require_email_verification = get_option('chama_require_email_verification');
            $is_email_verified                  = get_user_meta($user_id, 'is_email_verified', true);
            if ($require_require_email_verification && ! $is_email_verified && strlen($post_level) !== 0) {
                return false;
            }
            $subscription_level           = get_user_meta($user_id, 'chama_subscription_level', true);
            $current_period_end           = get_user_meta($user_id, 'chama_subscription_current_period_end', true);
            $current_period_end           = str_replace(',', '', $current_period_end);
            $current_period_end_timestamp = strtotime($current_period_end);
            $today                        = gmdate('Y-m-d');
            $today_timestamp              = strtotime($today);
            if ($post_level) {
                if ($current_period_end_timestamp < $today_timestamp) {
                    return false;
                }
                if (floatval($subscription_level) < floatval($post_level)) {
                    return false;
                } else {
                    return true;
                }
            } elseif ($post_level === '0') {
                if ($subscription_level && $current_period_end_timestamp < $today_timestamp) {
                    return false;
                } else {

                    if ($is_email_verified) {
                        return true;
                    }
                }
            } else {
                return true;
            }

        } else {
            if ($post_level || $post_level === '0') {
                return false;
            } else {
                return true;
            }
        }
    }
    add_filter('the_content', 'chama_restrict_content', 15);
    add_filter('the_content_rss', 'chama_restrict_content', 15);
    function chama_restrict_content($content)
    {
        global $post, $current_user;
        $post_type           = get_post_type($post->ID);
        $excluded_post_types = ['chama_tier', 'chama_commission', 'chama_campaign', 'chama_donation', 'chama_fund', 'chama_com_order', 'chama_subscription', 'slide'];
        if ($post && in_array($post->post_type, $excluded_post_types)) {
            return $content;
        }
        // Make sure that we are on the frontend and have a post ID.
        if (empty($post->ID) || current_user_can('manage_options')) {
            return $content;
        }

        $protection_data      = chama_get_protection_data($post->ID);
        $is_protected         = $protection_data['is_protected'];
        $post_level           = $protection_data['post_level'];
        $post_level_formatted = CHAMA_SYMBOL . number_format((float) $post_level, 2, '.', '');
        if (! chama_can_user_access_post($post_level, $current_user->ID)) {
            $enabled_more_tag = get_option('chama_more_tag_protection');
            if ($enabled_more_tag) {
                //$post_segments = explode('<!--more-->', $content);
                if (strpos($content, "<span id=\"more-" . $post->ID . "\"></span>") !== false) {
                    // More tag.
                    $pos     = strpos($content, "<span id=\"more-" . $post->ID . "\"></span>");
                    $content = substr($content, 0, $pos);
                } elseif (strpos($content, 'class="more-link">') !== false) {
                    // More link.
                    $content = preg_replace("/\<a.*class\=\"more\-link\".*\>.*\<\/a\>/", "", $content);
                } elseif (strpos($content, "<!-- wp:more -->") !== false) {
                    // More block.
                    $pos     = strpos($content, "<!-- wp:more -->");
                    $content = substr($content, 0, $pos);
                } elseif (strpos($content, "<!--more-->") !== false) {
                    // More tag.
                    $pos     = strpos($content, "<!--more-->");
                    $content = substr($content, 0, $pos);
                } else {
                    $content = '';
                }
            } else {
                $content = '';
            }
            ob_start();
            chama_restricted_content_message($post_level_formatted);
            $content .= ob_get_clean();
        }

        return $content;
    }

    function chama_restricted_content_message($post_level)
    {
        // Enqueue the registered style
        wp_enqueue_style('chama-protected-content');
        ob_start();
        $protection_message = '';
        if (str_contains($post_level, '0.01')) {
            $protection_message = 'Only paying members can access this content';
        } else {
            $protection_message = 'Only for members signed up for at least the ' . $post_level . ' level';
        }
    ?>

	<div class="chama-protected-content-cta" >
		<?php
            if (! is_user_logged_in()) {
                    // User not logged in. Show CTA for login
                ?>
			<h1 style="font-size: 60px;">&#x1F512;</h1>
            <h2 style="font-weight: bold; color: #fff;" >Only members can access this content.</h2>
            <p><?php
                   $allowed_html = [
                               'a' => [
                                   'class'  => [],
                                   'href'   => [],
                                   'id'     => [],
                                   'target' => [],
                                   'title'  => [],
                               ],
                           ];
                           /* translators: %s login for access. */
                       echo wp_kses(sprintf(__('<a href="%s" class="chama-cta-button">Login for access</a>', 'chama'), CHAMA_LOGIN_URL), $allowed_html);
                       ?></p>


			<?php
                } else {
                        // User is logged in. Show sign up for membership
                    ?>
				<h1 style="font-size: 60px;">&#x1F512;</h1>
                <h2 style="font-weight: bold; color: #fff;" ><?php echo esc_html($protection_message); ?></h2>
                <p><?php
                       $allowed_html = [
                                   'a' => [
                                       'class'  => [],
                                       'href'   => [],
                                       'id'     => [],
                                       'target' => [],
                                       'title'  => [],
                                   ],
                               ];
                               /* translators: %s upgrade link. */
                           echo wp_kses(sprintf(__('<a href="%s" class="chama-cta-button">Upgrade</a>', 'chama'), CHAMA_MEMBERSHIP_URL), $allowed_html);
                           ?></p>
			<?php
                }
                ?>
	</div>
	<?php
        $restricted_content_message = ob_get_clean();

            $restricted_content_message = apply_filters('chama_restricted_content_message', $restricted_content_message);

            echo wp_kses($restricted_content_message, chama_allowed_html());
        }
        // define the post_thumbnail_html callback
        function chama_filter_post_thumbnail($html, $post_id, $post_thumbnail_id, $size, $attr)
        {
            global $current_user;
            // Make sure that we are on the frontend and have a post ID.
            if (empty($post_id) || current_user_can('manage_options')) {
                return $html;
            }
            $protection_data = chama_get_protection_data($post_id);
            $is_protected    = $protection_data['is_protected'];
            $post_level      = $protection_data['post_level'];
            if (! chama_can_user_access_post($post_level, $current_user->ID)) {
                return '<img src="' . esc_attr(CHAMA_ASSETS_URL . 'img/chama_locked_featured.jpg') . '" />';
            }
            return $html;

        };

        // add the filter
        add_filter('post_thumbnail_html', 'chama_filter_post_thumbnail', 10, 5);

        function chama_format_raw_content($raw_content)
        {
            $formatted_content = wptexturize($raw_content);
            $formatted_content = convert_smilies($formatted_content);
            $formatted_content = convert_chars($formatted_content);
            $formatted_content = wpautop($formatted_content);
            $formatted_content = shortcode_unautop($formatted_content);
            $formatted_content = prepend_attachment($formatted_content);
            $formatted_content = capital_P_dangit($formatted_content);
            $formatted_content = do_shortcode($formatted_content);
            $formatted_content = do_blocks($formatted_content);

            $formatted_content = apply_filters('chama_format_raw_content_display', $formatted_content);

            return $formatted_content;
        }
        //Toocheke support
        function chama_toocheke_post_meta_handler($metadata, $post_id, $meta_key, $single)
        {
            include_once ABSPATH . 'wp-admin/includes/plugin.php';
            if (is_plugin_active('toocheke-companion/toocheke-companion.php')) {
                if ($meta_key === 'chama_tier_level') {
                    return $metadata;
                }
                // $meta_data_to_filter = array('desktop_comic_editor', 'comic_blog_post_editor', 'mobile_comic_2nd_language_editor', 'comic_2nd_language_blog_post_editor', 'desktop_comic_2nd_language_editor', 'transcript');
                $meta_data_to_filter = ['desktop_comic_editor', 'mobile_comic_2nd_language_editor', 'desktop_comic_2nd_language_editor', 'transcript', 'manga_chapter_pages'];
                if (! in_array($meta_key, $meta_data_to_filter)) {
                    return $metadata;
                }
                $post_type = get_post_type($post_id);

                if ( $post_type !== 'comic' && $post_type !== 'manga_chapter' ) {
                return $metadata;
                }
                return chama_restrict_metadata($metadata, $post_id);
            }

            // Return original if the check does not pass
            return $metadata;

        }
        function chama_restrict_metadata($metadata, $post_id)
        {

            global $current_user;
            global $chama_hide_content;
            $chama_hide_content = false;

            // Make sure that we are on the frontend and have a post ID.
            if (current_user_can('manage_options')) {
                return $metadata;
            }

            $protection_data      = chama_get_protection_data($post_id);
            $is_protected         = $protection_data['is_protected'];
            $post_level           = $protection_data['post_level'];
            $post_level_formatted = CHAMA_SYMBOL . number_format((float) $post_level, 2, '.', '');
            if (! chama_can_user_access_post($post_level, $current_user->ID)) {
                $chama_hide_content = true;
                $metadata           = '';
                ob_start();
                chama_restricted_content_message($post_level_formatted);
                $metadata .= ob_get_clean();
                return $metadata;
            }

            return $metadata;
    }
    add_filter('get_post_metadata', 'chama_toocheke_post_meta_handler', 100, 4);