<?php
// Защита от прямого доступа
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function enqueue_logs_page_styles() {
    // Подключение стилей для страницы логов
    wp_enqueue_style( 'ai-content-wizard-logs-page-style', AI_CONTENT_WIZARD_URL . 'css/logs-page-styles.css', array(), AI_CONTENT_WIZARD_VERSION );
}
add_action( 'admin_enqueue_scripts', 'enqueue_logs_page_styles' );

function ai_content_wizard_logs_page() {
    global $wpdb;
    
    // Форма фильтрации по периоду
    // По умолчанию выбираем "Last Month"
    $selected     = isset( $_GET['time_filter'] ) ? sanitize_text_field( $_GET['time_filter'] ) : 'month';
    $custom_start = isset( $_GET['custom_start'] ) ? sanitize_text_field( $_GET['custom_start'] ) : '';
    $custom_end   = isset( $_GET['custom_end'] ) ? sanitize_text_field( $_GET['custom_end'] ) : '';

    // Определяем временной интервал для фильтрации
    $start_date = '';
    $end_date   = '';
    if ( $selected === 'week' ) {
        $start_date = date( 'Y-m-d', strtotime( '-7 days' ) );
        $end_date   = date( 'Y-m-d' );
    } elseif ( $selected === 'month' ) {
        $start_date = date( 'Y-m-d', strtotime( '-1 month' ) );
        $end_date   = date( 'Y-m-d' );
    } elseif ( $selected === 'year' ) {
        $start_date = date( 'Y-m-d', strtotime( '-1 year' ) );
        $end_date   = date( 'Y-m-d' );
    } elseif ( $selected === 'custom' ) {
        if ( ! empty( $custom_start ) && ! empty( $custom_end ) ) {
            $start_date = $custom_start;
            $end_date   = $custom_end;
        }
    }
    
    // Формируем условия для запросов логов
    if ( $start_date && $end_date ) {
        $logs_date_condition_content = $wpdb->prepare( "WHERE DATE(date) BETWEEN %s AND %s", $start_date, $end_date );
        $logs_date_condition_article = $wpdb->prepare( "WHERE DATE(generation_time) BETWEEN %s AND %s", $start_date, $end_date );
    } else {
        $logs_date_condition_content = '';
        $logs_date_condition_article = '';
    }
    
    // Сохраним в глобальные переменные для использования в функциях вывода
    $GLOBALS['logs_date_condition_content'] = $logs_date_condition_content;
    $GLOBALS['logs_date_condition_article'] = $logs_date_condition_article;
    
    // Собираем GET-параметры фильтра для пагинации и табов
    $filter_params = "&time_filter=" . urlencode( $selected );
    if ( $selected === 'custom' ) {
        $filter_params .= "&custom_start=" . urlencode( $custom_start ) . "&custom_end=" . urlencode( $custom_end );
    }
    
    echo '<div class="ai-content-wizard-logs-page">';
    echo '<h1>' . esc_html__( 'AI Content Wizard - Logs', 'ai-content-wizard' ) . '</h1>';
    
    // Форма фильтрации
    echo '<form method="get" class="ai-cw-logs-filter-form">';
        if ( isset( $_GET['page'] ) ) {
            echo '<input type="hidden" name="page" value="' . esc_attr( $_GET['page'] ) . '">';
        }
        echo '<label for="time_filter">' . esc_html__( 'Period', 'ai-content-wizard' ) . ':</label>';
        echo '<select name="time_filter" id="time_filter">';
            echo '<option value="all"' . selected( $selected, 'all', false ) . '>' . esc_html__( 'All Time', 'ai-content-wizard' ) . '</option>';
            echo '<option value="week"' . selected( $selected, 'week', false ) . '>' . esc_html__( 'Last Week', 'ai-content-wizard' ) . '</option>';
            echo '<option value="month"' . selected( $selected, 'month', false ) . '>' . esc_html__( 'Last Month', 'ai-content-wizard' ) . '</option>';
            echo '<option value="year"' . selected( $selected, 'year', false ) . '>' . esc_html__( 'Last Year', 'ai-content-wizard' ) . '</option>';
            echo '<option value="custom"' . selected( $selected, 'custom', false ) . '>' . esc_html__( 'Custom', 'ai-content-wizard' ) . '</option>';
        echo '</select>';
        
        // Поля для произвольного периода
        $custom_display = ( $selected === 'custom' ) ? '' : 'display:none;';
        echo '<div id="custom_period_fields" style="' . esc_attr( $custom_display ) . '">';
            echo '<div class="custom-dates-wrapper">';
                echo '<label for="custom_start">' . esc_html__( 'Start Date', 'ai-content-wizard' ) . ':</label>';
                echo '<input type="date" name="custom_start" id="custom_start" value="' . esc_attr( $custom_start ) . '">';
                echo '<label for="custom_end">' . esc_html__( 'End Date', 'ai-content-wizard' ) . ':</label>';
                echo '<input type="date" name="custom_end" id="custom_end" value="' . esc_attr( $custom_end ) . '">';
            echo '</div>';
        echo '</div>';
        
        echo '<input type="submit" value="' . esc_attr__( 'Apply', 'ai-content-wizard' ) . '">';
    echo '</form>';
    
    // JS для переключения полей произвольного периода
    echo "<script>
        document.getElementById('time_filter').addEventListener('change', function() {
            var customFields = document.getElementById('custom_period_fields');
            if (this.value === 'custom') {
                customFields.style.display = '';
                customFields.classList.add('custom-active');
            } else {
                customFields.style.display = 'none';
                customFields.classList.remove('custom-active');
            }
        });
    </script>";
    
    // Получаем общее количество записей для каждого таба
    $content_total = $wpdb->get_var( "SELECT COUNT(*) FROM " . $wpdb->prefix . "ai_content_wizard_content_plan_logs " . $GLOBALS['logs_date_condition_content'] );
    $article_total = $wpdb->get_var( "SELECT COUNT(*) FROM " . $wpdb->prefix . "ai_content_wizard_posts_logs " . $GLOBALS['logs_date_condition_article'] );
    
    // Заголовок табов с кнопками и блоком количества записей
    echo '<div class="ai-cw-tab-header">';
		echo '<div class="ai-cw-tab-buttons">';
			echo '<button class="ai-cw-tab-button pro-tab" disabled style="opacity:0.5; cursor:not-allowed;" data-count="' . intval( $content_total ) . '">'
					. esc_html__( 'Content Plan Logs', 'ai-content-wizard' )
					. ' <span class="pro-badge" style="font-size:12px; background:#0073aa; color:#fff; padding:2px 4px; border-radius:3px; margin-left:5px;">PRO</span>'
				 . '</button>';
			echo '<button class="ai-cw-tab-button" onclick="openTab(event, \'PostGenerationLogs\')" data-count="' . intval( $article_total ) . '">'
					. esc_html__( 'Post Generation Logs', 'ai-content-wizard' )
				 . '</button>';
		echo '</div>';

		echo '<div class="log-count-header">';
			/* translators: %d — общее количество записей. */
			echo sprintf( esc_html__( 'Total Records: %d', 'ai-content-wizard' ), intval( $content_total ) );
		echo '</div>';

    echo '</div>';
    
    // Содержимое табов (без отдельного вывода количества записей)
    echo '<div id="ContentPlanLogs" class="ai-cw-tab-content" style="display: block;">';
        echo '<div class="tab-content-wrapper">';
            echo '<h2>' . esc_html__( 'Content Plan Logs', 'ai-content-wizard' ) . '</h2>';
            ai_content_wizard_display_logs( $filter_params );
        echo '</div>';
    echo '</div>';

    echo '<div id="PostGenerationLogs" class="ai-cw-tab-content" style="display: none;">';
        echo '<div class="tab-content-wrapper">';
            echo '<h2>' . esc_html__( 'Post Generation Logs', 'ai-content-wizard' ) . '</h2>';
            ai_content_wizard_display_article_logs( $filter_params );
        echo '</div>';
    echo '</div>';
    ?>
    <script>
        function openTab(evt, tabName) {
            var tabcontent = document.getElementsByClassName("ai-cw-tab-content");
            for (var i = 0; i < tabcontent.length; i++) {
                tabcontent[i].style.display = "none";
            }
            var tablinks = document.getElementsByClassName("ai-cw-tab-button");
            for (var i = 0; i < tablinks.length; i++) {
                tablinks[i].classList.remove("active");
            }
            document.getElementById(tabName).style.display = "block";
            evt.currentTarget.classList.add("active");

            // Обновляем количество записей в заголовке, берём из data-атрибута кнопки
            var count = evt.currentTarget.getAttribute('data-count');
            document.querySelector('.log-count-header').innerText = '<?php echo esc_html__( 'Total Records: ', 'ai-content-wizard' ); ?>' + count;

            // Обновляем параметр tab в URL и сохраняем активный таб
            var newUrl = new URL(window.location.href);
            newUrl.searchParams.set('tab', tabName);
            window.history.pushState({}, '', newUrl);
            localStorage.setItem('activeTab', tabName);
        }

        // При загрузке страницы проверяем активный таб из localStorage
        document.addEventListener('DOMContentLoaded', function() {
            var activeTab = localStorage.getItem('activeTab');
            if (activeTab) {
                var tabButton = document.querySelector("button[onclick*=\"openTab(event, '" + activeTab + "')\"]");
                if (tabButton) {
                    tabButton.click();
                }
            }
        });
    </script>
    <?php
    echo '</div>';
}

function ai_content_wizard_display_logs( $filter_params = '' ) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_content_plan_logs';
    
    // Пагинация
    $per_page     = 20;
    $current_page = isset( $_GET['content_plan_log_page'] ) ? max( 1, intval( $_GET['content_plan_log_page'] ) ) : 1;
    $offset       = ( $current_page - 1 ) * $per_page;
    
    // Общее количество записей
    $total_records = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name " . $GLOBALS['logs_date_condition_content'] );
    
    // Получаем записи с фильтром и пагинацией
    $query = "SELECT * FROM $table_name " . $GLOBALS['logs_date_condition_content'] . " ORDER BY date DESC LIMIT %d OFFSET %d";
    $logs  = $wpdb->get_results( $wpdb->prepare( $query, $per_page, $offset ), ARRAY_A );
    
    if ( ! $logs ) {
        echo "<p class='ai-cw-no-logs'>" . esc_html__( 'No Content Plan Logs available.', 'ai-content-wizard' ) . "</p>";
        return;
    }
    
    echo "<table class='ai-cw-logs-table wp-list-table widefat fixed striped'>";
    echo "<thead><tr>
        <th>" . esc_html__( 'Date', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Type', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Text Model', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Total Articles', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Interval', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Period', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Language', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Categories', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Total Cost', 'ai-content-wizard' ) . "</th>
    </tr></thead>";
    echo "<tbody>";
    
    foreach ( $logs as $log ) {
        echo "<tr>";
        echo "<td>" . esc_html( $log['date'] ) . "</td>";
        echo "<td>" . esc_html( $log['type'] ) . "</td>";
        echo "<td>" . esc_html( $log['text_model'] ) . "</td>";
        echo "<td>" . esc_html( $log['total_articles'] ) . "</td>";
        echo "<td>" . esc_html( $log['interval_days'] ) . "</td>";
        echo "<td>" . esc_html( $log['period_days'] ) . "</td>";
        echo "<td>" . esc_html( $log['language'] ) . "</td>";
        echo "<td>" . esc_html( $log['categories'] ) . "</td>";
        echo "<td>$" . number_format( $log['total_cost'], 2 ) . "</td>";
        echo "</tr>";
    }
    echo "</tbody></table>";
    
    // Пагинация
    $total_pages = ceil( $total_records / $per_page );
    if ( $total_pages > 1 ) {
        echo '<div class="pagination">';
        for ( $page = 1; $page <= $total_pages; $page++ ) {
            if ( $page == $current_page ) {
                echo '<span class="current-page">' . esc_html( $page ) . '</span> ';
            } else {
                echo '<a href="?page=ai_content_wizard_logs&log_page=' . esc_attr( $page ) . esc_attr( $filter_params ) . '">' . esc_html( $page ) . '</a> ';
            }
        }
        echo '</div>';
    }
}

function ai_content_wizard_display_article_logs( $filter_params = '' ) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_posts_logs';
    
    // Пагинация
    $per_page     = 20;
    $current_page = isset( $_GET['log_page'] ) ? max( 1, intval( $_GET['log_page'] ) ) : 1;
    $offset       = ( $current_page - 1 ) * $per_page;
    
    // Общее количество записей
    $total_records = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name " . $GLOBALS['logs_date_condition_article'] );
    
    // Получаем записи с фильтром и пагинацией
    $query = "SELECT * FROM $table_name " . $GLOBALS['logs_date_condition_article'] . " ORDER BY generation_time DESC LIMIT %d OFFSET %d";
    $logs  = $wpdb->get_results( $wpdb->prepare( $query, $per_page, $offset ), ARRAY_A );
    
    if ( ! $logs ) {
        echo "<p class='ai-cw-no-article-logs'>" . esc_html__( 'No Post Generation Logs available.', 'ai-content-wizard' ) . "</p>";
        return;
    }
    
    echo "<table class='ai-cw-article-logs-table wp-list-table widefat fixed striped'>";
    echo "<thead><tr>
        <th>" . esc_html__( 'Generation Time', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Post ID', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Type', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Category', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Publish Time', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Title', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Keyword', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Language', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Text Model', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Image Model', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Image Cost', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Text Cost', 'ai-content-wizard' ) . "</th>
        <th>" . esc_html__( 'Total Cost', 'ai-content-wizard' ) . "</th>
    </tr></thead>";
    echo "<tbody>";
    
    foreach ( $logs as $log ) {
        echo "<tr>";
        echo "<td>" . esc_html( $log['generation_time'] ) . "</td>";
        
        // Post ID с ссылкой на редактирование
        $edit_post_url = admin_url( 'post.php?post=' . intval( $log['post_id'] ) . '&action=edit' );
        echo "<td><a href='" . esc_url( $edit_post_url ) . "'>" . intval( $log['post_id'] ) . "</a></td>";
        
        echo "<td>" . esc_html( $log['type'] ) . "</td>";
        echo "<td>" . esc_html( $log['category'] ) . "</td>";
        echo "<td>" . esc_html( $log['publish_time'] ) . "</td>";
        
        // Title с ссылкой на пост
        $post_url = get_permalink( $log['post_id'] );
        echo "<td><a href='" . esc_url( $post_url ) . "'>" . esc_html( $log['title'] ) . "</a></td>";
        
        echo "<td>" . esc_html( $log['keyword'] ) . "</td>";
        echo "<td>" . esc_html( $log['language'] ) . "</td>";
        echo "<td>" . esc_html( $log['text_model'] ) . "</td>";
        echo "<td>" . esc_html( $log['image_model'] ) . "</td>";
        echo "<td>$" . number_format( $log['image_cost'], 3 ) . "</td>";
        echo "<td>$" . number_format( $log['text_cost'], 3 ) . "</td>";
        echo "<td>$" . number_format( $log['total_cost'], 3 ) . "</td>";
        echo "</tr>";
    }
    echo "</tbody></table>";
    
    // Пагинация
    $total_pages = ceil( $total_records / $per_page );
    if ( $total_pages > 1 ) {
        echo '<div class="pagination">';
        for ( $page = 1; $page <= $total_pages; $page++ ) {
            if ( $page == $current_page ) {
                echo '<span class="current-page">' . esc_html( $page ) . '</span> ';
            } else {
                echo '<a href="?page=ai_content_wizard_logs&log_page=' . esc_attr( $page ) . esc_attr( $filter_params ) . '">' . esc_html( $page ) . '</a> ';
            }
        }
        echo '</div>';
    }
}
