<?php
/**
 * Monthly optimization usage tracking.
 *
 * @package Shrinkwell_Image_Optimizer
 */

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

class Shrinkwell_Usage_Tracker
{
    private const MONTHLY_LIMIT_BYTES = 60 * 1024 * 1024;

    public function __construct()
    {
    }

    public function is_pro(): bool
    {
        return function_exists('shrinkwell_can_use_unlimited_optimization') && shrinkwell_can_use_unlimited_optimization();
    }

    public function get_current_usage_bytes(): int
    {
        $usage = get_option($this->get_usage_option_key(), 0);

        return max(0, (int) $usage);
    }

    public function get_monthly_limit_bytes(): int
    {
        return self::MONTHLY_LIMIT_BYTES;
    }

    public function has_reached_limit(): bool
    {
        if ($this->is_pro()) {
            return false;
        }

        return $this->get_current_usage_bytes() >= $this->get_monthly_limit_bytes();
    }

    public function can_optimize_bytes($bytes): bool
    {
        if ($this->is_pro()) {
            return true;
        }

        $bytes = max(0, (int) $bytes);

        return ($this->get_current_usage_bytes() + $bytes) <= $this->get_monthly_limit_bytes();
    }

    public function add_usage_bytes($bytes): int
    {
        if ($this->is_pro()) {
            return $this->get_current_usage_bytes();
        }

        $bytes = max(0, (int) $bytes);

        if (0 === $bytes) {
            return $this->get_current_usage_bytes();
        }

        $usage = $this->get_current_usage_bytes() + $bytes;
        update_option($this->get_usage_option_key(), $usage, false);

        return $usage;
    }

    public function get_usage_display(): string
    {
        if ($this->is_pro()) {
            return __('Unlimited WebP and AVIF optimization enabled', 'shrinkwell-image-optimizer');
        }

        return sprintf(
            /* translators: 1: Current monthly processed media amount. 2: Monthly optimization limit. */
            __('%1$s MB of %2$s MB processed this month', 'shrinkwell-image-optimizer'),
            number_format_i18n($this->get_current_usage_bytes() / (1024 * 1024), 1),
            number_format_i18n($this->get_monthly_limit_bytes() / (1024 * 1024), 0)
        );
    }

    public function get_usage_option_key(): string
    {
        return 'shrinkwell_usage_' . wp_date('Y_m');
    }
}
