<?php
/**
 * Account Content Subscriptions Tab
 *
 * @link       https://mediahubster.in
 * @since      1.0.4
 *
 * @package    Subscription_System
 * @subpackage Subscription_System/public/partials/account-tabs
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

// Get current user ID
$user_id = get_current_user_id();

// Initialize content manager
$content_manager = new Subs_Sys_Content_Manager();

// Ensure content tables exist before querying
if (!Subs_Sys_DB_Updater::content_tables_exist()) {
    $db_updater = new Subs_Sys_DB_Updater();
    $db_updater->add_content_subscription_tables();
    error_log('Content tables created from account page');
}

// Get user's active content subscriptions
$content_subscriptions = $content_manager->get_user_active_content_subscriptions($user_id);

// Debug logging
error_log('User ID: ' . $user_id);
error_log('Content subscriptions count: ' . count($content_subscriptions));
error_log('Content subscriptions data: ' . wp_json_encode($content_subscriptions));
error_log('Content tables exist: ' . (Subs_Sys_DB_Updater::content_tables_exist() ? 'yes' : 'no'));

// Get available content plans
$available_plans = $content_manager->get_content_plans();

// Filter out plans user is already subscribed to
$subscribed_plan_ids = array_column($content_subscriptions, 'content_plan_id');
$available_plans = array_filter($available_plans, function($plan) use ($subscribed_plan_ids) {
    return !in_array($plan->id, $subscribed_plan_ids);
});

?>

<div class="account-content-subscriptions">
    <div class="account-section-header">
        <h2><?php esc_html_e('Content Subscriptions', 'subscription-system'); ?></h2>
        <p class="section-description">
            <?php esc_html_e('Manage your content subscription plans and get notified when new content is published.', 'subscription-system'); ?>
        </p>
    </div>

    <!-- Current Content Subscriptions -->
    <div class="current-subscriptions">
        <h3><?php esc_html_e('Your Active Subscriptions', 'subscription-system'); ?></h3>
        
        <?php if (empty($content_subscriptions)): ?>
            <div class="no-subscriptions">
                <div class="empty-state">
                    <div class="empty-icon">📰</div>
                    <h4><?php esc_html_e('No Content Subscriptions Yet', 'subscription-system'); ?></h4>
                    <p><?php esc_html_e('You haven\'t subscribed to any content plans yet. Browse available plans below to get started.', 'subscription-system'); ?></p>
                </div>
            </div>
        <?php else: ?>
            <div class="subscriptions-grid">
                <?php foreach ($content_subscriptions as $subscription): ?>
                    <?php
                    // Determine status class and text
                    $status_class = 'status-' . $subscription->status;
                    $is_active = $subscription->status === 'active' && strtotime($subscription->end_date) > time();
                    $is_expired = strtotime($subscription->end_date) <= time();
                    
                    if ($is_expired && $subscription->status === 'active') {
                        $status_class = 'status-expired';
                        $status_text = __('Expired', 'subscription-system');
                    } else {
                        $status_text = ucfirst($subscription->status);
                    }

                    // Get content type display name
                    $content_types = $content_manager->get_content_type_options();
                    $content_type_display = $content_types[$subscription->content_type] ?? $subscription->content_type;

                    // Get content names
                    $content_names = array();
                    if ($subscription->content_ids) {
                        switch ($subscription->content_type) {
                            case 'category':
                                foreach ($subscription->content_ids as $cat_id) {
                                    $category = get_category($cat_id);
                                    if ($category) {
                                        $content_names[] = $category->name;
                                    }
                                }
                                break;
                            case 'tag':
                                foreach ($subscription->content_ids as $tag_id) {
                                    $tag = get_tag($tag_id);
                                    if ($tag) {
                                        $content_names[] = $tag->name;
                                    }
                                }
                                break;
                            case 'post':
                                foreach ($subscription->content_ids as $post_id) {
                                    $post = get_post($post_id);
                                    if ($post) {
                                        $content_names[] = $post->post_title;
                                    }
                                }
                                break;
                            case 'post_type':
                                foreach ($subscription->content_ids as $post_type) {
                                    $post_type_obj = get_post_type_object($post_type);
                                    if ($post_type_obj) {
                                        $content_names[] = $post_type_obj->label;
                                    }
                                }
                                break;
                        }
                    }
                    ?>
                    <div class="subscription-card">
                        <div class="subscription-header">
                            <h4 class="subscription-title"><?php echo esc_html($subscription->plan_name); ?></h4>
                            <span class="subscription-status <?php echo esc_attr($status_class); ?>">
                                <?php echo esc_html($status_text); ?>
                            </span>
                        </div>
                        
                        <div class="subscription-details">
                            <div class="detail-row">
                                <span class="detail-label"><?php esc_html_e('Content Type:', 'subscription-system'); ?></span>
                                <span class="detail-value"><?php echo esc_html($content_type_display); ?></span>
                            </div>
                            
                            <?php if (!empty($content_names)): ?>
                                <div class="detail-row">
                                    <span class="detail-label"><?php esc_html_e('Content:', 'subscription-system'); ?></span>
                                    <span class="detail-value"><?php echo esc_html(implode(', ', array_slice($content_names, 0, 3))); ?>
                                        <?php if (count($content_names) > 3): ?>
                                            <span class="more-items">+<?php echo (count($content_names) - 3); ?> more</span>
                                        <?php endif; ?>
                                    </span>
                                </div>
                            <?php endif; ?>
                            
                            <div class="detail-row">
                                <span class="detail-label"><?php esc_html_e('Notifications:', 'subscription-system'); ?></span>
                                <span class="detail-value"><?php echo esc_html(ucfirst($subscription->notification_frequency)); ?></span>
                            </div>
                            
                            <div class="detail-row">
                                <span class="detail-label"><?php esc_html_e('Valid Until:', 'subscription-system'); ?></span>
                                <span class="detail-value"><?php echo esc_html(date('M j, Y', strtotime($subscription->end_date))); ?></span>
                            </div>
                        </div>
                        
                        <?php if ($subscription->description): ?>
                            <div class="subscription-description">
                                <p><?php echo esc_html($subscription->description); ?></p>
                            </div>
                        <?php endif; ?>
                        
                        <div class="subscription-actions">
                            <?php if ($is_active): ?>
                                <button class="btn btn-danger btn-sm unsubscribe-from-plan" 
                                        data-plan-id="<?php echo esc_attr($subscription->content_plan_id); ?>"
                                        data-plan-name="<?php echo esc_attr($subscription->plan_name); ?>">
                                    <?php esc_html_e('Unsubscribe', 'subscription-system'); ?>
                                </button>
                            <?php elseif ($is_expired): ?>
                                <button class="btn btn-primary btn-sm renew-subscription" 
                                        data-plan-id="<?php echo esc_attr($subscription->content_plan_id); ?>">
                                    <?php esc_html_e('Renew', 'subscription-system'); ?>
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Available Content Plans -->
    <?php if (!empty($available_plans)): ?>
        <div class="available-plans">
            <h3><?php esc_html_e('Available Content Plans', 'subscription-system'); ?></h3>
            <p class="section-description">
                <?php esc_html_e('Subscribe to these plans to get notified about new content.', 'subscription-system'); ?>
            </p>
            
            <div class="plans-grid">
                <?php foreach ($available_plans as $plan): ?>
                    <?php
                    // Get content type display name
                    $content_types = $content_manager->get_content_type_options();
                    $content_type_display = $content_types[$plan->content_type] ?? $plan->content_type;
                    
                    // Get content names for this plan
                    $content_names = array();
                    if ($plan->content_ids) {
                        switch ($plan->content_type) {
                            case 'category':
                                foreach ($plan->content_ids as $cat_id) {
                                    $category = get_category($cat_id);
                                    if ($category) {
                                        $content_names[] = $category->name;
                                    }
                                }
                                break;
                            case 'tag':
                                foreach ($plan->content_ids as $tag_id) {
                                    $tag = get_tag($tag_id);
                                    if ($tag) {
                                        $content_names[] = $tag->name;
                                    }
                                }
                                break;
                            case 'post_type':
                                foreach ($plan->content_ids as $post_type) {
                                    $post_type_obj = get_post_type_object($post_type);
                                    if ($post_type_obj) {
                                        $content_names[] = $post_type_obj->label;
                                    }
                                }
                                break;
                        }
                    }
                    ?>
                    <div class="plan-card">
                        <div class="plan-header">
                            <h4 class="plan-title"><?php echo esc_html($plan->plan_name); ?></h4>
                            <div class="plan-price">
                                <?php if ($plan->price > 0): ?>
                                    <span class="price-amount">$<?php echo esc_html(number_format($plan->price, 2)); ?></span>
                                    <span class="price-period">/ <?php echo esc_html($plan->duration . ' ' . $plan->duration_unit); ?></span>
                                <?php else: ?>
                                    <span class="price-free"><?php esc_html_e('Free', 'subscription-system'); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <?php if ($plan->description): ?>
                            <div class="plan-description">
                                <p><?php echo esc_html($plan->description); ?></p>
                            </div>
                        <?php endif; ?>
                        
                        <div class="plan-details">
                            <div class="detail-row">
                                <span class="detail-label"><?php esc_html_e('Content Type:', 'subscription-system'); ?></span>
                                <span class="detail-value"><?php echo esc_html($content_type_display); ?></span>
                            </div>
                            
                            <?php if (!empty($content_names)): ?>
                                <div class="detail-row">
                                    <span class="detail-label"><?php esc_html_e('Includes:', 'subscription-system'); ?></span>
                                    <span class="detail-value"><?php echo esc_html(implode(', ', array_slice($content_names, 0, 2))); ?>
                                        <?php if (count($content_names) > 2): ?>
                                            <span class="more-items">+<?php echo (count($content_names) - 2); ?> more</span>
                                        <?php endif; ?>
                                    </span>
                                </div>
                            <?php endif; ?>
                            
                            <div class="detail-row">
                                <span class="detail-label"><?php esc_html_e('Notifications:', 'subscription-system'); ?></span>
                                <span class="detail-value"><?php echo esc_html(ucfirst($plan->notification_frequency)); ?></span>
                            </div>
                        </div>
                        
                        <div class="plan-actions">
                            <button class="btn btn-primary subscribe-to-plan" 
                                    data-plan-id="<?php echo esc_attr($plan->id); ?>">
                                <?php if ($plan->price > 0): ?>
                                    <?php printf(esc_html__('Subscribe - $%s', 'subscription-system'), number_format($plan->price, 2)); ?>
                                <?php else: ?>
                                    <?php esc_html_e('Subscribe for Free', 'subscription-system'); ?>
                                <?php endif; ?>
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Handle subscription to content plan
    $('.subscribe-to-plan').on('click', function(e) {
        e.preventDefault();
        
        const button = $(this);
        const planId = button.data('plan-id');
        const originalText = button.text();
        
        // Disable button and show loading
        button.prop('disabled', true).text('<?php esc_html_e('Processing...', 'subscription-system'); ?>');
        
        $.ajax({
            url: subs_sys_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'subscribe_to_content_plan',
                content_plan_id: planId,
                nonce: '<?php echo wp_create_nonce('subscribe_to_content_plan'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    if (response.data.redirect) {
                        window.location.href = response.data.redirect;
                    } else {
                        // Reload page to show updated subscriptions
                        window.location.reload();
                    }
                } else {
                    alert(response.data.message);
                    button.prop('disabled', false).text(originalText);
                }
            },
            error: function() {
                alert('<?php esc_html_e('An error occurred. Please try again.', 'subscription-system'); ?>');
                button.prop('disabled', false).text(originalText);
            }
        });
    });
    
    // Handle renewal
    $('.renew-subscription').on('click', function(e) {
        e.preventDefault();
        $(this).trigger('click');
    });
    
    // Handle unsubscribe from content plan
    $('.unsubscribe-from-plan').on('click', function(e) {
        e.preventDefault();
        
        const button = $(this);
        const planId = button.data('plan-id');
        const planName = button.data('plan-name');
        const originalText = button.text();
        
        // Confirm unsubscribe
        if (!confirm('<?php esc_html_e('Are you sure you want to unsubscribe from', 'subscription-system'); ?> "' + planName + '"? <?php esc_html_e('You will no longer receive notifications for this content.', 'subscription-system'); ?>')) {
            return;
        }
        
        // Disable button and show loading
        button.prop('disabled', true).text('<?php esc_html_e('Unsubscribing...', 'subscription-system'); ?>');
        
        $.ajax({
            url: subs_sys_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'unsubscribe_from_content_plan',
                plan_id: planId,
                unsubscribe_nonce: '<?php echo wp_create_nonce('unsubscribe_from_content_plan'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    alert('<?php esc_html_e('Successfully unsubscribed!', 'subscription-system'); ?>');
                    // Reload page to show updated subscriptions
                    window.location.reload();
                } else {
                    alert(response.data.message || '<?php esc_html_e('Failed to unsubscribe. Please try again.', 'subscription-system'); ?>');
                    button.prop('disabled', false).text(originalText);
                }
            },
            error: function() {
                alert('<?php esc_html_e('An error occurred. Please try again.', 'subscription-system'); ?>');
                button.prop('disabled', false).text(originalText);
            }
        });
    });
});
</script>

<style>
.account-content-subscriptions {
    max-width: 1200px;
}

.account-section-header {
    margin-bottom: 30px;
}

.account-section-header h2 {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
}

.section-description {
    color: #666;
    margin: 0 0 20px 0;
}

.current-subscriptions,
.available-plans {
    margin-bottom: 40px;
}

.current-subscriptions h3,
.available-plans h3 {
    margin: 0 0 16px 0;
    font-size: 20px;
    font-weight: 600;
}

/* Empty State */
.no-subscriptions {
    text-align: center;
    padding: 60px 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 2px dashed #dee2e6;
}

.empty-state .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
}

.empty-state h4 {
    margin: 0 0 8px 0;
    font-size: 18px;
    color: #333;
}

.empty-state p {
    color: #666;
    margin: 0;
}

/* Subscription Cards */
.subscriptions-grid,
.plans-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    gap: 20px;
}

.subscription-card,
.plan-card {
    background: #fff;
    border: 1px solid #e1e8ed;
    border-radius: 8px;
    padding: 20px;
    transition: box-shadow 0.2s;
}

.subscription-card:hover,
.plan-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.subscription-header,
.plan-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;
}

.subscription-title,
.plan-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    flex: 1;
}

.subscription-status {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.status-active {
    background: #d4edda;
    color: #155724;
}

.status-expired,
.status-cancelled {
    background: #f8d7da;
    color: #721c24;
}

.status-paused {
    background: #fff3cd;
    color: #856404;
}

.plan-price {
    text-align: right;
}

.price-amount {
    font-size: 20px;
    font-weight: 700;
    color: #1da1f2;
}

.price-period {
    font-size: 14px;
    color: #666;
}

.price-free {
    font-size: 16px;
    font-weight: 600;
    color: #28a745;
}

.subscription-details,
.plan-details {
    margin-bottom: 16px;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
}

.detail-label {
    font-weight: 600;
    color: #333;
}

.detail-value {
    color: #666;
    text-align: right;
    flex: 1;
    margin-left: 12px;
}

.more-items {
    color: #1da1f2;
    font-size: 12px;
}

.subscription-description,
.plan-description {
    margin-bottom: 16px;
    font-size: 14px;
    color: #666;
}

.subscription-actions,
.plan-actions {
    display: flex;
    gap: 8px;
}

.btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
    text-align: center;
    transition: background-color 0.2s;
}

.btn-primary {
    background: #1da1f2;
    color: white;
}

.btn-primary:hover {
    background: #1991db;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #5a6268;
}

.btn-danger {
    background: #dc3545;
    color: white;
}

.btn-danger:hover {
    background: #c82333;
}

.btn-sm {
    padding: 6px 12px;
    font-size: 12px;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

@media (max-width: 768px) {
    .subscriptions-grid,
    .plans-grid {
        grid-template-columns: 1fr;
    }
    
    .subscription-header,
    .plan-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .subscription-status {
        margin-top: 8px;
    }
    
    .plan-price {
        text-align: left;
        margin-top: 8px;
    }
}
</style>
