<?php
defined( 'ABSPATH' ) || exit;

// Pagination.
$per_page    = 25;
$current_page = isset( $_GET['paged'] ) ? max( 1, (int) $_GET['paged'] ) : 1;
$offset      = ( $current_page - 1 ) * $per_page;

// User filter.
$filter_user = isset( $_GET['lsc_user'] ) ? (int) $_GET['lsc_user'] : 0;

// Fetch data.
$sessions    = LSC_Sessions::get_sessions( [ 'limit' => $per_page, 'offset' => $offset, 'user_id' => $filter_user ] );
$total       = LSC_Sessions::count_sessions( $filter_user );
$total_pages = max( 1, ceil( $total / $per_page ) );

// All chatters for the filter dropdown.
$chatters = get_users( [ 'role__in' => [ 'chatter', 'administrator' ], 'orderby' => 'display_name' ] );

// Base URL for links.
$base_url = admin_url( 'admin.php?page=lsc-sessions' );
?>
<div class="wrap lsc-admin-wrap">
    <h1 class="lsc-page-title">
        <span class="dashicons dashicons-clock"></span>
        <?php esc_html_e( 'Chatter Activity Log', 'live-support-chat' ); ?>
    </h1>

    <?php if ( isset( $_GET['cleared'] ) ) : ?>
        <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Log cleared successfully.', 'live-support-chat' ); ?></p></div>
    <?php endif; ?>
    <?php if ( isset( $_GET['deleted'] ) ) : ?>
        <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Session record deleted.', 'live-support-chat' ); ?></p></div>
    <?php endif; ?>

    <!-- ── Filter bar ── -->
    <div class="lsc-card lsc-sessions-filter-bar">
        <form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
            <input type="hidden" name="page" value="lsc-sessions" />

            <label for="lsc_user_filter" style="font-weight:600;font-size:.88rem;">
                <?php esc_html_e( 'Filter by chatter:', 'live-support-chat' ); ?>
            </label>
            <select name="lsc_user" id="lsc_user_filter" style="min-width:180px;">
                <option value="0"><?php esc_html_e( '— All chatters —', 'live-support-chat' ); ?></option>
                <?php foreach ( $chatters as $chatter ) : ?>
                    <option value="<?php echo esc_attr( $chatter->ID ); ?>" <?php selected( $filter_user, $chatter->ID ); ?>>
                        <?php echo esc_html( $chatter->display_name . ' (' . $chatter->user_login . ')' ); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <?php submit_button( __( 'Filter', 'live-support-chat' ), 'secondary', '', false, [ 'style' => 'margin:0' ] ); ?>

            <?php if ( $filter_user ) : ?>
                <a href="<?php echo esc_url( $base_url ); ?>" class="button"><?php esc_html_e( 'Clear filter', 'live-support-chat' ); ?></a>
            <?php endif; ?>

            <!-- Clear all log button -->
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-left:auto;"
                  onsubmit="return confirm('<?php esc_attr_e( 'Clear the entire activity log? This cannot be undone.', 'live-support-chat' ); ?>')">
                <?php wp_nonce_field( 'lsc_clear_sessions' ); ?>
                <input type="hidden" name="action" value="lsc_clear_sessions" />
                <button type="submit" class="button button-link-delete">
                    🗑 <?php esc_html_e( 'Clear entire log', 'live-support-chat' ); ?>
                </button>
            </form>
        </form>
    </div>

    <!-- ── Stats summary ── -->
    <?php if ( ! empty( $sessions ) ) :
        // Quick stats from full dataset (not filtered page).
        $all_sessions = LSC_Sessions::get_sessions( [ 'limit' => 9999, 'user_id' => $filter_user ] );
        $closed = array_filter( $all_sessions, fn($s) => ! empty( $s->logout_at ) );
        $avg_sec = 0;
        if ( count( $closed ) > 0 ) {
            $total_sec = array_sum( array_map(
                fn($s) => max( 0, strtotime( $s->logout_at ) - strtotime( $s->login_at ) ),
                $closed
            ) );
            $avg_sec = (int) round( $total_sec / count( $closed ) );
        }
    ?>
    <div class="lsc-stats-row" style="margin-bottom:16px;">
        <div class="lsc-stat-card">
            <div class="lsc-stat-number"><?php echo esc_html( $total ); ?></div>
            <div class="lsc-stat-label"><?php esc_html_e( 'Total Sessions', 'live-support-chat' ); ?></div>
        </div>
        <div class="lsc-stat-card">
            <div class="lsc-stat-number"><?php echo esc_html( count( $closed ) ); ?></div>
            <div class="lsc-stat-label"><?php esc_html_e( 'Completed Sessions', 'live-support-chat' ); ?></div>
        </div>
        <div class="lsc-stat-card">
            <div class="lsc-stat-number"><?php echo esc_html( LSC_Sessions::duration( date( 'Y-m-d H:i:s', time() - $avg_sec ), date( 'Y-m-d H:i:s' ) ) ); ?></div>
            <div class="lsc-stat-label"><?php esc_html_e( 'Avg. Session Duration', 'live-support-chat' ); ?></div>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── Session table ── -->
    <div class="lsc-card" style="padding:0;overflow:hidden;">
        <?php if ( empty( $sessions ) ) : ?>
            <p style="padding:32px;text-align:center;color:#94a3b8;">
                <?php esc_html_e( 'No session records found.', 'live-support-chat' ); ?>
            </p>
        <?php else : ?>
            <table class="widefat lsc-sessions-table">
                <thead>
                    <tr>
                        <th><?php esc_html_e( 'Chatter', 'live-support-chat' ); ?></th>
                        <th><?php esc_html_e( 'Logged In', 'live-support-chat' ); ?></th>
                        <th><?php esc_html_e( 'Logged Out', 'live-support-chat' ); ?></th>
                        <th><?php esc_html_e( 'Duration', 'live-support-chat' ); ?></th>
                        <th><?php esc_html_e( 'IP Address', 'live-support-chat' ); ?></th>
                        <th><?php esc_html_e( 'Actions', 'live-support-chat' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $sessions as $s ) :
                        $is_active = empty( $s->logout_at );
                        $date_fmt  = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
                        $duration  = LSC_Sessions::duration( $s->login_at, $s->logout_at );
                    ?>
                    <tr class="<?php echo $is_active ? 'lsc-row-active' : ''; ?>">

                        <!-- Chatter -->
                        <td>
                            <div style="display:flex;align-items:center;gap:9px;">
                                <div class="lsc-session-avatar"><?php echo esc_html( strtoupper( substr( $s->display_name ?: $s->user_login, 0, 1 ) ) ); ?></div>
                                <div>
                                    <div style="font-weight:600;font-size:.88rem;"><?php echo esc_html( $s->display_name ?: $s->user_login ); ?></div>
                                    <div style="font-size:.75rem;color:#94a3b8;">@<?php echo esc_html( $s->user_login ); ?></div>
                                </div>
                            </div>
                        </td>

                        <!-- Logged in -->
                        <td>
                            <div style="font-size:.88rem;"><?php echo esc_html( mysql2date( $date_fmt, $s->login_at ) ); ?></div>
                        </td>

                        <!-- Logged out -->
                        <td>
                            <?php if ( $is_active ) : ?>
                                <span class="lsc-badge lsc-badge-green" style="animation:lsc-pulse-badge 2s infinite;">
                                    🟢 <?php esc_html_e( 'Currently active', 'live-support-chat' ); ?>
                                </span>
                            <?php else : ?>
                                <div style="font-size:.88rem;"><?php echo esc_html( mysql2date( $date_fmt, $s->logout_at ) ); ?></div>
                            <?php endif; ?>
                        </td>

                        <!-- Duration -->
                        <td>
                            <?php if ( $is_active ) : ?>
                                <span style="color:#94a3b8;font-size:.83rem;"><?php esc_html_e( 'In progress', 'live-support-chat' ); ?></span>
                            <?php else : ?>
                                <span class="lsc-badge lsc-badge-blue"><?php echo esc_html( $duration ); ?></span>
                            <?php endif; ?>
                        </td>

                        <!-- IP -->
                        <td style="font-size:.83rem;color:#64748b;font-family:monospace;">
                            <?php echo esc_html( $s->ip_address ?: '—' ); ?>
                        </td>

                        <!-- Actions -->
                        <td>
                            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
                                  onsubmit="return confirm('<?php esc_attr_e( 'Delete this record?', 'live-support-chat' ); ?>')">
                                <?php wp_nonce_field( 'lsc_delete_session' ); ?>
                                <input type="hidden" name="action"     value="lsc_delete_session" />
                                <input type="hidden" name="session_id" value="<?php echo esc_attr( $s->id ); ?>" />
                                <?php if ( $filter_user ) : ?>
                                    <input type="hidden" name="redirect_user" value="<?php echo esc_attr( $filter_user ); ?>" />
                                <?php endif; ?>
                                <button type="submit" class="button button-small button-link-delete">
                                    <?php esc_html_e( 'Delete', 'live-support-chat' ); ?>
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Pagination -->
            <?php if ( $total_pages > 1 ) : ?>
            <div class="lsc-sessions-pagination">
                <span style="color:#64748b;font-size:.83rem;">
                    <?php printf(
                        esc_html__( 'Showing %1$d–%2$d of %3$d sessions', 'live-support-chat' ),
                        $offset + 1,
                        min( $offset + $per_page, $total ),
                        $total
                    ); ?>
                </span>
                <div style="display:flex;gap:4px;">
                    <?php for ( $p = 1; $p <= $total_pages; $p++ ) :
                        $page_url = add_query_arg( array_filter( [ 'page' => 'lsc-sessions', 'paged' => $p > 1 ? $p : null, 'lsc_user' => $filter_user ?: null ] ), admin_url( 'admin.php' ) );
                    ?>
                        <a href="<?php echo esc_url( $page_url ); ?>"
                           class="button button-small <?php echo $p === $current_page ? 'button-primary' : ''; ?>">
                            <?php echo esc_html( $p ); ?>
                        </a>
                    <?php endfor; ?>
                </div>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<style>
.lsc-sessions-filter-bar { padding: 14px 20px; }
.lsc-sessions-table th   { padding: 12px 16px; font-size: .8rem; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; color: #64748b; border-bottom: 2px solid #e2e8f0 !important; background: #f8fafc; }
.lsc-sessions-table td   { padding: 14px 16px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }
.lsc-sessions-table tr:last-child td { border-bottom: none; }
.lsc-sessions-table tr.lsc-row-active td { background: #f0fdf4; }
.lsc-session-avatar {
    width: 34px; height: 34px; border-radius: 8px;
    background: linear-gradient(135deg,#2563eb,#7c3aed);
    color: #fff; font-weight: 700; font-size: .85rem;
    display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.lsc-sessions-pagination {
    display: flex; align-items: center; justify-content: space-between;
    padding: 14px 20px; border-top: 1px solid #f1f5f9;
    flex-wrap: wrap; gap: 10px;
}
@keyframes lsc-pulse-badge { 0%,100%{opacity:1} 50%{opacity:.6} }
</style>
