<?php
/**
 * Usage Tracker for BoostBot.
 *
 * @package BoostBot
 */

// Prevent direct access to the file.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * BoostBot_Usage_Tracker class.
 *
 * Tracks monthly usage of messages and conversations.
 *
 * @since 1.0.0
 */
class BoostBot_Usage_Tracker
{
    /**
     * Option key for usage data.
     *
     * @since 1.0.0
     * @access private static
     * @var string $option_key
     */
    private static $option_key = 'boostbot_usage_data';

    /**
     * Initialize the usage tracker.
     *
     * @since 1.0.0
     */
    public static function init()
    {
        // Schedule monthly reset
        if (!wp_next_scheduled('boostbot_monthly_reset')) {
            // Schedule for first day of next month at midnight
            $next_month = strtotime('first day of next month midnight');
            wp_schedule_event($next_month, 'monthly', 'boostbot_monthly_reset');
        }

        // Hook for monthly reset
        add_action('boostbot_monthly_reset', [__CLASS__, 'reset_monthly']);

        // Register custom cron schedule for monthly
        add_filter('cron_schedules', [__CLASS__, 'add_monthly_schedule']);
    }

    /**
     * Add monthly cron schedule.
     *
     * @since 1.0.0
     * @param array $schedules Existing schedules.
     * @return array Modified schedules.
     */
    public static function add_monthly_schedule($schedules)
    {
        if (!isset($schedules['monthly'])) {
            $schedules['monthly'] = [
                'interval' => 30 * DAY_IN_SECONDS,
                'display'  => __('Once Monthly', 'boostbot'),
            ];
        }
        return $schedules;
    }

    /**
     * Get current usage data.
     *
     * @since 1.0.0
     * @return array Usage data.
     */
    public static function get_usage()
    {
        $default = [
            'messages'      => 0,
            'conversations' => 0,
            'widgets'       => 0,
            'month'         => gmdate('Y-m'),
            'last_updated'  => null,
        ];

        $data = get_option(self::$option_key, $default);

        // Check if new month - auto reset
        if ($data['month'] !== gmdate('Y-m')) {
            $data = $default;
            update_option(self::$option_key, $data);
        }

        return $data;
    }

    /**
     * Increment a usage counter.
     *
     * @since 1.0.0
     * @param string $type   Type of usage (messages, conversations, widgets).
     * @param int    $amount Amount to increment.
     * @return array Updated usage data.
     */
    public static function increment($type, $amount = 1)
    {
        $data = self::get_usage();

        if (!isset($data[$type])) {
            $data[$type] = 0;
        }

        $data[$type] += absint($amount);
        $data['last_updated'] = current_time('mysql');

        update_option(self::$option_key, $data);

        // Check thresholds
        self::check_thresholds($data);

        // Log usage increment
        BoostBot_Logger::debug('Usage incremented', [
            'type'   => $type,
            'amount' => $amount,
            'total'  => $data[$type],
        ]);

        return $data;
    }

    /**
     * Check if user can send a message (within limit).
     *
     * @since 1.0.0
     * @return bool True if allowed, false if limit reached.
     */
    public static function can_send_message()
    {
        return true;
    }

    /**
     * Get remaining messages for this month.
     *
     * @since 1.0.0
     * @return int Remaining messages.
     */
    public static function get_remaining()
    {
        // Unlimited.
        return PHP_INT_MAX;
    }

    /**
     * Get usage percentage.
     *
     * @since 1.0.0
     * @return float Percentage of limit used.
     */
    public static function get_percentage()
    {
        // Unlimited.
        return 0;
    }

    /**
     * Get the monthly message limit.
     *
     * @since 1.0.0
     * @return int Monthly limit.
     */
    public static function get_monthly_limit()
    {
        // Monthly usage limits are deprecated (credits is the only limiter).
        return -1;
    }

    /**
     * Check usage thresholds and send alerts.
     *
     * @since 1.0.0
     * @param array $data Usage data.
     */
    private static function check_thresholds($data)
    {
        // Monthly usage alerts are deprecated.
        return;
    }

    /**
     * Send usage alert email.
     *
     * @since 1.0.0
     * @param int $percentage Percentage reached.
     * @param int $current    Current usage.
     * @param int $limit      Usage limit.
     */
    private static function send_usage_alert($percentage, $current, $limit)
    {
        $admin_email = get_option('admin_email');
        $site_name = get_bloginfo('name');

        $subject = sprintf(
            /* translators: %1$s: site name, %2$d: percentage of usage */
            __('[%1$s] BoostBot: הגעת ל-%2$d%% מהמכסה החודשית', 'boostbot'),
            $site_name,
            $percentage
        );

        $message = sprintf(
            /* translators: 1: site name, 2: percentage, 3: current usage, 4: limit */
            __(
                'שלום,

האתר %1$s הגיע ל-%2$d%% מהמכסה החודשית של BoostBot.

שימוש נוכחי: %3$d / %4$d הודעות

%5$s

צוות BoostBot',
                'boostbot'
            ),
            $site_name,
            $percentage,
            $current,
            $limit,
            $percentage >= 100
                ? __('המכסה נגמרה. שדרג ל-Pro לשימוש בלתי מוגבל!', 'boostbot')
                : __('שקול לשדרג ל-Pro לשימוש בלתי מוגבל.', 'boostbot')
        );

        wp_mail($admin_email, $subject, $message);

        BoostBot_Logger::info('Usage alert sent', [
            'percentage' => $percentage,
            'email'      => $admin_email,
        ]);
    }

    /**
     * Reset monthly usage.
     *
     * @since 1.0.0
     */
    public static function reset_monthly()
    {
        // Store previous month data for history
        $previous = self::get_usage();
        self::save_monthly_history($previous);

        // Reset current month
        delete_option(self::$option_key);
        delete_transient('boostbot_alert_80');
        delete_transient('boostbot_alert_100');

        BoostBot_Logger::info('Monthly usage reset', [
            'previous_messages' => $previous['messages'],
        ]);
    }

    /**
     * Save monthly history for analytics.
     *
     * @since 1.0.0
     * @param array $data Usage data to save.
     */
    private static function save_monthly_history($data)
    {
        $history = get_option('boostbot_usage_history', []);

        // Keep last 12 months
        $history[$data['month']] = [
            'messages'      => $data['messages'],
            'conversations' => $data['conversations'],
        ];

        // Limit to 12 months
        if (count($history) > 12) {
            array_shift($history);
        }

        update_option('boostbot_usage_history', $history);
    }

    /**
     * Get usage history.
     *
     * @since 1.0.0
     * @param int $months Number of months to retrieve.
     * @return array Usage history.
     */
    public static function get_history($months = 12)
    {
        $history = get_option('boostbot_usage_history', []);
        return array_slice($history, -$months, $months, true);
    }

    /**
     * Get detailed usage stats.
     *
     * @since 1.0.0
     * @return array Detailed stats.
     */
    public static function get_detailed_stats()
    {
        $usage = self::get_usage();
        $limit = self::get_monthly_limit();
        $history = self::get_history(6);

        // Calculate daily average
        $day_of_month = (int) gmdate('j');
        $daily_avg = $day_of_month > 0 ? round($usage['messages'] / $day_of_month, 1) : 0;

        // Projected usage for full month
        $days_in_month = (int) gmdate('t');
        $projected = round($daily_avg * $days_in_month);

        return [
            'current'            => $usage,
            'limit'              => $limit,
            'remaining'          => self::get_remaining(),
            'percentage'         => self::get_percentage(),
            'daily_average'      => $daily_avg,
            'projected_monthly'  => $projected,
            'is_over_projected'  => $limit > 0 && $projected > $limit,
            'history'            => $history,
        ];
    }
}



