<?php
/**
 * Content Subscribers Management Page
 *
 * This file displays the content subscribers management interface for admins.
 *
 * @link       https://mediahubster.in
 * @since      1.0.4
 *
 * @package    Subs_Sys
 * @subpackage Subs_Sys/admin/partials
 */

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

// Ensure content tables exist and are up to date
if ( ! Subs_Sys_DB_Updater::content_tables_exist() ) {
    Subs_Sys_DB_Updater::add_content_subscription_tables();
}

// Update table structure if needed
Subs_Sys_DB_Updater::update_content_table_structure();

global $wpdb;

// Handle bulk actions
if ( isset( $_POST['action'] ) && $_POST['action'] === 'bulk_unsubscribe' && isset( $_POST['subscribers'] ) ) {
    if ( wp_verify_nonce( $_POST['_wpnonce'], 'bulk_unsubscribe_nonce' ) ) {
        $unsubscribed_count = 0;
        foreach ( $_POST['subscribers'] as $subscription_id ) {
            $subscription_id = intval( $subscription_id );
            $result = $wpdb->update(
                $wpdb->prefix . 'subscription_content_subscriptions',
                array( 'status' => 'cancelled', 'end_date' => current_time( 'mysql' ) ),
                array( 'id' => $subscription_id ),
                array( '%s', '%s' ),
                array( '%d' )
            );
            if ( $result ) {
                $unsubscribed_count++;
            }
        }
        echo '<div class="notice notice-success"><p>' . sprintf( esc_html__( 'Successfully unsubscribed %d subscribers.', 'subscription-system' ), $unsubscribed_count ) . '</p></div>';
    }
}

// Get filter parameters
$status_filter = isset( $_GET['status'] ) ? sanitize_text_field( $_GET['status'] ) : 'all';
$plan_filter = isset( $_GET['plan'] ) ? intval( $_GET['plan'] ) : 0;
$search = isset( $_GET['s'] ) ? sanitize_text_field( $_GET['s'] ) : '';

// Build query conditions
$where_conditions = array();
$query_params = array();

if ( $status_filter !== 'all' ) {
    $where_conditions[] = 'cs.status = %s';
    $query_params[] = $status_filter;
}

if ( $plan_filter > 0 ) {
    $where_conditions[] = 'cs.content_plan_id = %d';
    $query_params[] = $plan_filter;
}

if ( ! empty( $search ) ) {
    $where_conditions[] = '(u.user_login LIKE %s OR u.user_email LIKE %s OR u.display_name LIKE %s)';
    $search_param = '%' . $wpdb->esc_like( $search ) . '%';
    $query_params[] = $search_param;
    $query_params[] = $search_param;
    $query_params[] = $search_param;
}

$where_clause = ! empty( $where_conditions ) ? 'WHERE ' . implode( ' AND ', $where_conditions ) : '';

// Get subscribers with pagination
$per_page = 20;
$current_page = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
$offset = ( $current_page - 1 ) * $per_page;

// Main query to get subscribers
$subscribers_query = "
    SELECT 
        cs.id,
        cs.user_id,
        cs.content_plan_id,
        cs.start_date,
        cs.end_date,
        cs.status,
        u.user_login,
        u.user_email,
        u.display_name,
        cp.plan_name,
        cp.price,
        cp.duration,
        cp.duration_unit,
        cp.content_type,
        cp.content_ids
    FROM {$wpdb->prefix}subscription_content_subscriptions cs
    LEFT JOIN {$wpdb->users} u ON cs.user_id = u.ID
    LEFT JOIN {$wpdb->prefix}subscription_content_plans cp ON cs.content_plan_id = cp.id
    {$where_clause}
    ORDER BY cs.start_date DESC
    LIMIT %d OFFSET %d
";

$query_params[] = $per_page;
$query_params[] = $offset;

$subscribers = $wpdb->get_results( $wpdb->prepare( $subscribers_query, $query_params ) );

// Get total count for pagination
$count_query = "
    SELECT COUNT(*)
    FROM {$wpdb->prefix}subscription_content_subscriptions cs
    LEFT JOIN {$wpdb->users} u ON cs.user_id = u.ID
    LEFT JOIN {$wpdb->prefix}subscription_content_plans cp ON cs.content_plan_id = cp.id
    {$where_clause}
";

$count_params = array_slice( $query_params, 0, -2 ); // Remove LIMIT and OFFSET params
$total_subscribers = $wpdb->get_var( empty( $count_params ) ? $count_query : $wpdb->prepare( $count_query, $count_params ) );

// Get statistics
$stats_query = "
    SELECT 
        cs.status,
        COUNT(*) as count,
        SUM(cp.price) as revenue
    FROM {$wpdb->prefix}subscription_content_subscriptions cs
    LEFT JOIN {$wpdb->prefix}subscription_content_plans cp ON cs.content_plan_id = cp.id
    GROUP BY cs.status
";
$stats = $wpdb->get_results( $stats_query );

// Get all content plans for filter dropdown
$content_plans = $wpdb->get_results( "SELECT id, plan_name FROM {$wpdb->prefix}subscription_content_plans ORDER BY plan_name" );

// Calculate total pages
$total_pages = ceil( $total_subscribers / $per_page );
?>

<div class="wrap">
    <h1 class="wp-heading-inline">
        <?php esc_html_e( 'Content Subscribers', 'subscription-system' ); ?>
    </h1>
    
    <!-- Statistics Cards -->
    <div class="subscription-stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0;">
        <?php
        $total_active = 0;
        $total_revenue = 0;
        $stats_by_status = array();
        
        foreach ( $stats as $stat ) {
            $stats_by_status[$stat->status] = $stat;
            if ( $stat->status === 'active' ) {
                $total_active = $stat->count;
            }
            $total_revenue += floatval( $stat->revenue );
        }
        ?>
        
        <div class="stats-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 12px; text-align: center;">
            <h3 style="margin: 0 0 10px 0; font-size: 32px; font-weight: 700;"><?php echo number_format( $total_subscribers ); ?></h3>
            <p style="margin: 0; opacity: 0.9;">Total Subscribers</p>
        </div>
        
        <div class="stats-card" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; padding: 20px; border-radius: 12px; text-align: center;">
            <h3 style="margin: 0 0 10px 0; font-size: 32px; font-weight: 700;"><?php echo number_format( $total_active ); ?></h3>
            <p style="margin: 0; opacity: 0.9;">Active Subscribers</p>
        </div>
        
        <div class="stats-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%); color: #8b4513; padding: 20px; border-radius: 12px; text-align: center;">
            <h3 style="margin: 0 0 10px 0; font-size: 32px; font-weight: 700;">$<?php echo number_format( $total_revenue, 2 ); ?></h3>
            <p style="margin: 0; opacity: 0.9;">Total Revenue</p>
        </div>
        
        <div class="stats-card" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); color: #4a5568; padding: 20px; border-radius: 12px; text-align: center;">
            <h3 style="margin: 0 0 10px 0; font-size: 32px; font-weight: 700;"><?php echo count( $content_plans ); ?></h3>
            <p style="margin: 0; opacity: 0.9;">Content Plans</p>
        </div>
    </div>

    <!-- Filters -->
    <div class="tablenav top">
        <div class="alignleft actions">
            <form method="get" style="display: inline-flex; gap: 10px; align-items: center;">
                <input type="hidden" name="post_type" value="subscription">
                <input type="hidden" name="page" value="content-subscribers">
                
                <select name="status" style="min-width: 120px;">
                    <option value="all"><?php esc_html_e( 'All Statuses', 'subscription-system' ); ?></option>
                    <option value="active" <?php selected( $status_filter, 'active' ); ?>><?php esc_html_e( 'Active', 'subscription-system' ); ?></option>
                    <option value="cancelled" <?php selected( $status_filter, 'cancelled' ); ?>><?php esc_html_e( 'Cancelled', 'subscription-system' ); ?></option>
                    <option value="expired" <?php selected( $status_filter, 'expired' ); ?>><?php esc_html_e( 'Expired', 'subscription-system' ); ?></option>
                </select>
                
                <select name="plan" style="min-width: 150px;">
                    <option value="0"><?php esc_html_e( 'All Plans', 'subscription-system' ); ?></option>
                    <?php foreach ( $content_plans as $plan ): ?>
                        <option value="<?php echo esc_attr( $plan->id ); ?>" <?php selected( $plan_filter, $plan->id ); ?>>
                            <?php echo esc_html( $plan->plan_name ); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                
                <input type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search subscribers...', 'subscription-system' ); ?>" style="min-width: 200px;">
                
                <input type="submit" class="button" value="<?php esc_attr_e( 'Filter', 'subscription-system' ); ?>">
                
                <?php if ( $status_filter !== 'all' || $plan_filter > 0 || ! empty( $search ) ): ?>
                    <a href="<?php echo admin_url( 'edit.php?post_type=subscription&page=content-subscribers' ); ?>" class="button">
                        <?php esc_html_e( 'Clear Filters', 'subscription-system' ); ?>
                    </a>
                <?php endif; ?>
            </form>
        </div>
        
        <div class="tablenav-pages">
            <?php
            $page_links = paginate_links( array(
                'base' => add_query_arg( 'paged', '%#%' ),
                'format' => '',
                'prev_text' => __( '&laquo;' ),
                'next_text' => __( '&raquo;' ),
                'total' => $total_pages,
                'current' => $current_page
            ) );
            
            if ( $page_links ) {
                echo '<span class="displaying-num">' . sprintf( esc_html( _n( '%s item', '%s items', $total_subscribers, 'subscription-system' ) ), number_format_i18n( $total_subscribers ) ) . '</span>';
                echo $page_links;
            }
            ?>
        </div>
    </div>

    <!-- Subscribers Table -->
    <form method="post">
        <?php wp_nonce_field( 'bulk_unsubscribe_nonce' ); ?>
        <input type="hidden" name="action" value="bulk_unsubscribe">
        
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <td class="manage-column column-cb check-column">
                        <input type="checkbox" id="cb-select-all">
                    </td>
                    <th class="manage-column"><?php esc_html_e( 'Subscriber', 'subscription-system' ); ?></th>
                    <th class="manage-column"><?php esc_html_e( 'Plan', 'subscription-system' ); ?></th>
                    <th class="manage-column"><?php esc_html_e( 'Content Type', 'subscription-system' ); ?></th>
                    <th class="manage-column"><?php esc_html_e( 'Price', 'subscription-system' ); ?></th>
                    <th class="manage-column"><?php esc_html_e( 'Status', 'subscription-system' ); ?></th>
                    <th class="manage-column"><?php esc_html_e( 'Start Date', 'subscription-system' ); ?></th>
                    <th class="manage-column"><?php esc_html_e( 'End Date', 'subscription-system' ); ?></th>
                    <th class="manage-column"><?php esc_html_e( 'Actions', 'subscription-system' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if ( empty( $subscribers ) ): ?>
                    <tr>
                        <td colspan="9" style="text-align: center; padding: 40px;">
                            <div style="color: #666; font-size: 16px;">
                                <?php if ( ! empty( $search ) || $status_filter !== 'all' || $plan_filter > 0 ): ?>
                                    <?php esc_html_e( 'No subscribers found matching your filters.', 'subscription-system' ); ?>
                                <?php else: ?>
                                    <?php esc_html_e( 'No content subscribers yet. Subscribers will appear here when users subscribe to content plans.', 'subscription-system' ); ?>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ( $subscribers as $subscriber ): ?>
                        <?php
                        // Parse content IDs
                        $content_ids = is_string( $subscriber->content_ids ) ? json_decode( $subscriber->content_ids, true ) : $subscriber->content_ids;
                        if ( ! is_array( $content_ids ) ) {
                            $content_ids = array();
                        }
                        
                        // Get content names based on type
                        $content_names = array();
                        switch ( $subscriber->content_type ) {
                            case 'category':
                                foreach ( $content_ids as $cat_id ) {
                                    $category = get_category( $cat_id );
                                    if ( $category ) {
                                        $content_names[] = $category->name;
                                    }
                                }
                                break;
                            case 'tag':
                                foreach ( $content_ids as $tag_id ) {
                                    $tag = get_tag( $tag_id );
                                    if ( $tag ) {
                                        $content_names[] = $tag->name;
                                    }
                                }
                                break;
                            case 'post_type':
                                foreach ( $content_ids as $post_type ) {
                                    $post_type_obj = get_post_type_object( $post_type );
                                    if ( $post_type_obj ) {
                                        $content_names[] = $post_type_obj->labels->name;
                                    }
                                }
                                break;
                            case 'post':
                                foreach ( $content_ids as $post_id ) {
                                    $post = get_post( $post_id );
                                    if ( $post ) {
                                        $content_names[] = $post->post_title;
                                    }
                                }
                                break;
                        }
                        
                        // Status styling
                        $status_class = '';
                        $status_color = '';
                        switch ( $subscriber->status ) {
                            case 'active':
                                $status_class = 'status-active';
                                $status_color = '#28a745';
                                break;
                            case 'cancelled':
                                $status_class = 'status-cancelled';
                                $status_color = '#dc3545';
                                break;
                            case 'expired':
                                $status_class = 'status-expired';
                                $status_color = '#ffc107';
                                break;
                            default:
                                $status_color = '#6c757d';
                        }
                        ?>
                        <tr>
                            <th scope="row" class="check-column">
                                <input type="checkbox" name="subscribers[]" value="<?php echo esc_attr( $subscriber->id ); ?>">
                            </th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 10px;">
                                    <?php echo get_avatar( $subscriber->user_email, 32, '', '', array( 'style' => 'border-radius: 50%;' ) ); ?>
                                    <div>
                                        <strong><?php echo esc_html( $subscriber->display_name ?: $subscriber->user_login ); ?></strong><br>
                                        <small style="color: #666;"><?php echo esc_html( $subscriber->user_email ); ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <strong><?php echo esc_html( $subscriber->plan_name ); ?></strong>
                                <?php if ( ! empty( $content_names ) ): ?>
                                    <br><small style="color: #666;"><?php echo esc_html( implode( ', ', array_slice( $content_names, 0, 3 ) ) ); ?><?php echo count( $content_names ) > 3 ? ' +' . ( count( $content_names ) - 3 ) . ' more' : ''; ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span style="background: #e9ecef; padding: 4px 8px; border-radius: 4px; font-size: 12px; text-transform: capitalize;">
                                    <?php echo esc_html( str_replace( '_', ' ', $subscriber->content_type ) ); ?>
                                </span>
                            </td>
                            <td>
                                <strong>$<?php echo number_format( floatval( $subscriber->price ), 2 ); ?></strong>
                                <br><small style="color: #666;">
                                    <?php 
                                    if ( isset( $subscriber->duration ) && isset( $subscriber->duration_unit ) && $subscriber->duration && $subscriber->duration_unit ) {
                                        echo esc_html( $subscriber->duration . ' ' . $subscriber->duration_unit );
                                    } else {
                                        echo esc_html__( 'One-time', 'subscription-system' );
                                    }
                                    ?>
                                </small>
                            </td>
                            <td>
                                <span style="color: <?php echo esc_attr( $status_color ); ?>; font-weight: 600; text-transform: capitalize;">
                                    <?php echo esc_html( $subscriber->status ); ?>
                                </span>
                            </td>
                            <td>
                                <?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $subscriber->start_date ) ) ); ?>
                            </td>
                            <td>
                                <?php if ( $subscriber->end_date && $subscriber->end_date !== '0000-00-00 00:00:00' ): ?>
                                    <?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $subscriber->end_date ) ) ); ?>
                                <?php else: ?>
                                    <span style="color: #666;">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ( $subscriber->status === 'active' ): ?>
                                    <button type="button" class="button button-small" onclick="unsubscribeUser(<?php echo esc_attr( $subscriber->id ); ?>, '<?php echo esc_js( $subscriber->display_name ?: $subscriber->user_login ); ?>')">
                                        <?php esc_html_e( 'Unsubscribe', 'subscription-system' ); ?>
                                    </button>
                                <?php else: ?>
                                    <span style="color: #666; font-style: italic;">
                                        <?php esc_html_e( 'No actions', 'subscription-system' ); ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
        
        <?php if ( ! empty( $subscribers ) ): ?>
            <div class="tablenav bottom">
                <div class="alignleft actions">
                    <select name="action2">
                        <option value="-1"><?php esc_html_e( 'Bulk Actions', 'subscription-system' ); ?></option>
                        <option value="bulk_unsubscribe"><?php esc_html_e( 'Unsubscribe Selected', 'subscription-system' ); ?></option>
                    </select>
                    <input type="submit" class="button action" value="<?php esc_attr_e( 'Apply', 'subscription-system' ); ?>" onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to unsubscribe the selected subscribers?', 'subscription-system' ); ?>');">
                </div>
                
                <div class="tablenav-pages">
                    <?php if ( $page_links ) echo $page_links; ?>
                </div>
            </div>
        <?php endif; ?>
    </form>
</div>

<style>
.subscription-stats-grid .stats-card {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease;
}

.subscription-stats-grid .stats-card:hover {
    transform: translateY(-2px);
}

.wp-list-table th,
.wp-list-table td {
    vertical-align: middle;
}

.status-active {
    color: #28a745 !important;
}

.status-cancelled {
    color: #dc3545 !important;
}

.status-expired {
    color: #ffc107 !important;
}
</style>

<script>
jQuery(document).ready(function($) {
    // Select all checkbox functionality
    $('#cb-select-all').on('click', function() {
        $('input[name="subscribers[]"]').prop('checked', this.checked);
    });
    
    // Update select all when individual checkboxes change
    $('input[name="subscribers[]"]').on('change', function() {
        var total = $('input[name="subscribers[]"]').length;
        var checked = $('input[name="subscribers[]"]:checked').length;
        $('#cb-select-all').prop('checked', total === checked);
    });
});

function unsubscribeUser(subscriptionId, userName) {
    if (confirm('Are you sure you want to unsubscribe ' + userName + ' from this content plan?')) {
        // Create a temporary form to submit the unsubscribe action
        var form = document.createElement('form');
        form.method = 'post';
        form.style.display = 'none';
        
        var nonceField = document.createElement('input');
        nonceField.type = 'hidden';
        nonceField.name = '_wpnonce';
        nonceField.value = '<?php echo wp_create_nonce( 'bulk_unsubscribe_nonce' ); ?>';
        form.appendChild(nonceField);
        
        var actionField = document.createElement('input');
        actionField.type = 'hidden';
        actionField.name = 'action';
        actionField.value = 'bulk_unsubscribe';
        form.appendChild(actionField);
        
        var subscriberField = document.createElement('input');
        subscriberField.type = 'hidden';
        subscriberField.name = 'subscribers[]';
        subscriberField.value = subscriptionId;
        form.appendChild(subscriberField);
        
        document.body.appendChild(form);
        form.submit();
    }
}
</script>
