<?php

/**
 * Admin Subscription Pending Cancellation Email
 *
 * Sent to the admin when a subscription is scheduled to cancel at the end
 * of the current billing period.
 *
 * @package ArraySubs\Features\Emails\Emails
 * @since 1.0.0
 */

namespace ArraySubs\Features\Emails\Emails;

defined('ABSPATH') || exit;

use ArraySubs\Features\Emails\Abstracts\BaseSubscriptionEmail;

/**
 * Admin Subscription Pending Cancellation Email class
 */
class AdminSubscriptionPendingCancellationEmail extends BaseSubscriptionEmail
{
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->id             = 'arraysubs_admin_subscription_pending_cancellation';
        $this->customer_email = false;
        $this->title          = __('[ArraySubs] Subscription Scheduled to Cancel (Admin)', 'arraysubs');
        $this->description    = __('Sent to the admin when a subscription is scheduled to cancel at the end of the current billing period.', 'arraysubs');

        $this->heading        = __('Subscription scheduled to cancel', 'arraysubs');
        $this->subject        = __('[{site_title}] Subscription #{subscription_id} scheduled to cancel on {scheduled_cancel_date}', 'arraysubs');

        $this->template_html  = 'admin-subscription-pending-cancellation.php';
        $this->template_plain = 'plain/admin-subscription-pending-cancellation.php';

        $this->placeholders['{scheduled_cancel_date}'] = \arraysubs_format_timestamp_local(
            \current_time('timestamp', true),
            \get_option('date_format')
        );
        $this->placeholders['{cancellation_reason}'] = __('Customer requested cancellation', 'arraysubs');

        $this->recipient = $this->get_option('recipient', \get_option('admin_email'));

        parent::__construct();
    }

    /**
     * Trigger the email
     *
     * @param int   $subscription_id Subscription ID
     * @param array $args            Additional arguments
     */
    public function trigger(int $subscription_id, array $args = []): void
    {
        $this->subscription_id = $subscription_id;
        $this->subscription = \arraysubs_get_subscription($subscription_id);

        if (!$this->subscription instanceof \WP_Post) {
            return;
        }

        $this->setup_locale();
        $this->recipient = $this->get_option('recipient', \get_option('admin_email'));
        $this->populate_placeholders($args);

        if ($this->is_enabled() && $this->get_recipient()) {
            $this->send(
                $this->get_recipient(),
                $this->get_subject(),
                $this->get_content(),
                $this->get_headers(),
                $this->get_attachments()
            );
        }

        $this->restore_locale();
    }

    /**
     * Populate placeholders
     *
     * @param array $args Additional arguments
     */
    protected function populate_placeholders(array $args = []): void
    {
        parent::populate_placeholders($args);

        $scheduled_date = \get_post_meta($this->subscription_id, '_cancellation_scheduled_date', true);
        $this->placeholders['{scheduled_cancel_date}'] = !empty($scheduled_date)
            ? \arraysubs_format_date_local($scheduled_date)
            : __('end of billing period', 'arraysubs');

        $reason_key = (string) \get_post_meta($this->subscription_id, '_cancellation_reason', true);
        $reason_label = '' !== $reason_key && \function_exists('arraysubs_get_cancellation_reason_label')
            ? \arraysubs_get_cancellation_reason_label($reason_key)
            : $reason_key;

        $this->placeholders['{cancellation_reason}'] = $reason_label !== ''
            ? $reason_label
            : __('Not specified', 'arraysubs');
    }

    /**
     * Get template arguments
     *
     * @param bool $plain_text Whether this is plain text email
     * @return array
     */
    protected function get_template_args(bool $plain_text = false): array
    {
        $args = parent::get_template_args($plain_text);
        $args['arraysubs_sent_to_admin'] = true;

        $scheduled_date = \get_post_meta($this->subscription_id, '_cancellation_scheduled_date', true);
        $args['arraysubs_scheduled_cancel_date'] = !empty($scheduled_date)
            ? \arraysubs_format_date_local($scheduled_date)
            : '';
        $args['arraysubs_scheduled_cancel_date_raw'] = $scheduled_date;

        $reason_key = (string) \get_post_meta($this->subscription_id, '_cancellation_reason', true);
        $args['arraysubs_cancellation_reason'] = '' !== $reason_key && \function_exists('arraysubs_get_cancellation_reason_label')
            ? \arraysubs_get_cancellation_reason_label($reason_key)
            : $reason_key;

        $args['arraysubs_cancelled_by'] = (string) \get_post_meta($this->subscription_id, '_cancelled_by', true);

        return $args;
    }

    /**
     * Initialize form fields
     */
    public function init_form_fields(): void
    {
        parent::init_form_fields();

        $this->form_fields = array_merge(
            [
                'recipient' => [
                    'title'       => __('Recipient(s)', 'arraysubs'),
                    'type'        => 'text',
                    'description' => sprintf(
                        /* translators: %s: default admin email */
                        __('Enter recipients (comma separated) for this email. Defaults to %s.', 'arraysubs'),
                        '<code>' . esc_attr(\get_option('admin_email')) . '</code>'
                    ),
                    'placeholder' => '',
                    'default'     => '',
                    'desc_tip'    => true,
                ],
            ],
            $this->form_fields
        );
    }

    /**
     * Get default additional content
     *
     * @return string
     */
    public function get_default_additional_content(): string
    {
        return '';
    }
}
