<?php
/**
 * Provide a admin area view for managing subscription plans
 *
 * @link       https://yourwebsite.com
 * @since      1.0.0
 *
 * @package    Subscription_System
 * @subpackage Subscription_System/admin/partials
 */

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

// Prevent multiple inclusions of this file
if (defined('SS_PLANS_DISPLAY_INCLUDED')) {
    return;
}
define('SS_PLANS_DISPLAY_INCLUDED', true);

// Retrieve transient messages after redirect
if (isset($_GET['settings-updated']) && get_transient('subscription_messages')) {
    $transient_messages = get_transient('subscription_messages');
    foreach ($transient_messages as $message) {
        add_settings_error('subscription_messages', $message['code'], $message['message'], $message['type']);
    }
    delete_transient('subscription_messages');
}

?>

<div class="subscription-system-admin-page">
    <div class="wrap">
        <h1 class="wp-heading-inline"><?php echo esc_html__('Subscription Plans', 'subscription-system'); ?></h1>
        <a href="#" class="page-title-action" id="show-add-plan"><?php echo esc_html__('Add New Plan', 'subscription-system'); ?></a>
        <hr class="wp-header-end">
        
        <?php settings_errors('subscription_messages'); ?>
        
        <!-- Shortcode Info Box -->
        <div class="notice notice-info is-dismissible">
            <h3><?php echo esc_html__('Subscription Plans Shortcode:', 'subscription-system'); ?></h3>
            <p><?php echo esc_html__('Use the following shortcode to display your subscription plans:', 'subscription-system'); ?></p>
            <code>[pricing_plans]</code> <?php echo esc_html__('– This will use the default layout set in the admin settings.', 'subscription-system'); ?>
            <p><code>[pricing_plans layout="layout1" code="2"]</code> <?php echo esc_html__('– This will display plans in Layout 1 filtered by category ID.', 'subscription-system'); ?></p>
            <p><code>[pricing_plans layout="layout2" code="3"]</code> <?php echo esc_html__('– This will display plans in Layout 2 filtered by category ID.', 'subscription-system'); ?></p>
            <p><?php echo esc_html__('Customize your subscription plans display by adding this shortcode to any post or page.', 'subscription-system'); ?></p>
        </div>
        
        <!-- Add New Plan Form -->
        <div id="add-plan-form" class="postbox" style="display: none; margin: 20px 0;">
            <div class="postbox-header">
                <h2 class="hndle"><?php echo esc_html__('Add New Plan', 'subscription-system'); ?></h2>
            </div>
            <div class="inside">
                <div class="plan-form-container" style="display: flex; flex-wrap: wrap;">
                    <div class="plan-form-fields" style="flex: 1; min-width: 300px; padding-right: 30px;">
                        <form method="post" action="">
                            <?php 
                            wp_nonce_field('subscription_add_plan', 'subscription_nonce');
                            wp_nonce_field('plan_action_nonce', 'nonce');
                            ?>
                            <table class="form-table" role="presentation">
                                <tr>
                                    <th scope="row"><label for="plan_name"><?php echo esc_html__('Plan Name', 'subscription-system'); ?></label></th>
                                    <td><input type="text" name="plan_name" id="plan_name" class="regular-text" required></td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="category_id"><?php echo esc_html__('Category', 'subscription-system'); ?></label></th>
                                    <td>
                                        <select name="category_id" id="category_id" class="regular-text" required>
                                            <option value=""><?php echo esc_html__('Select Category', 'subscription-system'); ?></option>
                                            <?php foreach ($categories as $category) : ?>
                                                <option value="<?php echo esc_attr($category->id); ?>"><?php echo esc_html($category->category_name); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="description"><?php echo esc_html__('Description', 'subscription-system'); ?></label></th>
                                    <td>
                                        <div class="feature-list-container">
                                            <div class="feature-input-group" style="margin-bottom: 10px;">
                                                <input type="text" class="feature-input regular-text" placeholder="<?php echo esc_attr__('Enter feature', 'subscription-system'); ?>">
                                                <button type="button" class="button remove-feature"><?php echo esc_html__('Remove', 'subscription-system'); ?></button>
                                            </div>
                                            <button type="button" class="button add-feature"><?php echo esc_html__('Add Feature', 'subscription-system'); ?></button>
                                            <input type="hidden" name="description" id="description" value="">
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="price"><?php echo esc_html__('Price', 'subscription-system'); ?></label></th>
                                    <td><input type="number" name="price" id="price" class="regular-text" step="0.01" min="0" required>
                                        <p class="description"><?php esc_html_e('Set to 0 for a free plan.', 'subscription-system'); ?></p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="duration"><?php echo esc_html__('Duration', 'subscription-system'); ?></label></th>
                                    <td>
                                        <select name="duration" id="duration" class="regular-text" required>
                                            <option value="1"><?php echo esc_html__('One Day (Testing)', 'subscription-system'); ?></option>
                                            <option value="7"><?php echo esc_html__('Weekly', 'subscription-system'); ?></option>
                                            <option value="30"><?php echo esc_html__('Monthly', 'subscription-system'); ?></option>
                                            <option value="90"><?php echo esc_html__('Quarterly', 'subscription-system'); ?></option>
                                            <option value="180"><?php echo esc_html__('Biannually', 'subscription-system'); ?></option>
                                            <option value="365"><?php echo esc_html__('Annually', 'subscription-system'); ?></option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="status"><?php echo esc_html__('Status', 'subscription-system'); ?></label></th>
                                    <td>
                                        <select name="status" id="status" class="regular-text">
                                            <option value="active"><?php esc_html_e('Active', 'subscription-system'); ?></option>
                                            <option value="inactive"><?php esc_html_e('Inactive', 'subscription-system'); ?></option>
                                        </select>
                                        <p class="description"><?php esc_html_e('Only active plans appear in the subscription modal and pricing pages.', 'subscription-system'); ?></p>
                                    </td>
                                </tr>
                            </table>

                            <h4 style="margin:20px 0 4px;color:#4338ca;">🔔 <?php esc_html_e('Interest Subscription Limits', 'subscription-system'); ?></h4>
                            <p class="description" style="margin-bottom:10px;"><?php esc_html_e('These limits control how many categories and tags a subscriber can pick when using the Subscribe Button & Modal. Set to 0 for unlimited.', 'subscription-system'); ?></p>
                            <table class="form-table" role="presentation" style="margin-top:0;">
                                <tr>
                                    <th scope="row"><label for="max_categories"><?php esc_html_e('Max Categories', 'subscription-system'); ?></label></th>
                                    <td>
                                        <input type="number" name="max_categories" id="max_categories" class="small-text" min="0" value="0">
                                        <p class="description"><?php esc_html_e('0 = unlimited. For free plans, a limit of 2 is recommended.', 'subscription-system'); ?></p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="max_tags"><?php esc_html_e('Max Tags', 'subscription-system'); ?></label></th>
                                    <td>
                                        <input type="number" name="max_tags" id="max_tags" class="small-text" min="0" value="0">
                                        <p class="description"><?php esc_html_e('0 = unlimited. For free plans, a limit of 3 is recommended.', 'subscription-system'); ?></p>
                                    </td>
                                </tr>
                            </table>
                            <input type="hidden" name="plan_features_json" id="plan_features_json" value="">

                            <p class="submit">
                                <input type="submit" name="add_plan" class="button button-primary" value="<?php echo esc_attr__('Save Plan', 'subscription-system'); ?>">
                                <button type="button" class="button" id="cancel-add"><?php echo esc_html__('Cancel', 'subscription-system'); ?></button>
                            </p>
                        </form>
                    </div>
                    
                    <div class="plan-preview" style="flex: 1; min-width: 300px;">
                        <h3><?php echo esc_html__('Plan Preview', 'subscription-system'); ?></h3>
                        <div class="plan-card" style="background-color: #8c9eff; border-radius: 8px; padding: 20px; color: white; text-align: center; max-width: 300px; border: 2px solid #ffd700;">
                            <h2 id="preview-plan-name" style="margin-top: 0; font-size: 24px;">STANDARD</h2>
                            <div class="price-container">
                                <span id="preview-price" style="font-size: 22px; font-weight: bold;">$29.99</span>
                                <span id="preview-duration">/month</span>
                            </div>
                            <hr style="border-color: rgba(255,255,255,0.3); margin: 20px 0;">
                            <ul id="preview-features" style="list-style: none; padding: 0; text-align: left; margin: 20px 0;">
                                <!-- Features will be added here dynamically -->
                            </ul>
                            <button class="order-button" style="background-color: white; color: #5c6bc0; border: none; padding: 10px 20px; border-radius: 5px; font-weight: bold; width: 100%;">Order Now</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Edit Plan Form (hidden by default, shown via JavaScript) -->
        <div id="edit-plan-form" class="postbox" style="display: none; margin: 20px 0;">
            <div class="postbox-header">
                <h2 class="hndle"><?php echo esc_html__('Edit Plan', 'subscription-system'); ?></h2>
            </div>
            <div class="inside">
                <div class="plan-form-container" style="display: flex; flex-wrap: wrap;">
                    <div class="plan-form-fields" style="flex: 1; min-width: 300px; padding-right: 30px;">
                        <form method="post" action="">
                            <?php 
                            wp_nonce_field('subscription_edit_plan', 'subscription_nonce');
                            wp_nonce_field('plan_action_nonce', 'nonce');
                            ?>
                            <input type="hidden" name="plan_id" id="edit_plan_id">
                            <table class="form-table" role="presentation">
                                <tr>
                                    <th scope="row"><label for="edit_plan_name"><?php echo esc_html__('Plan Name', 'subscription-system'); ?></label></th>
                                    <td><input type="text" name="plan_name" id="edit_plan_name" class="regular-text" required></td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="edit_category_id"><?php echo esc_html__('Category', 'subscription-system'); ?></label></th>
                                    <td>
                                        <select name="category_id" id="edit_category_id" class="regular-text" required>
                                            <option value=""><?php echo esc_html__('Select Category', 'subscription-system'); ?></option>
                                            <?php foreach ($categories as $category) : ?>
                                                <option value="<?php echo esc_attr($category->id); ?>"><?php echo esc_html($category->category_name); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="edit_description"><?php echo esc_html__('Description', 'subscription-system'); ?></label></th>
                                    <td>
                                        <div class="feature-list-container" id="edit-feature-container">
                                            <!-- Feature inputs will be added here dynamically -->
                                            <button type="button" class="button add-edit-feature"><?php echo esc_html__('Add Feature', 'subscription-system'); ?></button>
                                            <input type="hidden" name="description" id="edit_description" value="">
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="edit_price"><?php echo esc_html__('Price', 'subscription-system'); ?></label></th>
                                    <td><input type="number" name="price" id="edit_price" class="regular-text" step="0.01" min="0" required>
                                        <p class="description"><?php esc_html_e('Set to 0 for a free plan.', 'subscription-system'); ?></p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="edit_duration"><?php echo esc_html__('Duration', 'subscription-system'); ?></label></th>
                                    <td>
                                        <select name="duration" id="edit_duration" class="regular-text" required>
                                            <option value="1"><?php echo esc_html__('One Day (Testing)', 'subscription-system'); ?></option>
                                            <option value="7"><?php echo esc_html__('Weekly', 'subscription-system'); ?></option>
                                            <option value="30"><?php echo esc_html__('Monthly', 'subscription-system'); ?></option>
                                            <option value="90"><?php echo esc_html__('Quarterly', 'subscription-system'); ?></option>
                                            <option value="180"><?php echo esc_html__('Biannually', 'subscription-system'); ?></option>
                                            <option value="365"><?php echo esc_html__('Annually', 'subscription-system'); ?></option>
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="edit_status"><?php esc_html_e('Status', 'subscription-system'); ?></label></th>
                                    <td>
                                        <select name="status" id="edit_status" class="regular-text">
                                            <option value="active"><?php esc_html_e('Active', 'subscription-system'); ?></option>
                                            <option value="inactive"><?php esc_html_e('Inactive', 'subscription-system'); ?></option>
                                        </select>
                                        <p class="description"><?php esc_html_e('Only active plans appear in the subscription modal and pricing pages.', 'subscription-system'); ?></p>
                                    </td>
                                </tr>
                            </table>

                            <h4 style="margin:20px 0 4px;color:#4338ca;">🔔 <?php esc_html_e('Interest Subscription Limits', 'subscription-system'); ?></h4>
                            <p class="description" style="margin-bottom:10px;"><?php esc_html_e('These limits control how many categories and tags a subscriber can pick in the Subscribe Button & Modal. Set to 0 for unlimited.', 'subscription-system'); ?></p>
                            <table class="form-table" role="presentation" style="margin-top:0;">
                                <tr>
                                    <th scope="row"><label for="edit_max_categories"><?php esc_html_e('Max Categories', 'subscription-system'); ?></label></th>
                                    <td>
                                        <input type="number" name="max_categories" id="edit_max_categories" class="small-text" min="0" value="0">
                                        <p class="description"><?php esc_html_e('0 = unlimited. For free plans, 2 is recommended.', 'subscription-system'); ?></p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="edit_max_tags"><?php esc_html_e('Max Tags', 'subscription-system'); ?></label></th>
                                    <td>
                                        <input type="number" name="max_tags" id="edit_max_tags" class="small-text" min="0" value="0">
                                        <p class="description"><?php esc_html_e('0 = unlimited. For free plans, 3 is recommended.', 'subscription-system'); ?></p>
                                    </td>
                                </tr>
                            </table>
                            <input type="hidden" name="plan_features_json" id="edit_plan_features_json" value="">

                            <p class="submit">
                                <input type="submit" name="edit_plan" class="button button-primary" value="<?php echo esc_attr__('Update Plan', 'subscription-system'); ?>">
                                <button type="button" class="button" id="cancel-edit"><?php echo esc_html__('Cancel', 'subscription-system'); ?></button>
                            </p>
                        </form>
                    </div>
                    
                    <div class="plan-preview" style="flex: 1; min-width: 300px;">
                        <h3><?php echo esc_html__('Plan Preview', 'subscription-system'); ?></h3>
                        <div class="plan-card" style="background-color: #8c9eff; border-radius: 8px; padding: 20px; color: white; text-align: center; max-width: 300px; border: 2px solid #ffd700;">
                            <h2 id="edit-preview-plan-name" style="margin-top: 0; font-size: 24px;">STANDARD</h2>
                            <div class="price-container">
                                <span id="edit-preview-price" style="font-size: 22px; font-weight: bold;">$29.99</span>
                                <span id="edit-preview-duration">/month</span>
                            </div>
                            <hr style="border-color: rgba(255,255,255,0.3); margin: 20px 0;">
                            <ul id="edit-preview-features" style="list-style: none; padding: 0; text-align: left; margin: 20px 0;">
                                <!-- Features will be added here dynamically -->
                            </ul>
                            <button class="order-button" style="background-color: white; color: #5c6bc0; border: none; padding: 10px 20px; border-radius: 5px; font-weight: bold; width: 100%;">Order Now</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Plans List Table -->
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th scope="col" class="manage-column column-name"><?php echo esc_html__('Plan Name', 'subscription-system'); ?></th>
                    <th scope="col" class="manage-column column-description"><?php echo esc_html__('Features', 'subscription-system'); ?></th>
                    <th scope="col" class="manage-column column-price"><?php echo esc_html__('Price', 'subscription-system'); ?></th>
                    <th scope="col" class="manage-column column-duration"><?php echo esc_html__('Duration', 'subscription-system'); ?></th>
                    <th scope="col"><?php echo esc_html__('Interest Limits', 'subscription-system'); ?></th>
                    <th scope="col"><?php echo esc_html__('Status', 'subscription-system'); ?></th>
                    <th scope="col"><?php echo esc_html__('Stripe', 'subscription-system'); ?></th>
                    <th scope="col" class="manage-column column-actions"><?php echo esc_html__('Actions', 'subscription-system'); ?></th>
                </tr>
            </thead>
            <tbody id="the-list">
                <?php if (empty($plans)) : ?>
                    <tr>
                        <td colspan="6" class="colspanchange"><?php echo esc_html__('No plans found.', 'subscription-system'); ?></td>
                    </tr>
                <?php else : ?>
                    <?php foreach ($plans as $plan) : 
                        // Get category name
                        $category_name = '';
                        foreach ($categories as $category) {
                            if ($category->id == $plan->category_id) {
                                $category_name = $category->category_name;
                                break;
                            }
                        }

                        // Parse limits from features JSON
                        $plan_max_cats = 0;
                        $plan_max_tags = 0;
                        if ( ! empty( $plan->features ) ) {
                            $feat_data = json_decode( $plan->features, true );
                            if ( is_array( $feat_data ) ) {
                                $plan_max_cats = isset( $feat_data['max_categories'] ) ? (int) $feat_data['max_categories'] : 0;
                                $plan_max_tags = isset( $feat_data['max_tags'] )       ? (int) $feat_data['max_tags']       : 0;
                            }
                        }

                        $plan_status = ! empty( $plan->status ) ? $plan->status : 'active';
                    ?>
                        <tr>
                            <td class="column-name">
                                <strong><?php echo esc_html($plan->plan_name); ?></strong>
                                <?php if ( $category_name ) : ?>
                                    <br><small style="color:#888;"><?php echo esc_html( $category_name ); ?></small>
                                <?php endif; ?>
                            </td>
                            <td class="column-description">
                                <?php 
                                $desc = $plan->description;
                                if (substr($desc, 0, 1) === '[' && substr($desc, -1) === ']') {
                                    $desc = stripslashes($desc);
                                    $features_arr = json_decode($desc, true);
                                    if (is_array($features_arr) && !empty($features_arr)) {
                                        echo '<ul style="margin: 0; padding-left: 20px;">';
                                        foreach ($features_arr as $feature) {
                                            echo '<li>✓ ' . esc_html($feature) . '</li>';
                                        }
                                        echo '</ul>';
                                    } else {
                                        echo esc_html($desc);
                                    }
                                } else {
                                    echo esc_html($desc);
                                }
                                ?>
                            </td>
                            <td class="column-price">
                                <?php if ( (float) $plan->price <= 0 ) : ?>
                                    <span style="color:#059669;font-weight:600;"><?php esc_html_e( 'Free', 'subscription-system' ); ?></span>
                                <?php else : ?>
                                    $<?php echo esc_html( number_format( $plan->price, 2 ) ); ?>
                                <?php endif; ?>
                            </td>
                            <td class="column-duration">
                                <?php
                                $dur_map = array( 1 => 'Daily', 7 => 'Weekly', 30 => 'Monthly', 90 => 'Quarterly', 180 => '6 Months', 365 => 'Yearly' );
                                echo esc_html( isset( $dur_map[ (int) $plan->duration ] ) ? $dur_map[ (int) $plan->duration ] : $plan->duration . ' days' );
                                ?>
                            </td>
                            <td>
                                <small>
                                    <?php
                                    $cats_label = $plan_max_cats > 0 ? $plan_max_cats : '∞';
                                    $tags_label = $plan_max_tags > 0 ? $plan_max_tags : '∞';
                                    printf( 'Cat: <strong>%s</strong> &nbsp; Tags: <strong>%s</strong>', esc_html( $cats_label ), esc_html( $tags_label ) );
                                    ?>
                                </small>
                            </td>
                            <td>
                                <?php if ( $plan_status === 'active' ) : ?>
                                    <span style="background:#d1fae5;color:#065f46;padding:2px 8px;border-radius:12px;font-size:12px;font-weight:600;"><?php esc_html_e('Active','subscription-system'); ?></span>
                                <?php else : ?>
                                    <span style="background:#fee2e2;color:#991b1b;padding:2px 8px;border-radius:12px;font-size:12px;font-weight:600;"><?php esc_html_e('Inactive','subscription-system'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                $stripe_product_id = $plan->stripe_product_id;
                                $stripe_price_id = $plan->stripe_price_id;
                                $is_connected = !empty($stripe_product_id) && !empty($stripe_price_id);
                                $is_mock = $is_connected && (strpos($stripe_product_id, 'mock_') === 0);
                                if ($is_connected) {
                                    echo '<span class="stripe-status ' . ($is_mock ? 'mock-connected' : 'connected') . '">' .
                                        '<span class="dashicons dashicons-' . ($is_mock ? 'warning' : 'yes-alt') . '"></span> ' .
                                        ($is_mock ? 'Mock' : 'Connected') . '</span>';
                                } else {
                                    echo '<span class="stripe-status not-connected"><span class="dashicons dashicons-no"></span> None</span>';
                                }
                                ?>
                                <br><a href="#" class="sync-with-stripe" data-plan-id="<?php echo $plan->id; ?>" data-nonce="<?php echo wp_create_nonce('sync_plan_with_stripe'); ?>" style="font-size:11px;">Sync</a>
                            </td>
                            <td class="column-actions">
                                <button type="button" class="button button-small edit-plan" 
                                        data-id="<?php echo esc_attr($plan->id); ?>" 
                                        data-name="<?php echo esc_attr($plan->plan_name); ?>"
                                        data-description="<?php echo esc_attr($plan->description); ?>"
                                        data-price="<?php echo esc_attr($plan->price); ?>"
                                        data-duration="<?php echo esc_attr($plan->duration); ?>"
                                        data-category="<?php echo esc_attr($plan->category_id); ?>"
                                        data-status="<?php echo esc_attr($plan_status); ?>"
                                        data-max-categories="<?php echo esc_attr($plan_max_cats); ?>"
                                        data-max-tags="<?php echo esc_attr($plan_max_tags); ?>">
                                    <?php echo esc_html__('Edit', 'subscription-system'); ?>
                                </button>
                                <button type="button" class="button button-small delete-plan" 
                                        data-id="<?php echo esc_attr($plan->id); ?>"
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('delete_plan_' . $plan->id)); ?>">
                                    <?php echo esc_html__('Delete', 'subscription-system'); ?>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Show/hide add plan form
    $('#show-add-plan').on('click', function(e) {
        e.preventDefault();
        $('#add-plan-form').toggle();
        if ($('#add-plan-form').is(':visible')) {
            $('#plan_name').focus();
        }
    });
    
    // Cancel add plan
    $('#cancel-add').on('click', function(e) {
        e.preventDefault();
        $('#add-plan-form').hide();
    });
    
    // Edit plan
    $('.edit-plan').on('click', function() {
        // Hide the add plan form if it's open
        $('#add-plan-form').hide();
        
        var id           = $(this).data('id');
        var name         = $(this).data('name');
        var description  = $(this).data('description');
        var price        = $(this).data('price');
        var duration     = $(this).data('duration');
        var category     = $(this).data('category');
        var status       = $(this).data('status') || 'active';
        var maxCats      = parseInt($(this).data('max-categories'), 10) || 0;
        var maxTags      = parseInt($(this).data('max-tags'), 10) || 0;
        
        $('#edit_plan_id').val(id);
        $('#edit_plan_name').val(name);
        $('#edit_price').val(price);
        $('#edit_duration').val(duration);
        $('#edit_category_id').val(category);
        $('#edit_status').val(status);
        $('#edit_max_categories').val(maxCats);
        $('#edit_max_tags').val(maxTags);
        
        // Clear existing feature inputs
        $('#edit-feature-container .feature-input-group').remove();
        
        // Try to parse description as JSON (for features)
        try {
            var cleanDescription = description.replace(/\\\\/g, '\\').replace(/\\"/g, '"');
            var features = JSON.parse(cleanDescription);
            if (Array.isArray(features)) {
                features.forEach(function(feature) {
                    addEditFeature(feature);
                });
            } else {
                addEditFeature(cleanDescription);
            }
        } catch (e) {
            if (description) {
                addEditFeature(description);
            }
        }
        
        // Update the preview
        updateEditFeaturesList();
        
        $('#edit-plan-form').show();
        $('#edit_plan_name').focus();
        $('html, body').animate({
            scrollTop: $('#edit-plan-form').offset().top - 50
        }, 300);
    });
    
    // Delete plan
    $('.delete-plan').on('click', function() {
        var id = $(this).data('id');
        var nonce = $(this).data('nonce');
        
        if (confirm('<?php echo esc_js(__('Are you sure you want to delete this plan?', 'subscription-system')); ?>')) {
            window.location.href = '<?php echo admin_url('edit.php?post_type=subscription&page=subscription-plans&action=delete&plan_id='); ?>' + id + '&_wpnonce=' + nonce;
        }
    });
    
    // Cancel edit
    $('#cancel-edit').on('click', function(e) {
        e.preventDefault();
        $('#edit-plan-form').hide();
    });
    
    // Feature list management
    $('.add-feature').on('click', function() {
        var newFeature = $('<div class="feature-input-group" style="margin-bottom: 10px;">' +
            '<input type="text" class="feature-input regular-text" placeholder="<?php echo esc_attr__('Enter feature', 'subscription-system'); ?>">' +
            '<button type="button" class="button remove-feature"><?php echo esc_html__('Remove', 'subscription-system'); ?></button>' +
            '</div>');
        $(this).before(newFeature);
    });
    
    $(document).on('click', '.remove-feature', function() {
        $(this).parent().remove();
        updateFeaturesList();
    });
    
    // Duration change
    $('#duration').on('change', function() {
        var selectedOption = $(this).find('option:selected');
        var durationValue = $(this).val();
        
        // Update preview text based on selection
        if (durationValue == '1') {
            $('#preview-duration').text('/day');
        } else if (durationValue == '7') {
            $('#preview-duration').text('/week');
        } else if (durationValue == '30') {
            $('#preview-duration').text('/month');
        } else if (durationValue == '90') {
            $('#preview-duration').text('/quarter');
        } else if (durationValue == '180') {
            $('#preview-duration').text('/biannual');
        } else if (durationValue == '365') {
            $('#preview-duration').text('/year');
        }
    });
    
    // Initialize duration preview on page load
    $('#duration').trigger('change');
    
    // Live preview updates
    $('#plan_name').on('input', function() {
        $('#preview-plan-name').text($(this).val() || 'STANDARD');
    });
    
    $('#price').on('input', function() {
        var price = parseFloat($(this).val()) || 29.99;
        $('#preview-price').text('$' + price.toFixed(2));
    });
    
    $(document).on('input', '.feature-input', function() {
        updateFeaturesList();
    });
    
    function updateFeaturesList() {
        var features = [];
        $('.feature-input').each(function() {
            var featureText = $(this).val().trim();
            if (featureText) {
                features.push(featureText);
            }
        });
        
        // Update hidden description field with JSON
        $('#description').val(JSON.stringify(features));
        
        // Update preview
        var $previewList = $('#preview-features');
        $previewList.empty();
        
        if (features.length === 0) {
            // Add placeholder lines
            $previewList.append('<li style="height: 1px; background-color: rgba(255,255,255,0.5); margin: 10px 0;"></li>');
            $previewList.append('<li style="height: 1px; background-color: rgba(255,255,255,0.5); margin: 10px 0;"></li>');
        } else {
            features.forEach(function(feature) {
                $previewList.append('<li style="margin-bottom: 8px;">✓ ' + feature + '</li>');
            });
        }
    }
    
    // Initialize preview
    updateFeaturesList();
    
    // Add feature in edit form
    $('.add-edit-feature').on('click', function() {
        var newFeature = $('<div class="feature-input-group" style="margin-bottom: 10px;">' +
            '<input type="text" class="edit-feature-input regular-text" placeholder="<?php echo esc_attr__('Enter feature', 'subscription-system'); ?>">' +
            '<button type="button" class="button remove-edit-feature"><?php echo esc_html__('Remove', 'subscription-system'); ?></button>' +
            '</div>');
        $(this).before(newFeature);
        updateEditFeaturesList();
    });
    
    // Remove feature in edit form
    $(document).on('click', '.remove-edit-feature', function() {
        $(this).parent().remove();
        updateEditFeaturesList();
    });
    
    // Live updates for edit features
    $(document).on('input', '.edit-feature-input', function() {
        updateEditFeaturesList();
    });
    
    // Function to update edit features list and preview
    function updateEditFeaturesList() {
        var features = [];
        $('.edit-feature-input').each(function() {
            var featureText = $(this).val().trim();
            if (featureText) {
                features.push(featureText);
            }
        });
        
        // Update hidden description field with JSON
        $('#edit_description').val(JSON.stringify(features));
        
        // Update preview
        var $previewList = $('#edit-preview-features');
        $previewList.empty();
        
        if (features.length === 0) {
            // Add placeholder lines
            $previewList.append('<li style="height: 1px; background-color: rgba(255,255,255,0.5); margin: 10px 0;"></li>');
            $previewList.append('<li style="height: 1px; background-color: rgba(255,255,255,0.5); margin: 10px 0;"></li>');
        } else {
            features.forEach(function(feature) {
                $previewList.append('<li style="margin-bottom: 8px;">✓ ' + feature + '</li>');
            });
        }
    }
    
    // Update edit plan preview when fields change
    $('#edit_plan_name').on('input', function() {
        $('#edit-preview-plan-name').text($(this).val() || 'STANDARD');
    });
    
    $('#edit_price').on('input', function() {
        var price = parseFloat($(this).val()) || 29.99;
        $('#edit-preview-price').text('$' + price.toFixed(2));
    });
    
    $('#edit_duration').on('change', function() {
        var durationValue = $(this).val();
        if (durationValue == '1') {
            $('#edit-preview-duration').text('/day');
        } else if (durationValue == '7') {
            $('#edit-preview-duration').text('/week');
        } else if (durationValue == '30') {
            $('#edit-preview-duration').text('/month');
        } else if (durationValue == '90') {
            $('#edit-preview-duration').text('/quarter');
        } else if (durationValue == '180') {
            $('#edit-preview-duration').text('/biannual');
        } else if (durationValue == '365') {
            $('#edit-preview-duration').text('/year');
        }
    });
    
    // Function to add a feature input to the edit form
    function addEditFeature(value) {
        var newFeature = $('<div class="feature-input-group" style="margin-bottom: 10px;">' +
            '<input type="text" class="edit-feature-input regular-text" value="' + (value || '') + '" placeholder="<?php echo esc_attr__('Enter feature', 'subscription-system'); ?>">' +
            '<button type="button" class="button remove-edit-feature"><?php echo esc_html__('Remove', 'subscription-system'); ?></button>' +
            '</div>');
        $('.add-edit-feature').before(newFeature);
    }
    
    // Add this to your existing JavaScript
    $(document).on('click', '.view-features', function(e) {
        e.preventDefault();
        
        var features = $(this).data('features');
        var featuresList = '';
        
        if (Array.isArray(features) && features.length > 0) {
            featuresList = '<ul style="margin: 0; padding-left: 20px;">';
            features.forEach(function(feature) {
                featuresList += '<li>' + feature + '</li>';
            });
            featuresList += '</ul>';
        } else {
            featuresList = '<p>' + features + '</p>';
        }
        
        // Create and show modal
        var $modal = $('<div class="features-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 9999; display: flex; align-items: center; justify-content: center;">' +
            '<div class="modal-content" style="background: white; padding: 20px; border-radius: 5px; max-width: 500px; max-height: 80%; overflow-y: auto;">' +
            '<h3>' + <?php echo json_encode(__('Plan Features', 'subscription-system')); ?> + '</h3>' +
            featuresList +
            '<p style="text-align: right;"><button class="button close-modal">' + <?php echo json_encode(__('Close', 'subscription-system')); ?> + '</button></p>' +
            '</div>' +
            '</div>');
        
        $('body').append($modal);
        
        // Close modal when clicking close button or outside the modal
        $('.close-modal, .features-modal').on('click', function(e) {
            if (e.target === this) {
                $('.features-modal').remove();
            }
        });
    });
    
    // ── Build features JSON before submitting Add form ──────────────────────
    $('#add-plan-form form').on('submit', function() {
        var limits = {
            max_categories: parseInt($('#max_categories').val(), 10) || 0,
            max_tags:       parseInt($('#max_tags').val(), 10) || 0
        };
        $('#plan_features_json').val(JSON.stringify(limits));
    });

    // ── Build features JSON before submitting Edit form ──────────────────────
    $('#edit-plan-form form').on('submit', function() {
        var limits = {
            max_categories: parseInt($('#edit_max_categories').val(), 10) || 0,
            max_tags:       parseInt($('#edit_max_tags').val(), 10) || 0
        };
        $('#edit_plan_features_json').val(JSON.stringify(limits));
    });

    // Fix for the category column display
    $('.sync-with-stripe').on('click', function(e) {
        e.preventDefault();
        var planId = $(this).data('plan-id');
        var nonce = $(this).data('nonce');
        
        // Show loading indicator
        var $statusCell = $(this).closest('td');
        var originalContent = $statusCell.html();
        $statusCell.html('<span class="spinner is-active"></span> Syncing...');
        
        // AJAX call to sync with Stripe
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sync_plan_with_stripe',
                plan_id: planId,
                nonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    var isMock = response.data.mock_mode;
                    
                    var statusHtml = '<span class="stripe-status ' + (isMock ? 'mock-connected' : 'connected') + '">' +
                        '<span class="dashicons dashicons-' + (isMock ? 'warning' : 'yes-alt') + '"></span> ' +
                        (isMock ? 'Mock Connected' : 'Connected') + '</span>';
                    
                    if (isMock) {
                        statusHtml += '<br><small>Using test data - not connected to Stripe</small>';
                    } else {
                        statusHtml += '<br><small>Product ID: ' + response.data.product_id.substring(0, 8) + '...</small>';
                        statusHtml += '<br><small>Price ID: ' + response.data.price_id.substring(0, 8) + '...</small>';
                    }
                    
                    statusHtml += '<br><a href="#" class="sync-with-stripe" data-plan-id="' + planId + '" data-nonce="' + nonce + '">Sync with Stripe</a>';
                    
                    $statusCell.html(statusHtml);
                    
                    // Show success message
                    $('h1.wp-heading-inline').after('<div class="notice notice-' + (isMock ? 'warning' : 'success') + ' is-dismissible"><p>' + response.data.message + '</p></div>');
                    
                    // Initialize dismissible notices
                    $('.notice.is-dismissible').each(function() {
                        var $notice = $(this);
                        if (!$notice.find('.notice-dismiss').length) {
                            $notice.append('<button type="button" class="notice-dismiss"></button>');
                            $notice.on('click', '.notice-dismiss', function() {
                                $notice.fadeOut(300, function() { $notice.remove(); });
                            });
                        }
                    });
                } else {
                    $statusCell.html(originalContent);
                    alert('Error: ' + response.data.message);
                }
            },
            error: function() {
                $statusCell.html(originalContent);
                alert('An error occurred while syncing with Stripe.');
            }
        });
    });
});
</script> 