<?php 

class ContactForm7{
    public static function register(): void {

        if (!defined('WPCF7_VERSION')) {
            return;
        }

        add_filter('wpcf7_collect_mail_tags', [self::class, 'collectMailTags']);
        add_filter('wpcf7_special_mail_tags', [self::class, 'specialMailTags'], 10, 2);
        add_action('wpcf7_mail_failed', [self::class, 'mailFailed'], 10, 1);
    }

    public static function collectMailTags(array $tags): array {
        if (!in_array('_zoddak_emails', $tags, true)) {
            $tags[] = '_zoddak_emails';
        }
        return $tags;
    }

    public static function specialMailTags($output, string $name) {
        if ($name !== '_zoddak_emails') {
            return $output;
        }

        $selectedEmails = get_option('zoddak_newdevs_contact_users', []);

        return !empty($selectedEmails)
            ? implode(', ', $selectedEmails)
            : get_option('admin_email');
    }

    public static function mailFailed($mail): void {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('CF7 Mail Failed: ' . print_r($mail, true));
        }
    }
}