<?php

if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Homepage_Guard
{
    public const HOMEPAGE_META = '_puffergo_is_homepage';

    public const ACTIVATE_ACTION = 'puffergo_activate_homepage';

    public const DOCS_URL = 'https://puffergo.com/docs/how-to-set-your-wordpress-homepage/';

    public const DISMISSED_META_KEY = 'puffergo_homepage_notice_dismissed';

    public const DISMISS_ACTION = 'puffergo_dismiss_homepage_notice';

    public static function init(): void
    {
        add_action('admin_notices', array(__CLASS__, 'maybe_render_notice'));
        add_action('admin_post_' . self::ACTIVATE_ACTION, array(__CLASS__, 'handle_activate'));
        add_action('wp_ajax_' . self::DISMISS_ACTION, array(__CLASS__, 'handle_dismiss'));
    }

    public static function mark_as_homepage_candidate(int $page_id): void
    {
        if ($page_id > 0) {
            update_post_meta($page_id, self::HOMEPAGE_META, 1);
        }
    }

    public const DRAFT_GRACE_SECONDS = HOUR_IN_SECONDS;

    private static function find_candidate(): int
    {
        static $candidate = null;

        if (null !== $candidate) {
            return $candidate;
        } $posts = get_posts(array('post_type' => 'page', 'post_status' => array('publish', 'draft'), 'meta_key' => self::HOMEPAGE_META, 'meta_value' => 1, 'orderby' => 'modified', 'order' => 'DESC', 'posts_per_page' => 1, 'no_found_rows' => true, ));
        $candidate = ! empty($posts) ? (int) $posts[0]->ID : 0;

        return $candidate;
    }

    private static function front_page_unconfigured(): bool
    {
        return 0 === (int) get_option('page_on_front', 0) && 0 === (int) get_option('page_for_posts', 0);
    }

    private static function get_unconfigured_description(): string
    {
        return __('Your site is still showing the default blog feed — no static homepage or blog page has been set in Settings → Reading. Visitors opening your domain see a raw list of posts, which can make the site look unfinished. Set (or create) a homepage so they land on a real page instead.', 'puffergo');
    }

    private static function candidate_is_draft(): bool
    {
        $candidate = self::find_candidate();

        return $candidate && 'draft' === get_post_status($candidate);
    }

    private static function needs_activation(): bool
    {
        $candidate = self::find_candidate();

        if (! $candidate) {
            return self::front_page_unconfigured();
        }

if (self::candidate_is_draft()) {
            $modified = get_post_modified_time('U', true, $candidate);

            if ($modified && (time() - (int) $modified) < self::DRAFT_GRACE_SECONDS) {
                return false;
            }

return true;
        } $current_show = get_option('show_on_front', 'posts');
        $current_front = (int) get_option('page_on_front', 0);

        return ('page' !== $current_show || $current_front !== $candidate);
    }

    public static function get_dashboard_banner_data(): ?array
    {
        if (! current_user_can('manage_options') || ! self::needs_activation()) {
            return null;
        } $candidate = self::find_candidate();

        if (! $candidate) {
            return array('title' => __('Your homepage isn\'t set up yet', 'puffergo'), 'description' => self::get_unconfigured_description(), 'fixLabel' => __('Set up in Reading Settings', 'puffergo'), 'fixUrl' => admin_url('options-reading.php'), 'docsUrl' => self::DOCS_URL, );
        } $page_title = get_the_title($candidate);

        return array('title' => $page_title, 'description' => self::get_notice_description($page_title), 'fixLabel' => self::get_fix_label(), 'fixUrl' => self::get_activate_url(), 'docsUrl' => self::DOCS_URL, );
    }

    private static function get_activate_url(): string
    {
        return add_query_arg(array('action' => self::ACTIVATE_ACTION, '_wpnonce' => wp_create_nonce(self::ACTIVATE_ACTION), ), admin_url('admin-post.php'));
    }

    private static function get_notice_description(string $page_title): string
    {
        if (self::candidate_is_draft()) {
            return sprintf(__('The homepage PufferGo built for you ("%s") is still a draft — visitors opening your domain currently see the default blog feed instead, which can make your site look unfinished. One click below publishes it and sets it as your homepage.', 'puffergo'), $page_title);
        }

return sprintf(__('WordPress is currently not showing the homepage PufferGo built for you ("%s") — Settings → Reading is pointing somewhere else (often "Your latest posts"). A proper static homepage matters for SEO and first impressions: showing a raw blog feed instead can make your site look unfinished to visitors.', 'puffergo'), $page_title);
    }

    private static function get_fix_label(): string
    {
        return self::candidate_is_draft() ? __('Publish & set as homepage (Fix Now)', 'puffergo') : __('Set as homepage (Fix Now)', 'puffergo');
    }

    public static function maybe_render_notice(): void
    {
        if (! current_user_can('manage_options')) {
            return;
        } $screen = get_current_screen();

        if ($screen && 'toplevel_page_puffergo' === $screen->id) {
            return;
        }

if (get_user_meta(get_current_user_id(), self::DISMISSED_META_KEY, true)) {
            return;
        }

if (! self::needs_activation()) {
            return;
        } $candidate = self::find_candidate();

        if ($candidate) {
            $description = self::get_notice_description(get_the_title($candidate));
            $fix_label = self::get_fix_label();
            $fix_url = self::get_activate_url();
        } else {
            $description = self::get_unconfigured_description();
            $fix_label = __('Set up in Reading Settings', 'puffergo');
            $fix_url = admin_url('options-reading.php');
        } echo '<div class="notice notice-warning puffergo-admin-notice puffergo-homepage-notice" style="display:flex;align-items:flex-start;gap:12px;padding:12px 16px;">';
        echo '<div style="flex:1;">';
        echo '<p style="margin:0 0 4px;font-weight:600;">';
        esc_html_e('PufferGo: your homepage settings may need attention', 'puffergo');
        echo '</p>';
        echo '<p style="margin:0 0 8px;color:#555;">';
        echo esc_html($description);
        echo '</p>';
        echo '<a href="' . esc_url($fix_url) . '" class="button button-small">';
        echo esc_html($fix_label);
        echo '</a>';
        echo '<a href="' . esc_url(self::DOCS_URL) . '" target="_blank" rel="noopener noreferrer" style="margin-left:8px;font-size:13px;vertical-align:middle;">';
        esc_html_e('Learn why', 'puffergo');
        echo '</a>';
        echo '</div>';
        echo '<button type="button" class="puffergo-homepage-notice-dismiss" data-nonce="' . esc_attr(wp_create_nonce(self::DISMISS_ACTION)) . '" style="background:none;border:none;cursor:pointer;font-size:18px;line-height:1;color:#999;padding:0;flex-shrink:0;" aria-label="' . esc_attr__('Dismiss', 'puffergo') . '">&#x2715;</button>';
        echo '</div>';
        echo '<script>(function(){var b=document.currentScript.previousElementSibling.querySelector(".puffergo-homepage-notice-dismiss");if(!b)return;b.addEventListener("click",function(){var fd=new FormData();fd.append("action","' . esc_js(self::DISMISS_ACTION) . '");fd.append("nonce",b.dataset.nonce);fetch(ajaxurl,{method:"POST",body:fd,credentials:"same-origin"});b.closest(".puffergo-homepage-notice").remove();});})();</script>';
    }

    public static function handle_dismiss(): void
    {
        check_ajax_referer(self::DISMISS_ACTION, 'nonce');
        update_user_meta(get_current_user_id(), self::DISMISSED_META_KEY, 1);
        wp_send_json_success();
    }

    public static function handle_activate(): void
    {
        check_admin_referer(self::ACTIVATE_ACTION);

        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to do this.', 'puffergo'));
        } $candidate = self::find_candidate();

        if ($candidate && 'draft' === get_post_status($candidate)) {
            wp_publish_post($candidate);
        }

if ($candidate && 'publish' === get_post_status($candidate)) {
            update_option('show_on_front', 'page');
            update_option('page_on_front', $candidate);
        } wp_safe_redirect(wp_get_referer() ? wp_get_referer() : admin_url());
        exit;
    }
}
