<?php
/**
 * Content Plans admin display
 *
 * @link       https://mediahubster.in
 * @since      1.0.4
 *
 * @package    Subscription_System
 * @subpackage Subscription_System/admin/partials
 */

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

$content_manager = new Subs_Sys_Content_Manager();

// 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');
}

// Check if content tables exist
$tables_exist = Subs_Sys_DB_Updater::content_tables_exist();
$current_db_version = Subs_Sys_DB_Updater::get_current_version();

// Get current action
$action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
$plan_id = isset($_GET['plan_id']) ? intval($_GET['plan_id']) : 0;

// Get plan data for editing
$editing_plan = null;
if ($action === 'edit' && $plan_id > 0) {
    $editing_plan = $content_manager->get_content_plan($plan_id);
}

// Get all content plans
$content_plans = $content_manager->get_content_plans();

// Get content type options
$content_types = $content_manager->get_content_type_options();
$notification_frequencies = $content_manager->get_notification_frequency_options();
?>

<div class="wrap">
    <h1 class="wp-heading-inline"><?php esc_html_e('Content Subscription Plans', 'subscription-system'); ?></h1>
    
    <?php if ($action !== 'edit' && $action !== 'add'): ?>
        <a href="<?php echo esc_url(admin_url('admin.php?page=subscription-content-plans&action=add')); ?>" class="page-title-action">
            <?php esc_html_e('Add New Content Plan', 'subscription-system'); ?>
        </a>
    <?php endif; ?>
    
    <hr class="wp-header-end">

    <?php settings_errors('subscription_messages'); ?>

    <?php if (!$tables_exist): ?>
        <div class="notice notice-warning">
            <p>
                <strong><?php esc_html_e('Database Update Required', 'subscription-system'); ?></strong><br>
                <?php esc_html_e('The content subscription tables are not yet created. Please update the database to enable content subscription features.', 'subscription-system'); ?>
                <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=subscription-content-plans&subs_sys_action=update_database'), 'subs_sys_update_db')); ?>" class="button button-primary" style="margin-left: 10px;">
                    <?php esc_html_e('Update Database Now', 'subscription-system'); ?>
                </a>
            </p>
        </div>
    <?php endif; ?>

    <?php if ($action === 'add' || $action === 'edit'): ?>
        <!-- Add/Edit Content Plan Form -->
        <div class="content-plan-form-container">
            <h2><?php echo $action === 'edit' ? esc_html__('Edit Content Plan', 'subscription-system') : esc_html__('Add New Content Plan', 'subscription-system'); ?></h2>
            
            <form method="post" action="">
                <?php wp_nonce_field('content_plan_action', 'content_plan_nonce'); ?>
                <?php if ($editing_plan): ?>
                    <input type="hidden" name="plan_id" value="<?php echo esc_attr($editing_plan->id); ?>">
                <?php endif; ?>

                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="plan_name"><?php esc_html_e('Plan Name', 'subscription-system'); ?> <span class="required">*</span></label>
                        </th>
                        <td>
                            <input type="text" id="plan_name" name="plan_name" class="regular-text" 
                                   value="<?php echo $editing_plan ? esc_attr($editing_plan->plan_name) : ''; ?>" required>
                            <p class="description"><?php esc_html_e('Enter a descriptive name for this content subscription plan.', 'subscription-system'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="description"><?php esc_html_e('Description', 'subscription-system'); ?></label>
                        </th>
                        <td>
                            <textarea id="description" name="description" class="large-text" rows="4"><?php echo $editing_plan ? esc_textarea($editing_plan->description) : ''; ?></textarea>
                            <p class="description"><?php esc_html_e('Optional description of what this plan includes.', 'subscription-system'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="price"><?php esc_html_e('Price', 'subscription-system'); ?></label>
                        </th>
                        <td>
                            <input type="number" id="price" name="price" class="small-text" step="0.01" min="0"
                                   value="<?php echo $editing_plan ? esc_attr($editing_plan->price) : '0.00'; ?>">
                            <p class="description"><?php esc_html_e('Subscription price (0 for free).', 'subscription-system'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="duration"><?php esc_html_e('Duration', 'subscription-system'); ?></label>
                        </th>
                        <td>
                            <input type="number" id="duration" name="duration" class="small-text" min="1"
                                   value="<?php echo $editing_plan ? esc_attr($editing_plan->duration) : '30'; ?>">
                            <select name="duration_unit">
                                <option value="days" <?php selected($editing_plan ? $editing_plan->duration_unit : 'days', 'days'); ?>><?php esc_html_e('Days', 'subscription-system'); ?></option>
                                <option value="months" <?php selected($editing_plan ? $editing_plan->duration_unit : 'days', 'months'); ?>><?php esc_html_e('Months', 'subscription-system'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('How long the subscription lasts.', 'subscription-system'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="content_type"><?php esc_html_e('Content Type', 'subscription-system'); ?> <span class="required">*</span></label>
                        </th>
                        <td>
                            <select id="content_type" name="content_type" required onchange="updateContentOptions()">
                                <option value=""><?php esc_html_e('Select Content Type', 'subscription-system'); ?></option>
                                <?php foreach ($content_types as $type => $label): ?>
                                    <option value="<?php echo esc_attr($type); ?>" <?php selected($editing_plan ? $editing_plan->content_type : '', $type); ?>>
                                        <?php echo esc_html($label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description"><?php esc_html_e('What type of content this plan covers.', 'subscription-system'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="content_ids"><?php esc_html_e('Content Selection', 'subscription-system'); ?> <span class="required">*</span></label>
                        </th>
                        <td>
                            <div id="content_selection_container">
                                <!-- Dynamic content will be loaded here -->
                            </div>
                            <p class="description"><?php esc_html_e('Select the specific content items for this plan.', 'subscription-system'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="notification_frequency"><?php esc_html_e('Notification Frequency', 'subscription-system'); ?></label>
                        </th>
                        <td>
                            <select id="notification_frequency" name="notification_frequency">
                                <?php foreach ($notification_frequencies as $freq => $label): ?>
                                    <option value="<?php echo esc_attr($freq); ?>" <?php selected($editing_plan ? $editing_plan->notification_frequency : 'immediate', $freq); ?>>
                                        <?php echo esc_html($label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description"><?php esc_html_e('How often subscribers receive notifications.', 'subscription-system'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row">
                            <label for="status"><?php esc_html_e('Status', 'subscription-system'); ?></label>
                        </th>
                        <td>
                            <select id="status" name="status">
                                <option value="active" <?php selected($editing_plan ? $editing_plan->status : 'active', 'active'); ?>><?php esc_html_e('Active', 'subscription-system'); ?></option>
                                <option value="inactive" <?php selected($editing_plan ? $editing_plan->status : 'active', 'inactive'); ?>><?php esc_html_e('Inactive', 'subscription-system'); ?></option>
                            </select>
                        </td>
                    </tr>
                </table>

                <p class="submit">
                    <input type="submit" name="submit_content_plan" class="button button-primary" 
                           value="<?php echo $action === 'edit' ? esc_attr__('Update Content Plan', 'subscription-system') : esc_attr__('Create Content Plan', 'subscription-system'); ?>">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=subscription-content-plans')); ?>" class="button button-secondary">
                        <?php esc_html_e('Cancel', 'subscription-system'); ?>
                    </a>
                </p>
            </form>
        </div>

        <script type="text/javascript">
        // Ensure ajaxurl is defined
        if (typeof ajaxurl === 'undefined') {
            var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        }

        function updateContentOptions() {
            const contentType = document.getElementById('content_type').value;
            const container = document.getElementById('content_selection_container');
            
            if (!contentType) {
                container.innerHTML = '';
                return;
            }

            // Show loading
            container.innerHTML = '<p><?php esc_html_e('Loading...', 'subscription-system'); ?></p>';

            // AJAX call to get content options
            const data = new FormData();
            data.append('action', 'get_content_options');
            data.append('content_type', contentType);
            data.append('nonce', '<?php echo wp_create_nonce('get_content_options'); ?>');
            data.append('plan_id', '<?php echo intval($editing_plan ? $editing_plan->id : 0); ?>');
            <?php if ($editing_plan): ?>
            data.append('selected_ids', '<?php echo wp_json_encode($editing_plan->content_ids); ?>');
            <?php endif; ?>

            fetch(ajaxurl, {
                method: 'POST',
                body: data
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    container.innerHTML = result.data;
                } else {
                    container.innerHTML = '<p class="error">Error: ' + (result.data.message || '<?php esc_html_e('Error loading content options.', 'subscription-system'); ?>') + '</p>';
                }
            })
            .catch(error => {
                container.innerHTML = '<p class="error"><?php esc_html_e('Error loading content options.', 'subscription-system'); ?></p>';
            });
        }

        // Initialize content options if editing
        <?php if ($editing_plan && $editing_plan->content_type): ?>
        document.addEventListener('DOMContentLoaded', function() {
            updateContentOptions();
        });
        <?php endif; ?>
        </script>

    <?php elseif ($tables_exist): ?>
        <!-- Content Plans List -->
        <div class="content-plans-list">
            <?php if (empty($content_plans)): ?>
                <div class="no-content-plans">
                    <p><?php esc_html_e('No content subscription plans found.', 'subscription-system'); ?></p>
                    <p>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=subscription-content-plans&action=add')); ?>" class="button button-primary">
                            <?php esc_html_e('Create Your First Content Plan', 'subscription-system'); ?>
                        </a>
                    </p>
                </div>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th scope="col"><?php esc_html_e('Plan Name', 'subscription-system'); ?></th>
                            <th scope="col"><?php esc_html_e('Content Type', 'subscription-system'); ?></th>
                            <th scope="col"><?php esc_html_e('Price', 'subscription-system'); ?></th>
                            <th scope="col"><?php esc_html_e('Duration', 'subscription-system'); ?></th>
                            <th scope="col"><?php esc_html_e('Status', 'subscription-system'); ?></th>
                            <th scope="col"><?php esc_html_e('Stripe', 'subscription-system'); ?></th>
                            <th scope="col"><?php esc_html_e('Subscribers', 'subscription-system'); ?></th>
                            <th scope="col"><?php esc_html_e('Actions', 'subscription-system'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($content_plans as $plan): ?>
                            <?php
                            global $wpdb;
                            $subscriber_count = $wpdb->get_var($wpdb->prepare(
                                "SELECT COUNT(*) FROM {$wpdb->prefix}subscription_content_subscriptions WHERE content_plan_id = %d AND status = 'active'",
                                $plan->id
                            ));
                            $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;
                            $sync_nonce        = wp_create_nonce('sync_content_plan_with_stripe');
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo esc_html($plan->plan_name); ?></strong>
                                    <?php if ($plan->description): ?>
                                        <br><small><?php echo esc_html(wp_trim_words($plan->description, 10)); ?></small>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html($content_types[$plan->content_type] ?? $plan->content_type); ?></td>
                                <td>
                                    <?php if ($plan->price > 0): ?>
                                        $<?php echo esc_html(number_format($plan->price, 2)); ?>
                                    <?php else: ?>
                                        <?php esc_html_e('Free', 'subscription-system'); ?>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html($plan->duration . ' ' . $plan->duration_unit); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo esc_attr($plan->status); ?>">
                                        <?php echo esc_html(ucfirst($plan->status)); ?>
                                    </span>
                                </td>
                                <td class="ss-stripe-cell">
                                    <?php if ($is_connected): ?>
                                        <span class="stripe-status <?php echo $is_mock ? 'mock-connected' : 'connected'; ?>">
                                            <span class="dashicons dashicons-<?php echo $is_mock ? 'warning' : 'yes-alt'; ?>"></span>
                                            <?php echo $is_mock ? esc_html__('Mock', 'subscription-system') : esc_html__('Connected', 'subscription-system'); ?>
                                        </span>
                                        <?php if (! $is_mock): ?>
                                            <br><small title="<?php echo esc_attr($stripe_product_id); ?>"><?php echo esc_html(substr($stripe_product_id, 0, 12) . '…'); ?></small>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="stripe-status not-connected">
                                            <span class="dashicons dashicons-no"></span>
                                            <?php esc_html_e('None', 'subscription-system'); ?>
                                        </span>
                                    <?php endif; ?>
                                    <br>
                                    <a href="#"
                                       class="sync-content-plan-stripe"
                                       data-plan-id="<?php echo esc_attr($plan->id); ?>"
                                       data-nonce="<?php echo esc_attr($sync_nonce); ?>"
                                       style="font-size:11px;">
                                        <?php esc_html_e('Sync with Stripe', 'subscription-system'); ?>
                                    </a>
                                </td>
                                <td><?php echo esc_html($subscriber_count); ?></td>
                                <td>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=subscription-content-plans&action=edit&plan_id=' . $plan->id)); ?>" class="button button-small">
                                        <?php esc_html_e('Edit', 'subscription-system'); ?>
                                    </a>
                                    <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=subscription-content-plans&action=delete&plan_id=' . $plan->id), 'delete_content_plan_' . $plan->id)); ?>" 
                                       class="button button-small button-link-delete" 
                                       onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete this content plan? This will also remove all related subscriptions.', 'subscription-system'); ?>')">
                                        <?php esc_html_e('Delete', 'subscription-system'); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<style>
.content-plan-form-container {
    background: #fff;
    padding: 20px;
    margin-top: 20px;
    border: 1px solid #ccd0d4;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
}

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

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

.status-badge.status-inactive {
    background-color: #f8d7da;
    color: #721c24;
}

.required {
    color: #d63638;
}

.no-content-plans {
    text-align: center;
    padding: 40px 20px;
    background: #fff;
    border: 1px solid #ccd0d4;
    margin-top: 20px;
}

#content_selection_container {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #ddd;
    padding: 10px;
    background: #fafafa;
}

.content-checkboxes label {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 3px 0;
    line-height: 1.4;
}

.ss-claimed-item {
    opacity: 0.55;
    cursor: not-allowed;
}

.ss-claimed-item input[type="checkbox"] {
    cursor: not-allowed;
}

.ss-claimed-badge {
    display: inline-block;
    font-size: 11px;
    font-weight: 600;
    color: #8a2020;
    background: #fce8e8;
    border: 1px solid #f5c6cb;
    border-radius: 3px;
    padding: 1px 6px;
    margin-left: 4px;
    white-space: nowrap;
}

.ss-post-count {
    color: #8c8f94;
    font-size: 12px;
}

/* ── Stripe status column ─── */
.stripe-status {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    font-weight: 600;
    border-radius: 3px;
    padding: 2px 6px;
}
.stripe-status.connected {
    background: #d1fae5;
    color: #065f46;
}
.stripe-status.mock-connected {
    background: #fef3c7;
    color: #92400e;
}
.stripe-status.not-connected {
    background: #f3f4f6;
    color: #6b7280;
}
.stripe-status .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
    line-height: 1;
}
.ss-stripe-cell {
    min-width: 120px;
}
</style>

<script>
jQuery(document).ready(function ($) {
    $(document).on('click', '.sync-content-plan-stripe', function (e) {
        e.preventDefault();

        var $link     = $(this);
        var $cell     = $link.closest('td');
        var planId    = $link.data('plan-id');
        var nonce     = $link.data('nonce');
        var origHtml  = $cell.html();

        $cell.html('<span class="spinner is-active" style="float:none;margin:0;"></span> <?php esc_html_e('Syncing…', 'subscription-system'); ?>');

        $.ajax({
            url:  (typeof ajaxurl !== 'undefined') ? ajaxurl : '<?php echo esc_js(admin_url('admin-ajax.php')); ?>',
            type: 'POST',
            data: {
                action:  'sync_content_plan_with_stripe',
                plan_id: planId,
                nonce:   nonce
            },
            success: function (response) {
                if (response.success) {
                    var isMock   = response.data.mock_mode;
                    var icon     = isMock ? 'warning' : 'yes-alt';
                    var label    = isMock ? '<?php esc_html_e('Mock', 'subscription-system'); ?>'
                                         : '<?php esc_html_e('Connected', 'subscription-system'); ?>';
                    var cssClass = isMock ? 'mock-connected' : 'connected';

                    var html = '<span class="stripe-status ' + cssClass + '">'
                             + '<span class="dashicons dashicons-' + icon + '"></span> ' + label
                             + '</span>';

                    if (!isMock && response.data.product_id && response.data.product_id !== 'free') {
                        html += '<br><small title="' + response.data.product_id + '">'
                              + response.data.product_id.substring(0, 12) + '…</small>';
                    }
                    html += '<br><a href="#" class="sync-content-plan-stripe"'
                          + ' data-plan-id="' + planId + '" data-nonce="' + nonce + '"'
                          + ' style="font-size:11px;"><?php esc_html_e('Sync with Stripe', 'subscription-system'); ?></a>';

                    $cell.html(html);

                    var noticeClass = isMock ? 'notice-warning' : 'notice-success';
                    $('h1.wp-heading-inline').after(
                        '<div class="notice ' + noticeClass + ' is-dismissible" style="margin-top:12px;">'
                        + '<p>' + response.data.message + '</p>'
                        + '<button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button>'
                        + '</div>'
                    );
                    $(document).on('click', '.notice-dismiss', function () {
                        $(this).closest('.notice').fadeOut(200, function () { $(this).remove(); });
                    });
                } else {
                    $cell.html(origHtml);
                    alert('<?php esc_html_e('Error', 'subscription-system'); ?>: ' + (response.data ? response.data.message : '<?php esc_html_e('Unknown error.', 'subscription-system'); ?>'));
                }
            },
            error: function () {
                $cell.html(origHtml);
                alert('<?php esc_html_e('A network error occurred while syncing with Stripe.', 'subscription-system'); ?>');
            }
        });
    });
});
</script>
