<?php
// includes/limits.php
defined('ABSPATH') || exit;

// --- Blog Maker monthly post limit (based on blog-maker.log) ---
// Paid tier can be defined in wp-config.php via:
// define('BLOG_MAKER_PAID_TIER', true);

if (!function_exists('blog_maker_is_paid_tier')) {
    function blog_maker_is_paid_tier($user = null) {
        if ($user === null && function_exists('wp_get_current_user')) {
            $user = wp_get_current_user();
        }

        // Primary source: wp-config.php constant
        if (defined('BLOG_MAKER_PAID_TIER')) {
            $is_paid = (bool) BLOG_MAKER_PAID_TIER;
        } else {
            $is_paid = false;
        }

        // Optional override via filter (advanced usage)
        if (function_exists('apply_filters')) {
            $is_paid = (bool) apply_filters('blog_maker_is_paid_tier', $is_paid, $user);
        }

        return $is_paid;
    }
}

if (!function_exists('blog_maker_get_monthly_limit_status')) {
    function blog_maker_get_monthly_limit_status() {
        $limit = 2; // free-tier monthly limit

        $is_paid = blog_maker_is_paid_tier();

        $log_file = dirname(__FILE__) . '/blog-maker.log';
        $count_this_month = 0;

        $tz = function_exists('wp_timezone') ? wp_timezone() : new DateTimeZone(date_default_timezone_get());
        $now = new DateTime('now', $tz);

        if (is_readable($log_file)) {
            $lines = @file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            if (is_array($lines)) {
                $ym = $now->format('Y-m');
                foreach ($lines as $line) {
                    if (preg_match('/^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]/', $line, $m) ||
                        preg_match('/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\b/', $line, $m)) {

                        $dt = DateTime::createFromFormat('Y-m-d H:i:s', $m[1], $tz);
                        if ($dt && $dt->format('Y-m') === $ym) {
                            $count_this_month++;
                        }
                    }
                }
            }
        }

        $reset_at = (clone $now)->modify('first day of next month 00:00:00');

        return array(
            'limit' => $limit,
            'count_this_month' => $count_this_month,
            'is_paid' => $is_paid,
            'is_limited' => (!$is_paid && $count_this_month >= $limit),
            'reset_at' => $reset_at,
        );
    }
}

if (!function_exists('blog_maker_get_published_blog_count_this_month')) {
    function blog_maker_get_published_blog_count_this_month() {
        $tz = function_exists('wp_timezone') ? wp_timezone() : new DateTimeZone(date_default_timezone_get());
        $now = new DateTimeImmutable('now', $tz);
        $month_start = $now->modify('first day of this month')->setTime(0, 0, 0);

        $query = new WP_Query(array(
            'post_type'              => 'post',
            'post_status'            => 'publish',
            'fields'                 => 'ids',
            'posts_per_page'         => 1,
            'no_found_rows'          => false,
            'ignore_sticky_posts'    => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
            'date_query'             => array(
                array(
                    'column'    => 'post_date',
                    'after'     => $month_start->format('Y-m-d H:i:s'),
                    'before'    => $now->format('Y-m-d H:i:s'),
                    'inclusive' => true,
                ),
            ),
        ));

        return isset($query->found_posts) ? (int) $query->found_posts : 0;
    }
}
