<?php

namespace ZenoChatbot\Helper;

use ZenoChatbot\Framework\Support\Arr;

class Email
{
    public static function sendCustomerReply($data = [])
    {
        $default = [
            'email'   => Arr::get($data, 'email', ''),
            'message' => Arr::get($data, 'message', '')
        ];

        // check if email and message are provided. if not throw an error
        if (empty($default['email']) || empty($default['message'])) {
            return [
                'success' => false,
                'message' => 'Email and message are required'
            ];
        }

        // check if email is valid. if not throw an error
        if (!is_email($default['email'])) {
            return [
                'success' => false,
                'message' => 'Invalid email'
            ];
        }

        // pull application settings
        $settings = Settings::getEmailSettings();

        // build email subject
        $subject = 'Reply from ' . $settings['from_name'];

        // build email content from a message
        $emailContent = $default['message'];

        // prepare email headers
        $headers = [];
        $headers[] = 'Content-Type: text/plain; charset=UTF-8';
        $headers[] = 'From: ' . $settings['from_name'] . ' <' . $settings['from_email'] . '>';

        // Reply-To defaults to the From sender when left empty (documented behavior).
        $replyToEmail = !empty($settings['reply_to']) ? $settings['reply_to'] : $settings['from_email'];
        $replyToName  = !empty($settings['reply_to_name']) ? $settings['reply_to_name'] : $settings['from_name'];

        if (!empty($replyToEmail)) {
            $replyToHeader = !empty($replyToName)
                ? $replyToName . ' <' . $replyToEmail . '>'
                : $replyToEmail;
            $headers[] = 'Reply-To: ' . $replyToHeader;
        }

        // send email using WordPress wp_mail
        $sent = wp_mail($default['email'], $subject, $emailContent, $headers);

        // if not sent, throw an error
        if (!$sent) {
            throw new \Exception('Failed to send email');
        }

        return [
            'success' => true,
            'message' => 'Email sent successfully'
        ];
    }
}
