<?php
/**
 * Template for displaying pricing plans (Layout 2)
 *
 * @package    Subscription_System
 */

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

// Enqueue the layout-specific CSS
wp_enqueue_style('subscription-pricing-layout2', plugin_dir_url(dirname(__FILE__)) . 'css/pricing-layout2.css', array(), '1.0.0', 'all');

// Add responsive viewport meta tag if not already present
 

// Enqueue Stripe JS
wp_enqueue_script('stripe-js', 'https://js.stripe.com/v3/', array(), null, true);

// Enqueue our custom JS
wp_enqueue_script('subscription-pricing-js', plugin_dir_url(dirname(__FILE__)) . 'js/subscription-pricing.js', array('jquery', 'stripe-js'), '1.0.0', true);

// Localize script with necessary data
wp_localize_script('subscription-pricing-js', 'subscription_data', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'stripe_publishable_key' => get_option('subscription_stripe_publishable_key'),
    'stripe_secret_key' => get_option('subscription_stripe_secret_key'),
    'is_user_logged_in' => is_user_logged_in(),
    'register_page_url' => get_permalink(get_option('register_page')),
    'account_page_url' => get_permalink(get_option('account_page')),
    'thank_you_page_url' => get_permalink(get_option('thank_you_page')),
    'pricing_plans_page_url' => get_permalink(get_option('pricing_plans_page')),
    'nonce' => wp_create_nonce('subscription_check_nonce'),
    'subscribe_now_text' => esc_html__('Subscribe Now', 'subscription-system')
));
?>

<div class="subscription-pricing-plans layout2 <?php echo esc_attr($orientation_class); ?> columns-<?php echo esc_attr($atts['columns']); ?> ss-responsive">
    <?php if (empty($plans)) : ?>
        <p class="no-plans"><?php esc_html_e('No subscription plans available.', 'subscription-system'); ?></p>
    <?php else : ?>
        <div class="ss-pricing-container ss-layout2">
            <?php foreach ($plans as $index => $plan) : ?>
                <div class="ss-pricing-plan">
                    <div class="ss-plan-header">
                        <h3><?php echo esc_html($plan->plan_name); ?></h3>
                        <div class="ss-price">$<?php echo esc_html(number_format($plan->price, 2)); ?><span>/month</span></div>
                    </div>
                    <div class="ss-plan-features">
                        <ul>
                            <?php 
                            // If plan has features, display them
                            if (!empty($plan->description)) {
                                // Clean up the description string - remove escaped quotes
                                $clean_description = str_replace('\"', '"', $plan->description);
                                
                                // Try to decode the JSON
                                $features = json_decode($clean_description);
                                
                                // If JSON decode failed, try other methods
                                if ($features === null) {
                                    // Try to unserialize
                                    $features = maybe_unserialize($clean_description);
                                    
                                    // If still not an array, use as single item
                                    if (!is_array($features)) {
                                        $features = array($clean_description);
                                    }
                                }
                                
                                // Display features
                                if (is_array($features) || is_object($features)) {
                                    foreach ($features as $feature) {
                                        echo '<li>' . esc_html($feature) . '</li>';
                                    }
                                } else {
                                    echo '<li>' . esc_html($clean_description) . '</li>';
                                }
                            }
                            ?>
                        </ul>
                    </div>
                    <div class="ss-plan-footer">
                        <button class="ss-button subscribe-button" data-plan-id="<?php echo esc_attr($plan->id); ?>">
                            <?php esc_html_e('Subscribe Now', 'subscription-system'); ?>
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<style>
/* Override styles to match admin preview */
.subscription-pricing-plans.layout2 {
    background: transparent !important;
    padding: 40px 20px;
}

.ss-layout2 .ss-pricing-container {
    display: flex;
    justify-content: center;
    width: 100%;
    padding: 20px 0;
    background: transparent !important;
}

.ss-layout2 .ss-pricing-plans {
    display: flex;
    justify-content: center;
    max-width: 1200px;
    width: 100%;
    margin: 0 auto;
    gap: 20px;
    flex-wrap: wrap;
}

.ss-layout2 .ss-pricing-plan {
    flex: 1;
    max-width: 350px;
    min-width: 280px;
    background-color: transparent !important;
    border: 1px solid #e8e8e8;
    box-shadow: 0 8px 20px rgba(0,0,0,0.06);
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;
    position: relative;
}

.ss-layout2 .ss-pricing-plan:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 30px rgba(0,0,0,0.1);
}

.ss-layout2 .ss-pricing-plan.ss-featured {
    background-color: transparent !important;
    border: 2px solid #6a11cb;
    transform: scale(1.05);
    z-index: 1;
    box-shadow: 0 15px 30px rgba(106, 17, 203, 0.2);
    position: relative;
}

.ss-layout2 .ss-pricing-plan.ss-featured::before {
    content: 'POPULAR';
    position: absolute;
    top: 15px;
    right: 15px;
    background-color: #6a11cb;
    color: white;
    padding: 5px 10px;
    font-size: 12px;
    border-radius: 20px;
    font-weight: bold;
}

.ss-layout2 .ss-plan-header {
    padding: 30px 20px;
    text-align: center;
    border-bottom: 1px solid #f0f0f0;
    position: relative;
}

.ss-layout2 .ss-plan-header h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 1px;
    color: #333;
}

.ss-layout2 .ss-featured .ss-plan-header h3 {
    color: #6a11cb;
}

.ss-layout2 .ss-price {
    font-size: 36px;
    font-weight: bold;
    margin-top: 10px;
    color: #6a11cb;
}

.ss-layout2 .ss-price span {
    font-size: 16px;
    font-weight: normal;
    opacity: 0.8;
}

.ss-layout2 .ss-plan-features {
    padding: 0;
}

.ss-layout2 .ss-plan-features ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.ss-layout2 .ss-plan-features li {
    padding: 15px 20px;
    border-bottom: 1px solid #f0f0f0;
    text-align: center;
    font-size: 14px;
    color: #555;
}

.ss-layout2 .ss-plan-footer {
    padding: 30px;
    text-align: center;
    background-color: transparent;
}

.ss-layout2 .ss-button {
    display: inline-block;
    padding: 12px 30px;
    border-radius: 50px;
    text-decoration: none;
    font-weight: 600;
    transition: all 0.3s ease;
    font-size: 15px;
    letter-spacing: 0.5px;
    text-transform: uppercase;
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
    color: white;
    border: none;
    box-shadow: 0 5px 15px rgba(106, 17, 203, 0.3);
}

.ss-layout2 .ss-featured .ss-button {
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
    color: white;
}

.ss-layout2 .ss-button:hover {
    opacity: 0.95;
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(106, 17, 203, 0.4);
}

/* Improve responsive styles */
@media screen and (max-width: 991px) {
    .ss-layout2 {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
    }
    
    .ss-layout2 .ss-pricing-plan {
        flex: 0 0 calc(50% - 20px);
        max-width: calc(50% - 20px);
        margin: 0;
    }
    
    .ss-layout2 .ss-pricing-plan.ss-featured {
        transform: none;
    }
    
    /* Improve button sizing on tablets */
    .ss-layout2 .ss-button {
        width: 100%;
        padding: 12px 10px;
    }
}

@media screen and (max-width: 767px) {
    .ss-layout2 {
        flex-direction: column;
    }
    
    .ss-layout2 .ss-pricing-plan {
        flex: 0 0 100%;
        max-width: 100%;
        margin-bottom: 20px;
    }
    
    .ss-layout2 .ss-plan-header h3 {
        font-size: 1.5rem;
    }
    
    .ss-layout2 .ss-price {
        font-size: 1.8rem;
    }
    
    .ss-layout2 .ss-price span {
        font-size: 0.9rem;
    }
    
    .ss-layout2 .ss-plan-features ul li {
        font-size: 0.9rem;
        padding: 8px 5px;
    }
    
    /* Improve touch target size for mobile */
    .ss-layout2 .ss-button {
        padding: 14px 20px;
        font-size: 1rem;
    }
    
    /* Add spacing between elements */
    .ss-layout2 .ss-plan-header, 
    .ss-layout2 .ss-plan-features {
        margin-bottom: 15px;
    }
}

/* Extra small devices */
@media screen and (max-width: 480px) {
    .ss-layout2 .ss-pricing-plan {
        padding: 15px;
    }
    
    .ss-layout2 .ss-plan-header h3 {
        font-size: 1.3rem;
    }
    
    .ss-layout2 .ss-price {
        font-size: 1.6rem;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    // Initialize Stripe
    var stripe = Stripe('<?php echo esc_js(get_option('subscription_stripe_publishable_key')); ?>');
    
    $('.subscribe-button').on('click', function() {
        var planId = $(this).data('plan-id');
        var button = $(this);
        var planName = button.closest('.ss-pricing-plan').find('h3').text();
        var planPrice = button.closest('.ss-pricing-plan').find('.ss-price').text().replace(/[^0-9.]/g, '');
        
        // Check if user is logged in
        <?php if (!is_user_logged_in()): ?>
            // User is not logged in, redirect to register page
            window.location.href = '<?php echo esc_js(get_permalink(get_option('register_page'))); ?>?plan_id=' + planId;
            return;
        <?php else: ?>
            // Check if user already has this subscription
            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                type: 'POST',
                data: {
                    action: 'check_user_subscription',
                    plan_id: planId,
                    nonce: '<?php echo esc_attr(wp_create_nonce('subscription_check_nonce')); ?>'
                },
                success: function(response) {
                    if (response.success && response.data.has_subscription) {
                        // User already has this subscription, redirect to account page
                        window.location.href = '<?php echo esc_js(get_permalink(get_option('account_page'))); ?>?tab=subscriptions';
                    } else {
                        // User is logged in but doesn't have this subscription, proceed with payment
                        proceedWithPayment(planId, button, planName, planPrice);
                    }
                },
                error: function() {
                    // On error, proceed with payment flow
                    proceedWithPayment(planId, button, planName, planPrice);
                }
            });
        <?php endif; ?>
    });
    
    function proceedWithPayment(planId, button, planName, planPrice) {
        // Disable button and show loading state
        button.prop('disabled', true).addClass('loading').text('Processing...');
        
        // Create checkout session directly with Stripe API
        fetch('https://api.stripe.com/v1/checkout/sessions', {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer <?php echo esc_js(get_option('subscription_stripe_secret_key')); ?>',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                'payment_method_types[]': 'card',
                'line_items[0][price_data][currency]': 'usd',
                'line_items[0][price_data][product_data][name]': planName,
                'line_items[0][price_data][unit_amount]': Math.round(planPrice * 100),
                'line_items[0][price_data][recurring][interval]': 'month',
                'line_items[0][quantity]': 1,
                'mode': 'subscription',
                'success_url': '<?php echo esc_js(get_permalink(get_option('thank_you_page'))); ?>?session_id={CHECKOUT_SESSION_ID}',
                'cancel_url': '<?php echo esc_js(get_permalink(get_option('pricing_plans_page'))); ?>',
                'client_reference_id': planId,
                'metadata[plan_id]': planId
            })
        })
        .then(response => response.json())
        .then(session => {
            if (session.id) {
                return stripe.redirectToCheckout({ sessionId: session.id });
            } else if (session.error) {
                throw new Error(session.error.message);
            } else {
                throw new Error('Unknown error occurred');
            }
        })
        .then(result => {
            if (result.error) {
                throw new Error(result.error.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error: ' + error.message);
            button.prop('disabled', false).removeClass('loading').text('<?php esc_html_e('Subscribe Now', 'subscription-system'); ?>');
        });
    }
});
</script> 