<?php

namespace SoftminalB2B\Registration;

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

use SoftminalB2B\Models\Group;

/**
 * Registration notifications (FEATURES C2: "email notifications both
 * directions").
 *
 * Sent through wp_mail with WooCommerce's own header and footer templates, so
 * they inherit whatever styling the merchant has configured for Woo emails and
 * arrive looking like the rest of the shop's mail rather than plugin output.
 */
class Emails
{
    private static bool $registered = false;

    public static function init(): void
    {
        if (self::$registered) {
            return;
        }

        self::$registered = true;

        add_action('smb2b_registration_submitted', [self::class, 'onSubmitted'], 10, 2);
        add_action('smb2b_registration_approved', [self::class, 'onApproved'], 10, 2);
        add_action('smb2b_registration_rejected', [self::class, 'onRejected'], 10, 2);
    }

    /**
     * @param array<string, string> $business
     */
    public static function onSubmitted(int $userId, array $business): void
    {
        $user = get_userdata($userId);

        if (!$user) {
            return;
        }

        self::send(
            $user->user_email,
            __('We have your trade account application', 'softminal-b2b-wholesale-for-woocommerce'),
            sprintf(
                /* translators: %s: customer first name */
                __('Hi %s,', 'softminal-b2b-wholesale-for-woocommerce'),
                $user->first_name ?: $user->display_name
            ),
            [
                __('Thanks for applying for a trade account. Someone will review it shortly and we will email you as soon as it is approved.', 'softminal-b2b-wholesale-for-woocommerce'),
                __('You do not need to do anything else for now.', 'softminal-b2b-wholesale-for-woocommerce'),
            ]
        );

        self::notifyAdmin($user, $business);
    }

    public static function onApproved(int $userId, ?int $groupId): void
    {
        $user = get_userdata($userId);

        if (!$user) {
            return;
        }

        $group = $groupId ? Group::find($groupId) : null;

        $body = [
            __('Good news — your trade account is approved. Your prices are now live, so signing in will show them across the shop.', 'softminal-b2b-wholesale-for-woocommerce'),
        ];

        if ($group) {
            $body[] = sprintf(
                /* translators: %s: customer group name */
                __('You have been added to our %s pricing.', 'softminal-b2b-wholesale-for-woocommerce'),
                esc_html($group->name)
            );
        }

        // The applicant never chose a password, so the practical next step is a
        // set-password link rather than a login link they cannot use.
        $key = get_password_reset_key($user);

        if (!is_wp_error($key)) {
            $body[] = sprintf(
                '<a href="%s">%s</a>',
                esc_url(network_site_url("wp-login.php?action=rp&key={$key}&login=" . rawurlencode($user->user_login), 'login')),
                esc_html__('Set your password and sign in', 'softminal-b2b-wholesale-for-woocommerce')
            );
        }

        self::send(
            $user->user_email,
            __('Your trade account is approved', 'softminal-b2b-wholesale-for-woocommerce'),
            sprintf(
                /* translators: %s: customer first name */
                __('Hi %s,', 'softminal-b2b-wholesale-for-woocommerce'),
                $user->first_name ?: $user->display_name
            ),
            $body
        );
    }

    public static function onRejected(int $userId, string $reason): void
    {
        $user = get_userdata($userId);

        if (!$user) {
            return;
        }

        $body = [__('Thanks for your interest. We are not able to open a trade account for you at this time.', 'softminal-b2b-wholesale-for-woocommerce')];

        if (trim($reason) !== '') {
            $body[] = esc_html($reason);
        }

        $body[] = __('You can still shop with us using a normal customer account.', 'softminal-b2b-wholesale-for-woocommerce');

        self::send(
            $user->user_email,
            __('About your trade account application', 'softminal-b2b-wholesale-for-woocommerce'),
            sprintf(
                /* translators: %s: customer first name */
                __('Hi %s,', 'softminal-b2b-wholesale-for-woocommerce'),
                $user->first_name ?: $user->display_name
            ),
            $body
        );
    }

    /**
     * @param array<string, string> $business
     */
    private static function notifyAdmin(\WP_User $user, array $business): void
    {
        $lines = [
            sprintf(
                /* translators: 1: applicant name, 2: applicant email */
                __('%1$s (%2$s) has applied for a trade account.', 'softminal-b2b-wholesale-for-woocommerce'),
                $user->display_name,
                $user->user_email
            ),
        ];

        foreach (Applicant::fields() as $key => $field) {
            if (!empty($business[$key])) {
                $lines[] = sprintf('<strong>%s:</strong> %s', esc_html($field['label']), esc_html($business[$key]));
            }
        }

        $lines[] = sprintf(
            '<a href="%s">%s</a>',
            esc_url(admin_url('admin.php?page=softminal-b2b-wholesale-for-woocommerce#/registrations')),
            esc_html__('Review pending applications', 'softminal-b2b-wholesale-for-woocommerce')
        );

        self::send(
            (string) get_option('admin_email'),
            __('New trade account application', 'softminal-b2b-wholesale-for-woocommerce'),
            __('A new application is waiting', 'softminal-b2b-wholesale-for-woocommerce'),
            $lines
        );
    }

    /**
     * @param array<int, string> $paragraphs
     */
    private static function send(string $to, string $subject, string $heading, array $paragraphs): void
    {
        if ($to === '' || !is_email($to)) {
            return;
        }

        $body = '';

        foreach ($paragraphs as $paragraph) {
            $body .= '<p>' . $paragraph . '</p>';
        }

        $content = $body;

        // Wrapping in Woo's own template keeps these consistent with order
        // emails and inherits the merchant's colours and logo.
        //
        // The two calls live on different classes: wrap_message() is on
        // WC_Emails (what WC()->mailer() returns), while style_inline() is on
        // WC_Email, an individual email. Calling the latter on the former is a
        // fatal, so each is invoked on the object that actually has it.
        if (function_exists('WC') && WC()->mailer()) {
            $content = WC()->mailer()->wrap_message($heading, $body);

            if (class_exists('WC_Email')) {
                $content = (new \WC_Email())->style_inline($content);
            }
        }

        $headers = ['Content-Type: text/html; charset=UTF-8'];

        wp_mail($to, $subject, $content, $headers);
    }
}
