<?php
namespace MineCloudvod\LMS\Addons;
use \MineCloudvod\RestApi\LMS\Base;
defined( 'ABSPATH' ) || exit;

class History extends Base{

    private $id = 'history';

    public function __construct() {
        // 记录开始浏览（仅对已登录用户）
        add_action('template_redirect',[$this, 'record_browsing_start']);

        // 添加JavaScript处理页面离开事件
        add_action('wp_footer', [$this, 'add_browsing_tracker_script']);

        // AJAX处理函数
        add_action('wp_ajax_update_browsing_duration', [$this, 'handle_browsing_duration_update']);

        // 在用户列表添加"浏览记录"操作链接
        add_filter('user_row_actions', [$this, 'add_user_browsing_history_link'], 10, 2);

        // 注册浏览记录页面
        add_action('admin_menu', [$this, 'register_user_browsing_history_page']);

        // 添加CSS样式美化浏览记录页面
        add_action('admin_head', [$this, 'user_browsing_history_css']);


        add_action('admin_init', [$this, 'handle_browsing_history_delete']);
    }

    public function handle_browsing_history_delete() {
        // 验证权限
        if (!current_user_can('manage_options') || !isset($_GET['_wpnonce']) || !isset($_GET['page']) || $_GET['page'] !== 'user_browsing_history' || isset($_GET['deleted']) ) {
            return;
        }
        global $wpdb;
        $user_id = intval( $_GET['user_id'] ?? 0 );
        $table_name = $wpdb->prefix.'mcv_history';
        $nonce = sanitize_text_field(wp_unslash($_GET['_wpnonce'] ?? ''));
        
        // 验证安全令牌
        if (!wp_verify_nonce($nonce, 'delete_browsing_history_'. $user_id)) {
            wp_die('安全验证失败，请重试');
        }
        
        global $wpdb;
        $deleted = 0;
        
        // 根据不同参数执行删除
        if (isset($_GET['delete_all'])) {
            // 删除所有记录
            $deleted = $wpdb->delete($table_name, ['user_id' => $user_id]);
        } elseif (isset($_GET['delete_week'])) {
            // 删除一周前的记录
            $date = wp_date('Y-m-d H:i:s', strtotime('-1 week'));
            $deleted = $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM $table_name WHERE user_id = %d AND start_time < %s",
                    $user_id,
                    $date
                )
            );
        } elseif (isset($_GET['delete_month'])) {
            // 删除一个月前的记录
            $date = wp_date('Y-m-d H:i:s', strtotime('-1 month'));
            $deleted = $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM $table_name WHERE user_id = %d AND start_time < %s",
                    $user_id,
                    $date
                )
            );
        } elseif (isset($_GET['delete_year'])) {
            // 删除一年前的记录
            $date = wp_date('Y-m-d H:i:s', strtotime('-1 year'));
            $deleted = $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM $table_name WHERE user_id = %d AND start_time < %s",
                    $user_id,
                    $date
                )
            );
        }
        
        // 跳回浏览记录页面并显示提示信息
        $redirect_url = add_query_arg([
            'page' => 'user_browsing_history',
            'user_id' => $user_id,
            'deleted' => $deleted
        ], admin_url('users.php'));
        
        wp_redirect($redirect_url);
        exit;
    }
    // 添加CSS样式美化浏览记录页面
    public function user_browsing_history_css() {
        $screen = get_current_screen();
        if ($screen->id === 'users_page_user_browsing_history') {
        ?>
            <style>
        .wp-list-table.widefat.fixed.striped.users th {
                padding: 8px 10px;
            }
        .wp-list-table.widefat.fixed.striped.users td {
                vertical-align: middle;
                padding: 10px;
            }
        .wrap h1 {
                margin: 20px 0;
            }
            </style>
            <?php
        }
    }
    // 渲染浏览记录页面
    public function render_user_browsing_history_page() {
        if (!current_user_can('manage_options')) wp_die('无权访问');
    
        $user_id = isset($_GET['user_id'])? intval($_GET['user_id']) : 0;
        if (!$user_id) wp_die('请指定有效的用户ID');
        
        $user = get_user_by('id', $user_id);
        if (!$user) wp_die('用户不存在');
        
        global $wpdb;
        $table_name = $wpdb->prefix.'mcv_history';
        $per_page = 20;
        $paged = max(1, intval($_GET['paged'] ?? 1));
        $offset = ($paged - 1) * $per_page;
        
        // 获取记录总数和当前页记录
        $total = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_name WHERE user_id = %d", $user_id));
        $records = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table_name WHERE user_id = %d ORDER BY start_time DESC LIMIT %d OFFSET %d",
            $user_id, $per_page, $offset
        ));
        
        // 生成删除链接（带安全验证）
        $base_url = add_query_arg([
            'page' => 'user_browsing_history',
            'user_id' => $user_id
        ], admin_url('users.php'));
        
        $delete_all_url = wp_nonce_url(add_query_arg('delete_all', 1, $base_url), 'delete_browsing_history_'. $user_id);
        $delete_week_url = wp_nonce_url(add_query_arg('delete_week', 1, $base_url), 'delete_browsing_history_'. $user_id);
        $delete_month_url = wp_nonce_url(add_query_arg('delete_month', 1, $base_url), 'delete_browsing_history_'. $user_id);
        $delete_year_url = wp_nonce_url(add_query_arg('delete_year', 1, $base_url), 'delete_browsing_history_'. $user_id);
        
        // 生成分页链接
        $pagination_args = array(
            'base' => add_query_arg('paged', '%#%'),
            'format' => '',
            'total' => ceil($total / $per_page),
            'current' => $paged,
            'prev_text' => '上一页',
            'next_text' => '下一页',
        );
    ?>
        <div class="wrap">
            <h1 class="wp-heading-inline">用户浏览记录: <?php echo esc_html($user->display_name);?> (ID: <?php echo esc_html($user_id);?>)</h1>
            <a class="page-title-action" href="<?php echo esc_url(admin_url('users.php'));?>" class="button">返回用户列表</a>
            <?php
            
                // 显示删除成功提示
                $deleted = isset($_GET['deleted'])? intval($_GET['deleted']) : 0;
                if ($deleted > 0) {
                    echo '<div class="updated notice is-dismissible">';
                    echo '<p>成功删除 '. esc_html($deleted).'条浏览记录</p>';
                    echo '</div>';
                } elseif ($deleted === 0 && isset($_GET['deleted'])) {
                    echo '<div class="notice notice-info is-dismissible">';
                    echo '<p>没有符合条件的记录可删除</p>';
                    echo '</div>';
                }
                
            ?>
            <div class="delete-actions" style="margin: 15px 0; padding: 10px; background: #f0f0f1; border-radius: 4px;">
                <p><strong>数据清理：</strong> 选择要删除的记录范围</p>
                <div style="margin-top: 10px;">
                    <a href="<?php echo esc_url($delete_week_url);?>" class="button button-secondary" onclick="return confirm('确定要删除一周前的记录吗？')">删除一周前的数据</a>
                    <a href="<?php echo esc_url($delete_month_url);?>" class="button button-secondary" onclick="return confirm('确定要删除一个月前的记录吗？')">删除一个月前的数据</a>
                    <a href="<?php echo esc_url($delete_year_url);?>" class="button button-secondary" onclick="return confirm('确定要删除一年前的记录吗？')">删除一年前的数据</a>
                    <a href="<?php echo esc_url($delete_all_url);?>" class="button button-danger" style="background: #dc3232; color: white; border-color: #dc3232;" onclick="return confirm('确定要删除该用户的所有浏览记录吗？此操作不可恢复！')">删除所有数据</a>
                </div>
            </div>
            
            <?php if (empty($records)):?>
                <div class="updated notice">
                    <p>该用户暂无浏览记录。</p>
                </div>
            <?php else:?>
                <table class="wp-list-table widefat fixed striped users">
                    <thead>
                        <tr>
                            <th>文章标题</th>
                            <th>浏览时间</th>
                            <th>浏览时长</th>
                            <th>IP地址</th>
                            <th>浏览器信息</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($records as $record):?>
                            <tr>
                                <td>
                                    <?php 
                                    $cpost = get_post($record->post_id);
                                    $post_title = $cpost->popeng_title ?? '';
                                    $course_escaped = '';
                                    if( $cpost->post_type == MINECLOUDVOD_LMS['lesson_post_type'] ){
                                        $course_id = mcv_lms_get_course_id_by_lesson_id($cpost->ID);
                                        $course_escaped = '课程： <a href="'. esc_url(get_permalink($course_id)). '" target="_blank">'. esc_html(get_the_title($course_id)). '</a><br/>';
                                        $post_title = $cpost->post_title;
                                    }
                                    if ($post_title) {
                                        echo $course_escaped;
                                        echo '<a href="'. esc_url(get_permalink($record->post_id)). '" target="_blank">'. esc_html($post_title). '</a>';
                                    } else {
                                        echo '文章已被删除或不存在 (ID: '. esc_html($record->post_id). ')';
                                    }
                                ?>
                                </td>
                                <td><?php echo esc_html(wp_date('Y-m-d H:i:s', strtotime($record->start_time)));?></td>
                                <td><?php echo $record->duration? esc_html(gmdate('H:i:s', $record->duration)) : '未知';?></td>
                                <td><?php echo esc_html($record->user_ip);?></td>
                                <td><div style="max-width: 200px; word-wrap: break-word;"><?php echo esc_html($record->user_agent);?></div></td>
                                <td>
                                    <a href="<?php echo esc_url($record->page_url);?>" target="_blank" class="button button-small">查看页面</a>
                                </td>
                            </tr>
                        <?php endforeach;?>
                    </tbody>
                </table>
                
                <?php echo paginate_links($pagination_args);?>
            <?php endif;?>
        </div>
        <?php
    }
    // 注册浏览记录页面
    public function register_user_browsing_history_page() {
        add_users_page(
            '用户浏览记录',
            '',
            'manage_options',
            'user_browsing_history',
            [$this, 'render_user_browsing_history_page']
        );
    }
    // 在用户列表添加"浏览记录"操作链接
    public function add_user_browsing_history_link($actions, $user) {
        // 只有管理员可以查看
        if (current_user_can('manage_options')) {
            $actions['browsing_history'] = '<a href="'. admin_url('users.php?page=user_browsing_history&user_id='. $user->ID). '" title="查看该用户的浏览记录">浏览记录</a>';
        }
        return $actions;
    }
    // 创建浏览记录表（包含IP和User-Agent字段）
    public static function preInit(){
        global $wpdb;
        $table_name = $wpdb->prefix. 'mcv_history';
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            post_id bigint(20) NOT NULL,
            page_url text NOT NULL,
            user_ip varchar(45) NOT NULL,
            user_agent text NOT NULL,
            start_time datetime NOT NULL,
            end_time datetime NULL,
            duration int(11) NULL,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        
        require_once(ABSPATH. 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    // 记录开始浏览（仅对已登录用户）
    public function record_browsing_start() {
        // 只记录已登录用户且不在后台
        if (is_single() &&!is_admin() && is_user_logged_in()) {
            global $wpdb, $post;
            $table_name = $wpdb->prefix. 'mcv_history';
            
            $user_id = get_current_user_id();
            $post_id = $post->ID;
            $page_url = get_permalink();
            $start_time = current_time('mysql');
            $user_ip = $this->get_user_real_ip();
            $user_agent = sanitize_text_field($_SERVER['HTTP_USER_AGENT']);
            
            // 插入新记录
            $wpdb->insert(
                $table_name,
                array(
                    'user_id' => $user_id,
                    'post_id' => $post_id,
                    'page_url' => $page_url,
                    'user_ip' => $user_ip,
                    'user_agent' => $user_agent,
                'start_time' => $start_time
                )
            );
            
            // 存储记录ID到Cookie，用于后续更新 $cookie_params = session_get_cookie_params();
            $cookie_path = '/'; // 使用根路径确保所有页面可访问
            $cookie_domain = $_SERVER['HTTP_HOST'];
            // 移除域名前可能的点号，现代浏览器对Cookie域名处理更严格
            $cookie_domain = ltrim($cookie_domain, '.');
            $secure = is_ssl(); // 仅在HTTPS下使用secure标记
            $http_only = false; // 关键：设为false允许JS访问
            $same_site = 'Lax'; // 适当的SameSite策略
            
            $expire = time() + 3600;
            
            // 设置Cookie
            if (!headers_sent()) {
                setcookie(
                    'browsing_record_id',
                    $wpdb->insert_id,
                    array(
                        'expires' => $expire,
                        'path' => $cookie_path,
                        'domain' => $cookie_domain,
                        'secure' => $secure,
                        'httponly' => $http_only,
                        'samesite' => $same_site
                    )
                );
            }
        }
    }
    // 添加JavaScript处理页面离开事件
    public function add_browsing_tracker_script() {
        // 只对已登录用户加载脚本
        if (is_single() &&!is_admin() && is_user_logged_in()) {
        ?>
            <script>
            // 页面可见性状态检测
            let isPageActive = true;
            window.mcv_h_intervalId = null;
            
            // 初始化页面可见性状态
            function checkPageVisibility() {
                return document.visibilityState === 'visible';
            }
            
            // 更新浏览时长的函数
            function updateBrowsingDuration() {
                const recordId = getCookie('browsing_record_id');
                if (recordId) {
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', '<?php echo esc_url(admin_url('admin-ajax.php'));?>', false);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.send('action=update_browsing_duration&record_id=' + recordId);
                }
            }
            
            // 启动定时更新
            function startInterval() {
                if (!window.mcv_h_intervalId) {
                    // 然后每10秒更新一次
                    window.mcv_h_intervalId = setInterval(updateBrowsingDuration, 10000);
                }
            }
            
            // 停止定时更新
            function stopInterval() {
                if (window.mcv_h_intervalId) {
                    clearInterval(window.mcv_h_intervalId);
                    window.mcv_h_intervalId = null;
                }
            }
            
            // 处理页面可见性变化
            function handleVisibilityChange() {
                const wasActive = isPageActive;
                isPageActive = checkPageVisibility();
                
                // 页面从不可见变为可见
                if (isPageActive &&!wasActive) {
                    startInterval();
                }
                // 页面从可见变为不可见
                else if (!isPageActive && wasActive) {
                    // 最后更新一次时长
                    updateBrowsingDuration();
                    stopInterval();
                }
            }
            
            // 页面关闭或刷新时发送请求
            window.addEventListener('beforeunload', function() {
                updateBrowsingDuration();
            });
            
            // 监听页面可见性变化
            document.addEventListener('visibilitychange', handleVisibilityChange);
            
            // 初始化 - 只有页面可见时才启动定时器
            if (checkPageVisibility()) {
                startInterval();
            }
            
            // 获取Cookie的辅助函数（优化版）
            function getCookie(name) {
                const encodedName = encodeURIComponent(name) + '=';
                const cookieArray = document.cookie.split(';');
                for (let i = 0; i < cookieArray.length; i++) {
                    let cookie = cookieArray[i];
                    while (cookie.charAt(0) === ' ') {
                        cookie = cookie.substring(1);
                    }
                    if (cookie.indexOf(encodedName) === 0) {
                        return decodeURIComponent(cookie.substring(encodedName.length));
                    }
                }
                return null;
            }
            </script>
            <?php
        }
    }
    // AJAX处理函数
    public function handle_browsing_duration_update() {
        // 验证用户已登录
        if (is_user_logged_in() && isset($_POST['record_id'])) {
            global $wpdb;
            $table_name = $wpdb->prefix. 'mcv_history';
            $record_id = intval($_POST['record_id']);
            
            // 验证该记录属于当前用户
            $user_id = get_current_user_id();
            $record_owner = $wpdb->get_var(
                $wpdb->prepare("SELECT user_id FROM $table_name WHERE id = %d", $record_id)
            );
            
            if ($record_owner == $user_id) {
                $end_time = current_time('mysql');
                $duration = $wpdb->get_var(
                    $wpdb->prepare("SELECT duration FROM $table_name WHERE id = %d", $record_id)
                );
                if( !$duration ) $duration = 0;

                $duration += 10;
                $wpdb->update(
                    $table_name,
                    array(
                        'end_time' => $end_time,
                        'duration' => $duration
                    ),
                    array('id' => $record_id)
                );
            }
        }
        wp_die();
    }
    // 获取用户真实IP地址
    public function get_user_real_ip() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            return sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']);
        } else {
            return sanitize_text_field($_SERVER['REMOTE_ADDR']);
        }
    }
}