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

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

// Enqueue the layout-specific CSS
wp_enqueue_style('subscription-pricing-layout3', plugin_dir_url(dirname(__FILE__)) . 'css/pricing-layout3.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 layout3 <?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-layout3">
            <?php 
            $featured_index = ceil(count($plans) / 2) - 1; // Middle plan is featured
            foreach ($plans as $index => $plan) : 
                $is_featured = ($index === $featured_index) ? 'ss-featured' : '';
            ?>
                <div class="ss-pricing-plan <?php echo esc_attr($is_featured); ?>">
                    <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)) {
                                try {
                                    // 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 without dashicons
                                    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>';
                                    }
                                } catch (Exception $e) {
                                    // Fallback if any error occurs
                                    echo '<li>' . esc_html($plan->description) . '</li>';
                                }
                            }
                            ?>
                        </ul>
                    </div>
                    <div class="ss-plan-footer">
                        <button class="ss-pricing-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.layout3 {
    background: transparent !important;
    padding: 40px 20px;
}

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

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

.ss-layout3 .ss-pricing-plan {
    flex: 1;
    max-width: 350px;
    min-width: 280px;
    background-color: transparent !important;
    border-radius: 15px;
    border: 1px solid #e5e5e5;
    transition: all 0.3s ease;
    box-shadow: 0 10px 25px rgba(0,0,0,0.08);
    overflow: hidden;
    position: relative;
}

.ss-layout3 .ss-pricing-plan:hover {
    transform: translateY(-10px);
    box-shadow: 0 20px 40px rgba(0,0,0,0.12);
}

.ss-layout3 .ss-pricing-plan.ss-featured {
    background-color: transparent !important;
    border: 2px solid #4CAF50;
    box-shadow: 0 15px 30px rgba(76, 175, 80, 0.25);
    position: relative;
}

.ss-layout3 .ss-pricing-plan.ss-featured::before {
    content: 'BEST VALUE';
    position: absolute;
    top: 15px;
    right: -35px;
    background-color: #FF9800;
    color: white;
    padding: 5px 40px;
    font-size: 12px;
    transform: rotate(45deg);
    font-weight: bold;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    z-index: 1;
}

.ss-layout3 .ss-plan-header {
    padding: 30px 20px;
    position: relative;
    overflow: hidden;
    border-bottom: none;
    text-align: center;
}

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

.ss-layout3 .ss-featured .ss-plan-header h3 {
    color: #4CAF50;
}

.ss-layout3 .ss-price {
    font-size: 34px;
    font-weight: bold;
    margin-top: 10px;
    color: #4CAF50;
}

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

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

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

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

.ss-layout3 .ss-plan-features li:before {
    content: "✓";
    color: #4CAF50;
    margin-right: 15px;
    font-weight: bold;
}

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

.ss-layout3 .ss-pricing-button {
    display: inline-block;
    padding: 14px 35px;
    background-color: #4CAF50;
    color: white;
    border-radius: 30px;
    text-decoration: none;
    font-weight: 600;
    font-size: 15px;
    letter-spacing: 0.5px;
    text-transform: uppercase;
    transition: all 0.3s ease;
    box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
    border: none;
    cursor: pointer;
}

.ss-layout3 .ss-featured .ss-pricing-button {
    background-color: #4CAF50;
    color: white;
}

.ss-layout3 .ss-pricing-button:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(76, 175, 80, 0.4);
    background-color: #3d8b40;
}

/* Responsive styles for Layout 3 */
@media screen and (max-width: 991px) {
    .ss-layout3 {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
    }
    
    .ss-layout3 .ss-pricing-plan {
        flex: 0 0 calc(50% - 20px);
        max-width: calc(50% - 20px);
        margin: 0;
    }
    
    .ss-layout3 .ss-pricing-plan.ss-featured {
        transform: none;
    }
}

@media screen and (max-width: 767px) {
    .ss-layout3 {
        flex-direction: column;
    }
    
    .ss-layout3 .ss-pricing-plan {
        flex: 0 0 100%;
        max-width: 100%;
        margin-bottom: 20px;
    }
    
    .ss-layout3 .ss-pricing-plan.ss-featured {
        transform: scale(1);
        order: -1; /* Move featured plan to the top on mobile */
        border: 2px solid #4CAF50;
    }
    
    .ss-layout3 .ss-plan-header h3 {
        font-size: 1.5rem;
    }
    
    .ss-layout3 .ss-price {
        font-size: 1.8rem;
    }
    
    .ss-layout3 .ss-price span {
        font-size: 0.9rem;
    }
    
    .ss-layout3 .ss-plan-features ul li {
        font-size: 0.9rem;
        padding: 8px 5px;
    }
    
    .ss-layout3 .ss-pricing-button {
        padding: 10px 15px;
    }
}
</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('<?php esc_html_e('Unknown error occurred', 'subscription-system'); ?>');
            }
        })
        .then(result => {
            if (result.error) {
                throw new Error(result.error.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('<?php esc_html_e('Error connecting to server. Please try again.', 'subscription-system'); ?>');
            button.prop('disabled', false).removeClass('loading').text('<?php _e('Subscribe Now', 'subscription-system'); ?>');
        });
    }
});
</script> 