<?php

namespace GriffinForms\Includes\MailTemplates;

class StorageThresholdExceeded extends \GriffinForms\Includes\MailTemplates\Format
{
    protected $subject = 'Storage Threshold Exceeded on Your Site';
    protected $content = 'The storage threshold for your site has been exceeded.';

    // Set the subject of the admin alert
    public function setSubject($subject)
    {
        $this->subject = $subject;
    }

    // Set the content of the admin alert
    public function setContent($content)
    {
        $this->content = $content;
    }

    protected function processSubject()
    {
        // Translators: Subject line for storage threshold exceeded alert.
        $subject = __('Storage Threshold Exceeded on Your Site', 'griffinforms-form-builder');
        $this->subject = $subject;
    }

    protected function processContent()
    {
        $site_name = isset($this->data['site_name']) ? wp_specialchars_decode($this->data['site_name'], ENT_QUOTES) : wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);

        // Use values from $this->data instead of direct calls
        $current_bytes = isset($this->data['current_bytes']) ? (int) $this->data['current_bytes'] : 0;
        $threshold_mb  = isset($this->data['threshold_mb']) ? (float) $this->data['threshold_mb'] : 0.0;
        if (!is_finite($threshold_mb) || $threshold_mb < 0) {
            $threshold_mb = 0.0;
        }

        // Formatters
        if (class_exists('GriffinForms\\Admin\\Units') && method_exists(\GriffinForms\Admin\Units::getInstance(), 'formatBytes')) {
            $current_h = \GriffinForms\Admin\Units::getInstance()->formatBytes($current_bytes);
        } else {
            $current_h = $this->formatBytesFallback($current_bytes);
        }

        $threshold_h = sprintf(
            /* translators: %s: threshold size in megabytes */
            __('%s MB', 'griffinforms-form-builder'),
            number_format_i18n($threshold_mb, 2)
        );

        $time = wp_date(get_option('date_format') . ' ' . get_option('time_format'));

        // Optional CTA buttons (with safe defaults)
        $settings_url    = admin_url('admin.php?page=griffinforms-settings-filestorage');
        $submissions_url = admin_url('admin.php?page=griffinforms-submissions');

        $cta_html = '';
        if ($settings_url || $submissions_url) {
            $cta_html .= '<p style="margin:16px 0 6px;">';
            if ($settings_url) {
                $cta_html .= '<a href="' . esc_url($settings_url) . '" style="display:inline-block;padding:8px 12px;border-radius:4px;background:#2271b1;color:#fff;text-decoration:none;margin-right:8px;">' . esc_html__( 'Open File Storage Settings', 'griffinforms-form-builder' ) . '</a>';
            }
            if ($submissions_url) {
                $cta_html .= '<a href="' . esc_url($submissions_url) . '" style="display:inline-block;padding:8px 12px;border-radius:4px;background:#646970;color:#fff;text-decoration:none;">' . esc_html__( 'View Submissions', 'griffinforms-form-builder' ) . '</a>';
            }
            $cta_html .= '</p>';
        }

        // Build content (HTML allowed in templates)
        $content  = '<div class="gf-mail-card" style="max-width:640px;border:1px solid #dcdcde;border-radius:8px;padding:16px;font:14px/1.5 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;color:#1d2327;">';
        $content .= '<h2 style="margin:0 0 12px;font-size:18px;">' . esc_html($site_name) . '</h2>';
        $content .= '<p>' . esc_html__('The storage threshold for your website has been exceeded.', 'griffinforms-form-builder') . '</p>';
        $content .= '<table role="presentation" cellspacing="0" cellpadding="0" style="width:100%;margin:8px 0 12px;border-collapse:collapse;">';
        $content .=   '<tr><td style="padding:8px;border:1px solid #dcdcde;background:#f6f7f7;">' . esc_html__('Current usage', 'griffinforms-form-builder') . '</td>'
                .  '<td style="padding:8px;border:1px solid #dcdcde;">' . esc_html($current_h) . '</td></tr>';
        $content .=   '<tr><td style="padding:8px;border:1px solid #dcdcde;background:#f6f7f7;">' . esc_html__('Configured threshold', 'griffinforms-form-builder') . '</td>'
                .  '<td style="padding:8px;border:1px solid #dcdcde;">' . esc_html($threshold_h) . '</td></tr>';
        $content .=   '<tr><td style="padding:8px;border:1px solid #dcdcde;background:#f6f7f7;">' . esc_html__('Detected on', 'griffinforms-form-builder') . '</td>'
                .  '<td style="padding:8px;border:1px solid #dcdcde;">' . esc_html($time) . '</td></tr>';
        $content .= '</table>';
        $content .= '<p>' . esc_html__('Please review your storage usage and take appropriate action to free up space or increase your storage limits.', 'griffinforms-form-builder') . '</p>';
        $content .= $cta_html; // already escaped URLs & labels
        $content .= '<p style="margin:12px 0 0;color:#50575e; font-size: 12px;">' . esc_html__('Note: This storage calculation only includes files attached to completed submissions. Temporary files from incomplete submissions are purged automatically.', 'griffinforms-form-builder') . '</p>';
        $content .= '<p style="margin:8px 0 0;color:#50575e; font-size: 12px;">' . esc_html__('You will receive this alert only once after the threshold is crossed. It will trigger again only after usage drops below the threshold and later exceeds it.', 'griffinforms-form-builder') . '</p>';
        $content .= '</div>';

        $this->content = $content;
    }

    /**
     * Fallback human-readable bytes formatter (KB/MB/GB) with 2 decimals.
     *
     * @param int $bytes
     * @return string
     */
    protected function formatBytesFallback($bytes)
    {
        $bytes = (int) $bytes;
        if ($bytes < 1024) {
            return sprintf(_n('%s byte', '%s bytes', $bytes, 'griffinforms-form-builder'), number_format_i18n($bytes));
        }
        $kb = $bytes / 1024;
        if ($kb < 1024) {
            return sprintf(__('%.2f KB', 'griffinforms-form-builder'), $kb);
        }
        $mb = $kb / 1024;
        if ($mb < 1024) {
            return sprintf(__('%.2f MB', 'griffinforms-form-builder'), $mb);
        }
        $gb = $mb / 1024;
        return sprintf(__('%.2f GB', 'griffinforms-form-builder'), $gb);
    }
}