<?php
if (!defined('ABSPATH')) exit;

class FORMFORGE_Notifications {
    private static $instance = null;
    public static function instance() { if (!self::$instance) self::$instance = new self(); return self::$instance; }
    private function __construct() {}

    public function send($form, $data, $submission_id) {
        $settings = $form->settings;
        $global   = get_option('formforge_settings', []);

        // Admin notification — fall back to global default email when per-form email is not set
        $notify_email = !empty($settings['notify_email'])
            ? $settings['notify_email']
            : ($global['default_notification_email'] ?? get_option('admin_email'));

        if (!empty($settings['notify_admin']) && !empty($notify_email)) {
            $this->send_admin_email($form, $data, $notify_email, $submission_id);
        }

        // Auto-reply
        if (!empty($settings['auto_reply']) && !empty($settings['auto_reply_field'])) {
            $email_field = $settings['auto_reply_field'];
            foreach ($data as $id => $field) {
                if ($id === $email_field && is_email($field['value'])) {
                    $this->send_auto_reply($field['value'], $settings, $form->title);
                    break;
                }
            }
        }
    }

    private function send_admin_email($form, $data, $to, $submission_id) {
        $global = get_option('formforge_settings', []);
        $site   = !empty($global['email_sender_name']) ? $global['email_sender_name'] : get_bloginfo('name');
        $safe_site  = preg_replace('/[\r\n]+/', ' ', (string) $site);
        $safe_title = preg_replace('/[\r\n]+/', ' ', (string) $form->title);
        /* translators: 1: site name, 2: form title, 3: submission ID */
        $subject = sprintf(__('[%1$s] New submission: %2$s (#%3$d)', 'formforge'), $safe_site, $safe_title, $submission_id);

        $blocks = [
            ['label' => __('Form', 'formforge'), 'value' => $form->title],
            ['label' => __('Submission', 'formforge'), 'value' => '#' . $submission_id],
        ];

        foreach (FORMFORGE_Value_Formatter::submission_display_fields($data) as $field) {
            $blocks[] = [
                'label' => $field['label'] ?? '',
                'value' => FORMFORGE_Value_Formatter::text($field['value'] ?? '', ''),
            ];
        }

        Forge_Email_Template::send_wp($to, $subject, [
            'product'     => 'formforge',
            'title'       => __('New form submission', 'formforge'),
            /* translators: %s: form title */
            'preheader'   => sprintf(__('New submission for %s', 'formforge'), $safe_title),
            'intro'       => __('A visitor submitted your form. Review the details below.', 'formforge'),
            'blocks'      => $blocks,
            'cta'         => [
                'label' => __('View submission', 'formforge'),
                'url'   => admin_url('admin.php?page=formforge-submissions&form_id=' . $form->id),
            ],
            /* translators: %s: plugin name */
            'footer_note' => sprintf(__('Sent by %s on your WordPress site.', 'formforge'), 'Form Forge'),
        ]);
    }

    private function send_auto_reply($to, $settings, $form_title) {
        $safe_title = preg_replace('/[\r\n]+/', ' ', (string) $form_title);
        /* translators: %s: form title */
        $subject = $settings['auto_reply_subject'] ?: sprintf(__('Thank you for your submission: %s', 'formforge'), $safe_title);
        $subject = preg_replace('/[\r\n]+/', ' ', (string) $subject);
        $message = $settings['auto_reply_message'] ?: __('We received your submission and will get back to you soon.', 'formforge');

        Forge_Email_Template::send_wp($to, $subject, [
            'product'     => 'formforge',
            'title'       => __('Thank you for your submission', 'formforge'),
            /* translators: %s: form title */
            'preheader'   => sprintf(__('We received your submission for %s.', 'formforge'), $safe_title),
            'intro'       => $message,
            /* translators: %s: plugin name */
            'footer_note' => sprintf(__('Sent by %s on your WordPress site.', 'formforge'), 'Form Forge'),
        ]);
    }
}
