<?php

/**
 * Renewal Requires Verification Email
 *
 * Sent to customers when a Stripe renewal needs SCA/3DS verification.
 *
 * @package ArraySubs\Features\Emails\Emails
 */

namespace ArraySubs\Features\Emails\Emails;

defined('ABSPATH') || exit;

use ArraySubs\Features\Emails\Abstracts\BaseSubscriptionEmail;

/**
 * Renewal requires verification email class.
 */
class RenewalRequiresVerificationEmail extends BaseSubscriptionEmail
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->id             = 'arraysubs_renewal_requires_verification';
        $this->customer_email = true;
        $this->title          = __('[ArraySubs] Renewal Requires Verification', 'arraysubs');
        $this->description    = __('Renewal verification emails are sent when an automatic renewal needs customer authentication.', 'arraysubs');
        $this->heading        = __('Your renewal needs verification', 'arraysubs');
        $this->subject        = __('[{site_title}] Verify your subscription renewal #{subscription_id}', 'arraysubs');
        $this->template_html  = 'customer-renewal-requires-verification.php';
        $this->template_plain = 'plain/customer-renewal-requires-verification.php';

        $this->placeholders['{order_id}']         = '67890';
        $this->placeholders['{verification_url}'] = wc_get_checkout_url();
        $this->placeholders['{auth_url}']         = wc_get_checkout_url();
        $this->placeholders['{payment_amount}']   = $this->format_payment_amount_placeholder(29.99);
        $this->placeholders['{auth_deadline}']    = $this->format_auth_deadline();

        parent::__construct();
    }

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

        if (! empty($args['order_id'])) {
            $order = wc_get_order(absint($args['order_id']));
            $this->order = $order instanceof \WC_Order ? $order : null;
        }

        $action_url     = $this->get_action_url($args);
        $auth_deadline  = $this->format_auth_deadline();
        $payment_amount = $this->order
            ? $this->format_payment_amount_placeholder((float) $this->order->get_total())
            : '';

        $this->placeholders['{order_id}']         = $this->order ? $this->order->get_id() : ($args['order_id'] ?? '');
        $this->placeholders['{verification_url}'] = $action_url;
        $this->placeholders['{auth_url}']         = $action_url;
        $this->placeholders['{payment_amount}']   = $payment_amount;
        $this->placeholders['{auth_deadline}']    = $auth_deadline;
    }

    /**
     * Get template arguments.
     *
     * @param bool $plain_text Whether this is plain text.
     * @return array
     */
    protected function get_template_args(bool $plain_text = false): array
    {
        $args           = parent::get_template_args($plain_text);
        $action_url     = (string) ($this->placeholders['{auth_url}'] ?? '');
        $auth_deadline  = (string) ($this->placeholders['{auth_deadline}'] ?? '');
        $payment_amount = (string) ($this->placeholders['{payment_amount}'] ?? '');

        $args['arraysubs_order_id']             = $this->order ? $this->order->get_id() : 0;
        $args['arraysubs_action_url']           = $action_url;
        $args['arraysubs_payment_amount']       = $payment_amount;
        $args['arraysubs_card_brand']           = (string) get_post_meta($this->subscription_id, '_payment_method_brand', true);
        $args['arraysubs_card_last4']           = (string) get_post_meta($this->subscription_id, '_payment_method_last4', true);
        $args['arraysubs_grace_period_ends_at'] = $auth_deadline;
        $args['arraysubs_auth_deadline']        = $auth_deadline;

        return $args;
    }

    /**
     * Get the verification action URL.
     *
     * @param array $args Additional arguments.
     * @return string
     */
    private function get_action_url(array $args = []): string
    {
        $action_url = (string) ($args['action_url'] ?? '');

        if ('' === $action_url && $this->order) {
            $action_url = add_query_arg('wc-stripe-confirmation', 1, $this->order->get_checkout_payment_url(false));
        }

        return $action_url;
    }

    /**
     * Format the SCA deadline for placeholders and templates.
     *
     * @return string
     */
    private function format_auth_deadline(): string
    {
        return arraysubs_format_timestamp_local(
            time() + (3 * DAY_IN_SECONDS),
            get_option('date_format') . ' ' . get_option('time_format')
        );
    }

    /**
     * Format payment amount for subject-safe placeholder usage.
     *
     * @param float $amount Payment amount.
     * @return string
     */
    private function format_payment_amount_placeholder(float $amount): string
    {
        return html_entity_decode(
            wp_strip_all_tags(wc_price($amount)),
            ENT_QUOTES,
            get_bloginfo('charset')
        );
    }

    /**
     * Get default additional content.
     *
     * @return string
     */
    public function get_default_additional_content(): string
    {
        return __('Complete verification as soon as possible to keep your subscription active.', 'arraysubs');
    }
}
