<?php

namespace SoftminalB2B\Messaging;

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

use SoftminalB2B\Models\Conversation;
use SoftminalB2B\Models\Message;

/**
 * New-message notifications, both directions ([[project-messaging-feature]]).
 *
 * A message is emailed to the other party the moment it is posted, so the mail
 * is only ever about a line the recipient has not read — which is exactly the
 * cursor-exact rule the plan asks for (a brand-new inbound message is unread by
 * definition). Sent through wp_mail wrapped in WooCommerce's own template, the
 * same way registration mail is (see Registration\Emails).
 */
class Emails
{
    /**
     * Notify the shop that a buyer posted. Sent to the WooCommerce admin email;
     * merchants also see the in-app bell and menu bubble.
     */
    public static function notifyShop(Conversation $conversation, Message $message): void
    {
        $buyer = get_userdata((int) $conversation->buyer_id);
        $name  = $buyer ? $buyer->display_name : __('A customer', 'softminal-b2b-wholesale-for-woocommerce');

        $subject = trim((string) $conversation->subject);
        $subject = $subject !== '' ? $subject : __('General enquiry', 'softminal-b2b-wholesale-for-woocommerce');

        $link = admin_url('admin.php?page=softminal-b2b-wholesale-for-woocommerce#/messages/' . (int) $conversation->id);

        self::send(
            (string) get_option('admin_email'),
            sprintf(
                /* translators: %s: customer name */
                __('New message from %s', 'softminal-b2b-wholesale-for-woocommerce'),
                $name
            ),
            __('You have a new B2B message', 'softminal-b2b-wholesale-for-woocommerce'),
            [
                sprintf(
                    /* translators: 1: customer name, 2: conversation subject */
                    __('%1$s wrote about "%2$s":', 'softminal-b2b-wholesale-for-woocommerce'),
                    esc_html($name),
                    esc_html($subject)
                ),
                self::quote($message->body),
                sprintf(
                    '<a href="%s">%s</a>',
                    esc_url($link),
                    esc_html__('Open the conversation', 'softminal-b2b-wholesale-for-woocommerce')
                ),
            ]
        );
    }

    /**
     * Notify the buyer that the shop replied.
     */
    public static function notifyBuyer(Conversation $conversation, Message $message): void
    {
        $buyer = get_userdata((int) $conversation->buyer_id);

        if (!$buyer) {
            return;
        }

        $subject = trim((string) $conversation->subject);
        $subject = $subject !== '' ? $subject : __('your enquiry', 'softminal-b2b-wholesale-for-woocommerce');

        self::send(
            $buyer->user_email,
            __('The store replied to your message', 'softminal-b2b-wholesale-for-woocommerce'),
            sprintf(
                /* translators: %s: customer first name */
                __('Hi %s,', 'softminal-b2b-wholesale-for-woocommerce'),
                $buyer->first_name ?: $buyer->display_name
            ),
            [
                sprintf(
                    /* translators: %s: conversation subject */
                    __('We have replied about %s:', 'softminal-b2b-wholesale-for-woocommerce'),
                    esc_html($subject)
                ),
                self::quote($message->body),
                sprintf(
                    '<a href="%s">%s</a>',
                    esc_url(self::buyerCentreUrl()),
                    esc_html__('View and reply', 'softminal-b2b-wholesale-for-woocommerce')
                ),
            ]
        );
    }

    /**
     * The storefront page where a buyer reads their messages. Defaults to the
     * My Account "Messages" endpoint; filterable for merchants who host the
     * `[smb2b_messages]` shortcode on a custom page.
     */
    private static function buyerCentreUrl(): string
    {
        $url = function_exists('wc_get_account_endpoint_url')
            ? wc_get_account_endpoint_url('smb2b-messages')
            : home_url('/');

        /**
         * Filter the URL buyers are sent to from message notifications.
         *
         * @param string $url The default My Account messages URL.
         */
        return (string) apply_filters('smb2b_messages_buyer_url', $url);
    }

    private static function quote(string $body): string
    {
        // Render the message body as a quoted block; keep line breaks, escape
        // everything else (the body is plain text sanitised on the way in).
        return '<blockquote style="margin:0 0 1em;padding:0 0 0 1em;border-left:3px solid #ddd;color:#555;">'
            . nl2br(esc_html($body))
            . '</blockquote>';
    }

    /**
     * @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;

        // Wrap in Woo's template so the mail matches the shop's order emails.
        // wrap_message() lives on WC_Emails, style_inline() on WC_Email — call
        // each on the object that owns it (a cross-call is fatal).
        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);
    }
}
