<?php

/**
 * Trial Conversion Service
 *
 * @package ArraySubs\Features\RecurringBilling\Services
 */

namespace ArraySubs\Features\RecurringBilling\Services;

defined('ABSPATH') || exit;

use ArraySubs\Features\PlanSwitching\Services\AutoDowngradeHandler;

/**
 * Handles trial-to-active subscription conversion
 */
class TrialConverter
{
    /**
     * Process trial conversions (scheduled daily)
     */
    public function processTrialConversions(): void
    {
        // Get all trial subscriptions
        $args = [
            'post_type'      => 'arraysubs_data',
            'post_status'    => 'arraysubs-trial',
            'posts_per_page' => -1,
            'meta_query'     => [
                [
                    'key'     => '_next_payment_date',
                    'value'   => current_time('mysql', true),
                    'compare' => '<=',
                    'type'    => 'DATETIME',
                ],
            ],
        ];

        $subscriptions = get_posts($args);

        foreach ($subscriptions as $subscription) {
            $this->convertTrialToActive($subscription->ID);
        }
    }

    /**
     * Convert a single trial subscription to active
     *
     * @param int $subscription_id Subscription ID
     * @return bool True on success
     */
    public function convertTrialToActive(int $subscription_id): bool
    {
        $subscription = arraysubs_get_subscription($subscription_id);

        if (!$subscription instanceof \WP_Post || $subscription->post_status !== 'arraysubs-trial') {
            return false;
        }

        if (
            class_exists(AutoDowngradeHandler::class)
            && AutoDowngradeHandler::shouldHandleTrialConversion($subscription_id)
        ) {
            if (AutoDowngradeHandler::processTrialExpiry($subscription_id)) {
                return true;
            }
        }

        // Update status to active
        wp_update_post([
            'ID'          => $subscription_id,
            'post_status' => 'arraysubs-active',
        ]);

        // Calculate next payment date based on billing period (not trial period)
        $billing_interval = (int) get_post_meta($subscription_id, '_billing_interval', true);
        $billing_period = get_post_meta($subscription_id, '_billing_period', true);

        $next_payment_date = arraysubs_calculate_next_payment_date(
            current_time('mysql', true),
            $billing_interval,
            $billing_period
        );

        update_post_meta($subscription_id, '_next_payment_date', $next_payment_date);

        // Clear trial info
        update_post_meta($subscription_id, '_trial_length', 0);

        // Trigger action
        do_action('arraysubs_trial_converted', $subscription_id);

        // Log the conversion
        $this->logConversion($subscription_id);

        return true;
    }

    /**
     * Log trial conversion
     *
     * @param int $subscription_id Subscription ID
     */
    private function logConversion(int $subscription_id): void
    {
        $customer_id = get_post_meta($subscription_id, '_customer_id', true);
        $product_id = get_post_meta($subscription_id, '_product_id', true);
    }

    /**
     * Check if subscription is in trial
     *
     * @param int $subscription_id Subscription ID
     * @return bool True if in trial
     */
    public function isInTrial(int $subscription_id): bool
    {
        $subscription = arraysubs_get_subscription($subscription_id);

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

        return $subscription->post_status === 'arraysubs-trial';
    }

    /**
     * Get trial end date
     *
     * @param int $subscription_id Subscription ID
     * @return string|null Trial end date or null
     */
    public function getTrialEndDate(int $subscription_id): ?string
    {
        if (!$this->isInTrial($subscription_id)) {
            return null;
        }

        return get_post_meta($subscription_id, '_next_payment_date', true) ?: null;
    }
}
