<?php

/**
 * Email helper functions
 *
 * @package ArraySubs\Functions
 */

defined('ABSPATH') || exit;

/**
 * Send a subscription-related email
 *
 * This is a convenience wrapper for triggering subscription emails
 * through the WooCommerce email system.
 *
 * @param string $email_id        Email identifier (e.g., 'new_subscription', 'payment_failed')
 * @param int    $subscription_id Subscription ID
 * @param array  $variables       Additional template variables
 * @return bool Whether email was triggered successfully
 */
function arraysubs_send_subscription_email(string $email_id, int $subscription_id, array $variables = []): bool
{
    // WooCommerce must be active
    if (!function_exists('WC')) {
        return false;
    }

    $mailer = WC()->mailer();
    $email_key = 'arraysubs_' . $email_id;
    $email = $mailer->emails[$email_key] ?? null;

    if (!$email) {
        return false;
    }

    // Pass variables in args for template use
    $args = array_merge(['template_vars' => $variables], $variables);

    $email->trigger($subscription_id, $args);
    return true;
}

/**
 * Check if an email type is enabled
 *
 * @param string $email_id Email identifier
 * @return bool
 */
function arraysubs_is_email_enabled(string $email_id): bool
{
    // Map email IDs to setting keys
    $setting_map = [
        'new_subscription'             => 'emails.new_subscription.enabled',
        'renewal_reminder'             => 'emails.renewal_upcoming.enabled',
        'renewal_invoice'              => 'emails.renewal_invoice.enabled',
        'payment_successful'           => 'emails.renewal_payment_received.enabled',
        'payment_failed'               => 'emails.payment_failed.enabled',
        'subscription_on_hold'         => 'emails.subscription_on_hold.enabled',
        'subscription_cancelled'       => 'emails.subscription_cancelled.enabled',
        'subscription_expired'         => 'emails.subscription_expired.enabled',
        'auto_downgrade'               => 'emails.auto_downgrade.enabled',
        'subscription_skipped'         => 'emails.subscription_skipped.enabled',
        'subscription_paused'          => 'emails.subscription_paused.enabled',
        'subscription_resumed'         => 'emails.subscription_resumed.enabled',
        'trial_started'                => 'emails.trial_started.enabled',
        'trial_converted'              => 'emails.trial_converted.enabled',
        'plan_switch'                  => 'emails.plan_switch.enabled',
        'card_expiring'                 => 'emails.card_expiring.enabled',
        'renewal_requires_verification' => 'emails.renewal_requires_verification.enabled',
        'admin_new_subscription'        => 'emails.admin_new_subscription',
        'admin_payment_failed'          => 'emails.admin_payment_failed',
        'admin_subscription_cancelled'  => 'emails.admin_cancelled',
    ];

    $setting_key = $setting_map[$email_id] ?? null;

    if (!$setting_key) {
        return true; // Enable by default if no setting exists
    }

    return (bool) arraysubs_get_setting($setting_key, true);
}

/**
 * Get email placeholders for a subscription
 *
 * @param int $subscription_id Subscription ID
 * @return array Associative array of placeholder => value
 */
function arraysubs_get_email_placeholders(int $subscription_id): array
{
    $subscription = arraysubs_get_subscription($subscription_id);

    if (!$subscription instanceof \WP_Post) {
        return [];
    }

    $customer_id = get_post_meta($subscription_id, '_customer_id', true);
    $customer_email = get_post_meta($subscription_id, '_customer_email', true);
    $customer_name = '';
    $customer_first_name = '';

    if (!empty($customer_id)) {
        $user = get_user_by('ID', $customer_id);
        if ($user) {
            $customer_name = trim($user->first_name . ' ' . $user->last_name);
            $customer_first_name = $user->first_name ?: $user->display_name;
            if (empty($customer_name)) {
                $customer_name = $user->display_name;
            }
        }
    }

    // Build billing period string
    $interval = get_post_meta($subscription_id, '_billing_interval', true);
    $period = get_post_meta($subscription_id, '_billing_period', true);
    $billing_period = arraysubs_format_billing_period($interval, $period);

    // Get product name
    $product_name = arraysubs_get_subscription_product_name_by_subscription($subscription_id);

    return [
        '{site_title}'          => get_bloginfo('name'),
        '{site_address}'        => wp_parse_url(home_url(), PHP_URL_HOST),
        '{site_url}'            => home_url(),
        '{store_email}'         => get_option('admin_email'),
        '{subscription_id}'     => $subscription_id,
        '{customer_name}'       => $customer_name,
        '{customer_first_name}' => $customer_first_name,
        '{customer_email}'      => $customer_email ?: ($user->user_email ?? ''),
        '{product_name}'        => $product_name,
        '{next_payment_date}'   => arraysubs_format_date_local(
            get_post_meta($subscription_id, '_next_payment_date', true)
        ),
        '{recurring_amount}'    => wc_price(
            get_post_meta($subscription_id, '_recurring_amount', true)
        ),
        '{billing_period}'      => $billing_period,
        '{subscription_status}' => arraysubs_get_status_label($subscription->post_status),
        '{my_account_url}'      => wc_get_account_endpoint_url('subscriptions'),
    ];
}
