<?php
/**
 * Plugin Name: GoVIP
 * Description: Early-access countdown overlay for posts + tasteful archive notices.
 * Version:     1.2.2
 */

if (!defined('ABSPATH')) exit;

/* -------------------------------------------------
   Utilities
------------------------------------------------- */

function govip_wp_timezone() {
    if (function_exists('wp_timezone')) return wp_timezone();
    $tz_string = get_option('timezone_string');
    if ($tz_string) return new DateTimeZone($tz_string);
    $offset = (float) get_option('gmt_offset');
    $hours  = (int) $offset;
    $mins   = abs(($offset - $hours) * 60);
    $sign   = $offset < 0 ? '-' : '+';
    return new DateTimeZone(sprintf('%s%02d:%02d', $sign, abs($hours), $mins));
}

function govip_get_release_string($post_id) {
    $val = get_post_meta($post_id, '_govip_release_date', true);
    return is_string($val) ? $val : '';
}

function govip_get_release_timestamp($post_id) {
    $raw = govip_get_release_string($post_id);
    if (!$raw) return 0;
    try {
        $dt = new DateTime($raw, govip_wp_timezone());
        return $dt->getTimestamp();
    } catch (Exception $e) {
        return 0;
    }
}

function govip_is_gated($post_id = null) {
    $post_id = $post_id ?: get_the_ID();
    if (!$post_id || get_post_type($post_id) !== 'post') return false;
    return govip_get_release_timestamp($post_id) > time();
}

function govip_human_diff_short($future_ts) {
    $sec = max(0, $future_ts - time());
    $d = intdiv($sec, 86400); $sec %= 86400;
    $h = intdiv($sec, 3600);  $sec %= 3600;
    $m = intdiv($sec, 60);
    if ($d > 0) return sprintf('%dd %dh', $d, $h);
    if ($h > 0) return sprintf('%dh %dm', $h, $m);
    return sprintf('%dm', $m);
}

function govip_join_url() {
    return function_exists('wp_registration_url') ? wp_registration_url() : wp_login_url();
}

/* Shorthand HTML for the archive meta line */
function govip_archive_meta_html($post_id) {
    $ts   = govip_get_release_timestamp($post_id);
    $when = govip_human_diff_short($ts);
    $join = esc_url(govip_join_url());

    return sprintf(
        '<div class="govip-meta">%s <strong>%s</strong> <span class="sep">·</span> <a href="%s">%s</a></div>',
        esc_html__('Opens in', 'govip'),
        esc_html($when),
        $join,
        esc_html__('Join to read early', 'govip')
    );
}

/* -------------------------------------------------
   Admin: meta box
------------------------------------------------- */

add_action('add_meta_boxes', function() {
    add_meta_box('govip_release_box', __('GoVIP Release Time', 'govip'),
        function($post) {
            wp_nonce_field('govip_release_save', 'govip_release_nonce');
            $val = esc_attr(govip_get_release_string($post->ID));
            echo '<p>' . esc_html__('Pick a future date & time for early access lock (site timezone).', 'govip') . '</p>';
            echo '<input type="datetime-local" id="govip_release_date" name="govip_release_date" style="width:100%;" value="'.$val.'" />';
        },
        'post', 'side', 'default'
    );
});

add_action('save_post_post', function($post_id){
    if (!isset($_POST['govip_release_nonce']) || !wp_verify_nonce($_POST['govip_release_nonce'], 'govip_release_save')) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['govip_release_date']) && $_POST['govip_release_date'] !== '') {
        update_post_meta($post_id, '_govip_release_date', sanitize_text_field($_POST['govip_release_date']));
    } else {
        delete_post_meta($post_id, '_govip_release_date');
    }
});

/* -------------------------------------------------
   Assets
------------------------------------------------- */

add_action('wp_enqueue_scripts', function() {
    wp_enqueue_style('govip-css', plugin_dir_url(__FILE__) . 'GoVIP-assets/GoVIP.css', [], '1.2.2');

    if (is_singular('post')) {
        wp_enqueue_script('govip-js', plugin_dir_url(__FILE__) . 'GoVIP-assets/GoVIP.js', [], '1.0', true);
    }

    // tiny archive styles in case your CSS file doesn’t include them
    $inline = '
    .govip-meta{margin-top:.4rem;font-size:.9em;opacity:.9}
    .govip-meta .sep{opacity:.6;margin:0 .35em}
    .govip-meta a{font-weight:700;text-decoration:underline}
    .govip-thumb-wrap{position:relative}
    .govip-badge{position:absolute;top:10px;left:10px;display:inline-flex;gap:6px;align-items:center;padding:4px 8px;border-radius:999px;font-size:12px;font-weight:700;background:rgba(0,0,0,.75);color:#e3d5ca;backdrop-filter:blur(2px)}
    .govip-badge svg{width:12px;height:12px}';
    wp_add_inline_style('govip-css', $inline);
});

/* -------------------------------------------------
   SINGLE POSTS: overlay via footer (archives remain clean)
------------------------------------------------- */

add_action('wp_footer', function() {
    if (!is_singular('post') || is_user_logged_in()) return;
    $post_id = get_queried_object_id();
    if (!$post_id || !govip_is_gated($post_id)) return;

    $release_str = govip_get_release_string($post_id);
    $join_url    = esc_url(govip_join_url());
    $assets_url  = plugin_dir_url(__FILE__) . 'GoVIP-assets/';

    $iso = '';
    try {
        $dt = new DateTime($release_str, govip_wp_timezone());
        $iso = $dt->format('Y-m-d\TH:i:s');
    } catch (Exception $e) {}

    ?>
    <div class="go-vip-wrapper" role="dialog" aria-modal="true" aria-label="<?php esc_attr_e('Early access overlay', 'govip'); ?>">
        <header>
            <img class="alert" src="<?php echo esc_url($assets_url . 'alert-sign.png'); ?>" alt="">
        </header>

        <h1><?php esc_html_e('Early access is for members only', 'govip'); ?></h1>

        <!-- IMPORTANT: match existing JS -->
        <div id="countdown-wrapper" data-release-date="<?php echo esc_attr($iso); ?>">
            <div id="countdown-container" class="timer-container">
                <div class="child-container" id="days">
                    <div class="countdown-number"><h2>00</h2></div>
                    <div class="seconds"><h3><?php esc_html_e('Days', 'govip'); ?></h3></div>
                </div>
                <div class="child-container" id="hours">
                    <div class="countdown-number"><h2>00</h2></div>
                    <div class="seconds"><h3><?php esc_html_e('Hours', 'govip'); ?></h3></div>
                </div>
                <div class="child-container" id="minutes">
                    <div class="countdown-number"><h2>00</h2></div>
                    <div class="seconds"><h3><?php esc_html_e('Minutes', 'govip'); ?></h3></div>
                </div>
                <div class="child-container" id="seconds">
                    <div class="countdown-number"><h2>00</h2></div>
                    <div class="seconds"><h3><?php esc_html_e('Seconds', 'govip'); ?></h3></div>
                </div>
            </div>
        </div>

        <h3 class="early-access-h3"><?php esc_html_e('Countdown until early access ends', 'govip'); ?></h3>
        <h3 id="countdown-finished" class="finished-h3" aria-live="polite" aria-atomic="true" style="display:none;">
            <?php esc_html_e('Early access has finished. Please refresh the page.', 'govip'); ?>
        </h3>

        <div class="button-container">
            <a class="member-button" href="<?php echo $join_url; ?>">
                <?php esc_html_e('Become a member today', 'govip'); ?>
            </a>
        </div>

        <footer>
            <img class="footer-logo" src="<?php echo esc_url($assets_url . 'GoVIP-logo.webp'); ?>" alt="">
            <span><?php esc_html_e('Page created with plugin', 'govip'); ?></span>
        </footer>
    </div>
    <?php
});

/* -------------------------------------------------
   ARCHIVES: badge + meta line (supports excerpt OR content)
------------------------------------------------- */

/* Add a class to gated posts on archives (handy for theme targeting) */
add_filter('post_class', function($classes, $class, $post_id) {
    if (is_admin() || is_singular()) return $classes;
    if (!is_user_logged_in() && govip_is_gated($post_id)) $classes[] = 'govip-is-gated';
    return $classes;
}, 10, 3);

/* Lock badge on the thumbnail */
add_filter('post_thumbnail_html', function($html, $post_id, $thumb_id, $size, $attr) {
    if (is_admin() || is_singular() || is_user_logged_in()) return $html;
    if (!govip_is_gated($post_id)) return $html;

    $badge = '<span class="govip-badge" aria-label="' . esc_attr__('Early access', 'govip') . '">' .
             '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12 2a5 5 0 00-5 5v3H6a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2v-8a2 2 0 00-2-2h-1V7a5 5 0 00-5-5zm-3 8V7a3 3 0 016 0v3H9z"/></svg>' .
             esc_html__('Early Access', 'govip') .
             '</span>';

    // Ensure a positioned wrapper
    if (strpos($html, 'post-thumbnail') === false) {
        return '<div class="post-thumbnail govip-thumb-wrap">' . $badge . $html . '</div>';
    }
    // Inject right after the opening tag of the thumbnail container
    $html = preg_replace('/(<[^>]*class="[^"]*post-thumbnail[^"]*"[^>]*>)/', '$1' . $badge, $html, 1);
    return $html;
}, 10, 5);

/* Append meta line when the theme uses the_excerpt() */
add_filter('get_the_excerpt', function($excerpt, $post) {
    if (is_admin() || is_singular() || is_user_logged_in()) return $excerpt;
    if (!$post instanceof WP_Post) return $excerpt;
    if (!govip_is_gated($post->ID)) return $excerpt;

    return trim(wp_strip_all_tags($excerpt)) . "\n\n" . govip_archive_meta_html($post->ID);
}, 10, 2);

/* Append meta line when the theme uses the_content() on archives */
add_filter('the_content', function($content) {
    if (is_admin() || is_singular() || is_user_logged_in()) return $content;

    // Only touch main archive queries inside the loop (avoid widgets/feeds)
    if (!is_archive() && !is_home() && !is_search()) return $content;
    if (!in_the_loop() || !is_main_query()) return $content;

    $post_id = get_the_ID();
    if (!$post_id || !govip_is_gated($post_id)) return $content;

    // Don’t strip or replace; just append a small meta line.
    return $content . "\n\n" . govip_archive_meta_html($post_id);
}, 12);

/* -------------------------------------------------
   We intentionally DO NOT gate the_content on archives.
   Single-post overlay handles access for logged-out users.
------------------------------------------------- */
