<?php

namespace WeDevs\Wpuf\Pro\Admin;

/**
 * Post status reject, approve email notification class
 *
 * @since   3.4.7
 *
 * @package WP User Frontend
 */
class Post_Status_Notification {
    private $user;

    /**
     * WPUF_Post_Status_Change constructor.
     */
    public function __construct() {
        add_filter( 'wpuf_mail_options', [ $this, 'add_mail_settings' ] );
        add_action( 'transition_post_status', [ $this, 'handle_post_status' ], 10, 3 );
    }

    /**
     * Global settings
     *
     * @since 3.4.7
     *
     * @param $settings_fields
     *
     * @return mixed
     */
    public function add_mail_settings( $settings_fields ) {
        $settings_fields[] = [
            'name'  => 'approved_post_email',
            'label' => '<span class="dashicons dashicons-saved"></span> ' . __( 'Approved Post Email', 'wpuf-pro' ),
            'type'  => 'html',
            'class' => 'approved-post-email',
        ];
        $settings_fields[] = [
            'name'    => 'enable_post_approval_notification',
            'class'   => 'approved-post-email-option',
            'label'   => __( 'Post Approval Notification', 'wpuf-pro' ),
            'desc'    => __( 'Enable Post Approval Notification .', 'wpuf-pro' ),
            'default' => 'on',
            'type'    => 'checkbox',
        ];
        $settings_fields[] = [
            'name'    => 'approved_post_email_subject',
            'label'   => __( 'Approved Email Subject for User', 'wpuf-pro' ),
            'desc'    => __( 'This sets the subject of the emails sent to approved post author.', 'wpuf-pro' ),
            'default' => 'Post has been approved',
            'type'    => 'text',
            'class'   => 'approved-post-email-option',
        ];
        $settings_fields[] = [
            'name'    => 'approved_post_email_body',
            'label'   => __( 'Approved Email Body for post author', 'wpuf-pro' ),
            'desc' => sprintf(
                __( 'This sets the body of the emails sent to approved post author.%1$s%2$sYou may use:%3$s %4$s %5$s %6$s %7$s', 'wpuf-pro' ),
                '<br>',
                '<strong>',
                '</strong>',
                '<code>{username}</code>',
                '<code>{display_name}</code>',
                '<code>{post_title}</code>',
                '<code>{post_link}</code>'
            ),
            'default' => 'Hi {username},

            Your post has been approved by an administrator.

            Thanks',
            'type'    => 'wysiwyg',
            'class'   => 'approved-post-email-option',
        ];

        return $settings_fields;
    }

    /**
     * Handle post status for email notification
     *
     * @since 3.4.7
     *
     * @param $old_status
     * @param $post
     *
     * @param $new_status
     *
     * @return void
     */
    public function handle_post_status( $new_status, $old_status, $post ) {
        if ( 'on' !== wpuf_get_option( 'enable_post_approval_notification', 'wpuf_mails', 'on' ) ) {
            return;
        }
        if ( $new_status === 'private' ) {
            return;
        }
        $form_id = get_post_meta( $post->ID, '_wpuf_form_id', true );
        if ( ! $form_id ) {
            return;
        }
        $form_settings = wpuf_get_form_settings( $form_id );
        if ( ! $form_settings ) {
            return;
        }
        $post_form_status = ! empty( $form_settings['post_status'] ) ? $form_settings['post_status'] : '';
        if ( $post_form_status === 'publish' ) {
            return;
        }
        if ( $old_status === $post_form_status && ( $new_status === 'publish' || $new_status === 'trash' ) ) {
            $this->send_mail( $new_status, $post );
        }
    }

    /**
     * Send email for reject, publish post
     *
     * @since 3.4.7
     *
     * @param $post
     *
     * @param $status
     *
     * @return void
     */
    public function send_mail( $status, $post ) {
        $this->user = get_user_by( 'id', $post->post_author );
        $user_email = $this->user->user_email;
        $subject    = '';
        $body       = '';

        // Only 'publish' status triggers an email. Any other status (e.g. 'trash') leaves
        // $subject/$body empty and falls through to the early-return below. This is intentional:
        // the original code passed empty values to wp_mail(), which was a latent bug.
        if ( 'publish' === $status ) {
            // Check for role-based template first (from HTML Email Templates module)
            $role_template          = null;
            $email_templates_active = class_exists( 'WPUF_Email_Templates' ) && method_exists( 'WPUF_Email_Templates', 'get_template_for_user' );

            if ( $email_templates_active ) {
                $role_template = \WPUF_Email_Templates::get_template_for_user( 'approved_post_email', $post->post_author );
            }

            if ( $role_template && ! empty( $role_template['subject'] ) && ! empty( $role_template['body'] ) ) {
                // Use role-based template
                $subject = $role_template['subject'];
                $body    = wpautop( $role_template['body'] );
            } else {
                // Check if user's role is allowed to receive the default template
                if ( $email_templates_active && method_exists( 'WPUF_Email_Templates', 'should_user_receive_default_email' ) ) {
                    if ( ! \WPUF_Email_Templates::should_user_receive_default_email( 'approved_post_email', $post->post_author ) ) {
                        /** This action is documented in includes/Frontend/Profile_Form.php */
                        do_action( 'wpuf_email_suppressed_by_role', 'approved_post_email', $post->post_author, $status );

                        return;
                    }
                }

                // Fall back to default template
                $subject = wpuf_get_option( 'approved_post_email_subject', 'wpuf_mails' );
                $body    = wpautop( wpuf_get_option( 'approved_post_email_body', 'wpuf_mails' ) );
            }
        }

        if ( empty( $subject ) || empty( $body ) ) {
            return;
        }

        $body    = $this->prepare_mail_body( $post, $body );
        $body    = get_formatted_mail_body( $body, $subject );
        $headers = [ 'Content-Type: text/html; charset=UTF-8' ];
        wp_mail( $user_email, $subject, $body, $headers );
    }

    /**
     * Placeholder for mail body
     *
     * @since 3.4.7
     *
     * @param $mail_body
     *
     * @param $post
     *
     * @return string|string[]
     */
    public function prepare_mail_body( $post, $mail_body ) {
        $sub_field_search  = [ '{username}', '{user_email}', '{display_name}', '{post_title}', '{post_link}' ];
        $sub_field_replace = [
            $this->user->user_login,
            $this->user->user_email,
            $this->user->display_name,
            $post->post_title,
            get_post_permalink( $post->ID ),
        ];

        return str_replace( $sub_field_search, $sub_field_replace, $mail_body );
    }

}
