<?php

/**
 * Retention Discount Accepted Email
 *
 * Sent to customers when they accept a retention discount offer.
 *
 * @package ArraySubs\Features\Emails\Emails
 * @since 1.0.0
 */

namespace ArraySubs\Features\Emails\Emails;

defined('ABSPATH') || exit;

use ArraySubs\Features\Emails\Abstracts\BaseSubscriptionEmail;

/**
 * Retention Discount Accepted Email class.
 */
class RetentionDiscountAcceptedEmail extends BaseSubscriptionEmail
{
    /**
     * Offer title.
     *
     * @var string
     */
    protected string $offer_title = '';

    /**
     * Discount label.
     *
     * @var string
     */
    protected string $discount_value = '';

    /**
     * Discount duration in renewals.
     *
     * @var int
     */
    protected int $discount_duration = 0;

    /**
     * Base recurring amount.
     *
     * @var string
     */
    protected string $base_recurring_amount = '';

    /**
     * Discounted recurring amount.
     *
     * @var string
     */
    protected string $discounted_recurring_amount = '';

    /**
     * Savings per renewal.
     *
     * @var string
     */
    protected string $savings_per_renewal = '';

    /**
     * Next payment date.
     *
     * @var string
     */
    protected string $next_payment_date = '';

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->id             = 'arraysubs_retention_discount_accepted';
        $this->customer_email = true;
        $this->title          = \__('[ArraySubs] Retention Discount Accepted', 'arraysubs');
        $this->description    = \__('Sent to customers when they accept a retention discount offer during the cancellation rescue flow.', 'arraysubs');

        $this->heading        = \__('Your subscription discount is now active', 'arraysubs');
        $this->subject        = \__('[{site_title}] Your retention discount for {product_name} is active', 'arraysubs');

        $this->template_html  = 'customer-retention-discount-accepted.php';
        $this->template_plain = 'plain/customer-retention-discount-accepted.php';

        $this->offer_title                 = \__('Special discount offer', 'arraysubs');
        $this->discount_value              = '20%';
        $this->discount_duration           = 3;
        $this->base_recurring_amount       = wc_price(29.99);
        $this->discounted_recurring_amount = wc_price(23.99);
        $this->savings_per_renewal         = wc_price(6.00);
        $this->next_payment_date           = \arraysubs_format_timestamp_local(
            strtotime('+30 days', \current_time('timestamp', true)),
            \get_option('date_format')
        );

        parent::__construct();

        $this->placeholders['{offer_title}'] = $this->offer_title;
        $this->placeholders['{discount_value}'] = $this->discount_value;
        $this->placeholders['{discount_duration}'] = (string) $this->discount_duration;
        $this->placeholders['{base_recurring_amount}'] = $this->base_recurring_amount;
        $this->placeholders['{discounted_recurring_amount}'] = $this->discounted_recurring_amount;
        $this->placeholders['{savings_per_renewal}'] = $this->savings_per_renewal;
    }

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

        $offer_data = isset($args['offer_data']) && is_array($args['offer_data'])
            ? $args['offer_data']
            : [];

        $offer_details = \get_post_meta($this->subscription_id, '_retention_offer_details', true);
        $offer_details = is_array($offer_details) ? $offer_details : [];

        $discount = \arraysubs_get_subscription_active_retention_discount($this->subscription_id);
        $discount = is_array($discount) ? $discount : [];

        $discount_type = \sanitize_text_field($discount['type'] ?? ($offer_data['discount_type'] ?? 'percent'));
        $discount_amount = (float) ($discount['amount'] ?? ($offer_data['discount_amount'] ?? \get_post_meta($this->subscription_id, '_retention_discount_amount', true)));
        $duration = \absint($discount['remaining'] ?? \get_post_meta($this->subscription_id, '_retention_discount_remaining', true));
        $base_amount = (float) ($discount['base_amount'] ?? \get_post_meta($this->subscription_id, '_retention_discount_base_amount', true));
        $effective_amount = (float) ($discount['effective_amount'] ?? \get_post_meta($this->subscription_id, '_retention_discount_effective_amount', true));

        if ($base_amount <= 0) {
            $base_amount = (float) \get_post_meta($this->subscription_id, '_recurring_amount', true);
        }

        if ($effective_amount <= 0 && $base_amount > 0) {
            $effective_amount = (float) \arraysubs_get_subscription_effective_recurring_amount($this->subscription_id);
        }

        $this->offer_title = \sanitize_text_field($offer_data['offer_title'] ?? ($offer_details['title'] ?? ''));
        if ($this->offer_title === '') {
            $this->offer_title = \__('Special discount offer', 'arraysubs');
        }

        $this->discount_value = $this->format_discount_value($discount_type, $discount_amount);
        $this->discount_duration = max(1, $duration);
        $this->base_recurring_amount = wc_price($base_amount);
        $this->discounted_recurring_amount = wc_price($effective_amount);
        $this->savings_per_renewal = wc_price(max(0, $base_amount - $effective_amount));

        $next_payment = \get_post_meta($this->subscription_id, '_next_payment_date', true);
        $this->next_payment_date = !empty($next_payment)
            ? \arraysubs_format_date_local($next_payment)
            : \__('N/A', 'arraysubs');

        $this->placeholders['{offer_title}'] = $this->offer_title;
        $this->placeholders['{discount_value}'] = $this->discount_value;
        $this->placeholders['{discount_duration}'] = (string) $this->discount_duration;
        $this->placeholders['{base_recurring_amount}'] = $this->base_recurring_amount;
        $this->placeholders['{discounted_recurring_amount}'] = $this->discounted_recurring_amount;
        $this->placeholders['{savings_per_renewal}'] = $this->savings_per_renewal;
    }

    /**
     * Get template arguments.
     *
     * @param bool $plain_text Whether plain text email.
     * @return array
     */
    protected function get_template_args(bool $plain_text = false): array
    {
        $args = parent::get_template_args($plain_text);
        $args['arraysubs_offer_title'] = $this->offer_title;
        $args['arraysubs_discount_value'] = $this->discount_value;
        $args['arraysubs_discount_duration'] = $this->discount_duration;
        $args['arraysubs_base_recurring_amount'] = $this->base_recurring_amount;
        $args['arraysubs_discounted_recurring_amount'] = $this->discounted_recurring_amount;
        $args['arraysubs_savings_per_renewal'] = $this->savings_per_renewal;
        $args['arraysubs_next_payment_date'] = $this->next_payment_date;

        return $args;
    }

    /**
     * Get default additional content.
     *
     * @return string
     */
    public function get_default_additional_content(): string
    {
        return \__('Thanks for staying with us. Your next renewals will use the discounted amount shown in this email while the offer remains active.', 'arraysubs');
    }

    /**
     * Format the discount label for display.
     *
     * @param string $discount_type Discount type.
     * @param float  $discount_amount Discount amount.
     * @return string
     */
    private function format_discount_value(string $discount_type, float $discount_amount): string
    {
        if ($discount_type === 'percent') {
            $formatted_amount = rtrim(rtrim(sprintf('%.2f', $discount_amount), '0'), '.');
            return $formatted_amount . '%';
        }

        return \wp_strip_all_tags(\wc_price($discount_amount));
    }
}
