<?php
/**
 * Subscription history component
 *
 * @link       https://yourwebsite.com
 * @since      1.0.0
 *
 * @package    Subscription_System
 * @subpackage Subscription_System/public/partials/components
 */

// This component requires $user_id to be set before including it
if (!isset($user_id)) {
    $user_id = get_current_user_id();
}

// Check if we should limit the number of entries
$limit = isset($history_limit) ? intval($history_limit) : 0;

// Try to get cached data first
$cache_key = 'subscription_history_' . $user_id . '_' . $limit;
$history = wp_cache_get($cache_key, 'subscription_system');

if (false === $history) {
    global $wpdb;
    $subscriptions_table = $wpdb->prefix . 'subscriptions';
    $plans_table = $wpdb->prefix . 'subscription_plans';

    // Prepare the query with proper escaping
    $query = $wpdb->prepare(
        "SELECT s.*, p.plan_name, p.duration 
         FROM {$wpdb->prefix}subscriptions s 
         LEFT JOIN {$wpdb->prefix}subscription_plans p ON s.plan_id = p.id 
         WHERE s.user_id = %d 
         ORDER BY s.id DESC" . ($limit > 0 ? " LIMIT %d" : ""),
        array_merge([$user_id], $limit > 0 ? [$limit] : [])
    );

    $history = $wpdb->get_results($query);
    
    // Cache the results for 5 minutes
    wp_cache_set($cache_key, $history, 'subscription_system', 5 * MINUTE_IN_SECONDS);
}

// Get total count for pagination
$total_count = 0;
if ($limit > 0) {
    $cache_key_count = 'subscription_history_count_' . $user_id;
    $total_count = wp_cache_get($cache_key_count, 'subscription_system');
    
    if (false === $total_count) {
        global $wpdb;
        $total_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}subscriptions WHERE user_id = %d",
            $user_id
        ));
        wp_cache_set($cache_key_count, $total_count, 'subscription_system', 5 * MINUTE_IN_SECONDS);
    }
}

// Get currency from options
$currency = get_option('subscription_currency', 'USD');

// Check if we should show a custom title
$history_title = isset($history_title) ? $history_title : esc_html__('Subscription History', 'subscription-system');
?>

<div class="subscription-history-component">
    <h3><?php echo esc_html($history_title); ?></h3>
    
    <?php if ($history && !empty($history)) : ?>
        <div class="subscription-history-wrapper">
            <table class="subscription-history-table">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Plan', 'subscription-system'); ?></th>
                        <th><?php esc_html_e('Status', 'subscription-system'); ?></th>
                        <th><?php esc_html_e('Start Date', 'subscription-system'); ?></th>
                        <th><?php esc_html_e('End Date', 'subscription-system'); ?></th>
                        <th><?php esc_html_e('Amount', 'subscription-system'); ?></th>
                        <?php if (isset($show_actions) && $show_actions) : ?>
                        <th><?php esc_html_e('Actions', 'subscription-system'); ?></th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($history as $item) : 
                        // Calculate end date based on duration
                        $item_duration = isset($item->duration) ? intval($item->duration) : 30;
                        $item_end_timestamp = strtotime("+" . $item_duration . " days", strtotime($item->start_date));
                        $item_end_date = date_i18n(get_option('date_format'), $item_end_timestamp);
                        
                        // Get duration label
                        $item_duration_label = '';
                        switch ($item_duration) {
                            case 30:
                                $item_duration_label = esc_html__('Monthly', 'subscription-system');
                                break;
                            case 90:
                                $item_duration_label = esc_html__('Quarterly', 'subscription-system');
                                break;
                            case 180:
                                $item_duration_label = esc_html__('Biannually', 'subscription-system');
                                break;
                            case 365:
                                $item_duration_label = esc_html__('Annually', 'subscription-system');
                                break;
                            default:
                                /* translators: %d: number of days for subscription duration */
                                $item_duration_label = sprintf(
                                    esc_html__('Every %d days', 'subscription-system'),
                                    $item_duration
                                );
                        }
                    ?>
                        <tr>
                            <td><?php echo esc_html($item->plan_name); ?></td>
                            <td>
                                <span class="subscription-status <?php echo esc_attr(strtolower($item->status)); ?>">
                                    <?php echo esc_html(ucfirst($item->status)); ?>
                                </span>
                            </td>
                            <td><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($item->start_date))); ?></td>
                            <td>
                                <?php 
                                if (!empty($item->end_date) && $item->end_date !== '0000-00-00 00:00:00') {
                                    echo esc_html(date_i18n(get_option('date_format'), strtotime($item->end_date)));
                                } else {
                                    echo esc_html($item_end_date);
                                    echo ' <span class="renewal-type">(' . esc_html($item_duration_label) . ')</span>';
                                }
                                ?>
                            </td>
                            <td><?php echo esc_html($currency . ' ' . number_format($item->amount, 2)); ?></td>
                            <?php if (isset($show_actions) && $show_actions) : ?>
                            <td class="subscription-actions-cell">
                                <?php if (strtolower($item->status) === 'active') : ?>
                                    <button type="button" class="subscription-action-btn ss-pause-subscription" data-id="<?php echo esc_attr($item->id); ?>">
                                        <?php esc_html_e('Pause', 'subscription-system'); ?>
                                    </button>
                                    <button type="button" class="subscription-action-btn ss-cancel-subscription" data-id="<?php echo esc_attr($item->id); ?>">
                                        <?php esc_html_e('Cancel', 'subscription-system'); ?>
                                    </button>
                                <?php elseif (strtolower($item->status) === 'paused') : ?>
                                    <button type="button" class="subscription-action-btn ss-resume-subscription" data-id="<?php echo esc_attr($item->id); ?>">
                                        <?php esc_html_e('Resume', 'subscription-system'); ?>
                                    </button>
                                <?php endif; ?>
                            </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <?php if ($limit > 0 && $total_count > $limit) : ?>
                <div class="subscription-history-footer">
                    <p class="showing-entries">
                        <?php 
                        /* translators: %1$d: number of entries shown, %2$d: total number of entries */
                        echo sprintf(
                            esc_html__('Showing %1$d of %2$d entries', 'subscription-system'),
                            count($history),
                            $total_count
                        ); 
                        ?>
                    </p>
                </div>
            <?php endif; ?>
        </div>
    <?php else : ?>
        <p class="no-history-message"><?php esc_html_e('No subscription history found.', 'subscription-system'); ?></p>
    <?php endif; ?>
</div>

<?php if (isset($show_actions) && $show_actions) : ?>
<script>
jQuery(document).ready(function($) {
    // Remove the old event handlers since we're using the ones in subscription-system-public.js
});
</script>
<?php endif; ?> 