<?php
/**
 * Request Log Page
 * 
 * Displays all API request logs with pagination and delete options
 * 
 * @package PSSG_Sync_Sheet
 * @since 1.1.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly  

use PSSG_Sync_Sheet\App\Service\Request_Log;

// Handle bulk actions
if ( isset( $_POST['pssg_bulk_action'] ) && isset( $_POST['pssg_log_nonce'] ) ) {
    if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['pssg_log_nonce'] ) ), 'pssg_log_bulk_action' ) ) {
        $action = sanitize_text_field( wp_unslash( $_POST['pssg_bulk_action'] ) );
        
        if ( $action === 'delete' && !empty( $_POST['log_ids'] ) ) {
            $ids = array_map( 'absint', (array) $_POST['log_ids'] );
            Request_Log::delete_logs( $ids );
            echo '<div class="notice notice-success"><p>' . esc_html__( 'Selected logs have been deleted.', 'product-sync-master-sheet' ) . '</p></div>';
        }
        
        if ( $action === 'delete_all' ) {
            Request_Log::delete_all_logs();
            echo '<div class="notice notice-success"><p>' . esc_html__( 'All logs have been deleted.', 'product-sync-master-sheet' ) . '</p></div>';
        }
    }
}

// Handle single delete
if ( isset( $_GET['delete_log'] ) && isset( $_GET['_wpnonce'] ) ) {
    if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'pssg_delete_log' ) ) {
        $log_id = absint( $_GET['delete_log'] );
        if ( Request_Log::delete_log( $log_id ) ) {
            echo '<div class="notice notice-success"><p>' . esc_html__( 'Log entry deleted successfully.', 'product-sync-master-sheet' ) . '</p></div>';
        }
    }
}

// Pagination
$per_page = 20;
$current_page = isset( $_GET['paged'] ) ? max( 1, absint( $_GET['paged'] ) ) : 1;
$status_filter = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '';
$search = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';

// Get logs
$args = [
    'per_page' => $per_page,
    'page' => $current_page,
    'status' => $status_filter,
    'search' => $search,
];

$logs = Request_Log::get_logs( $args );
$total_logs = Request_Log::get_logs_count( $args );
$total_pages = ceil( $total_logs / $per_page );

// Status counts for filters
$status_counts = [
    'all' => Request_Log::get_logs_count( [] ),
    'success' => Request_Log::get_logs_count( ['status' => 'success'] ),
    'error' => Request_Log::get_logs_count( ['status' => 'error'] ),
    'unauthorized' => Request_Log::get_logs_count( ['status' => 'unauthorized'] ),
];

include $this->topbar_file;
?>

<div class="wrap pssg_wrap pssg-content pssg-request-log-page">
    <h1 class="wp-heading">
        <i class="pssg_icon-doc-text"></i>
        <?php echo esc_html__( 'API Logs', 'product-sync-master-sheet' ); ?>
        <span class="title-count"><?php echo esc_html( number_format_i18n( $total_logs ) ); ?></span>
    </h1>

    <!-- Filters -->
    <div class="pssg-log-filters">
        <ul class="subsubsub">
            <li>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=pssg-api-logs' ) ); ?>" 
                   class="<?php echo empty($status_filter) ? 'current' : ''; ?>">
                    <?php echo esc_html__( 'All', 'product-sync-master-sheet' ); ?>
                    <span class="count">(<?php echo esc_html( $status_counts['all'] ); ?>)</span>
                </a> |
            </li>
            <li>
                <a href="<?php echo esc_url( add_query_arg( 'status', 'success', admin_url( 'admin.php?page=pssg-api-logs' ) ) ); ?>"
                   class="<?php echo $status_filter === 'success' ? 'current' : ''; ?>">
                    <?php echo esc_html__( 'Success', 'product-sync-master-sheet' ); ?>
                    <span class="count">(<?php echo esc_html( $status_counts['success'] ); ?>)</span>
                </a> |
            </li>
            <li>
                <a href="<?php echo esc_url( add_query_arg( 'status', 'error', admin_url( 'admin.php?page=pssg-api-logs' ) ) ); ?>"
                   class="<?php echo $status_filter === 'error' ? 'current' : ''; ?>">
                    <?php echo esc_html__( 'Error', 'product-sync-master-sheet' ); ?>
                    <span class="count">(<?php echo esc_html( $status_counts['error'] ); ?>)</span>
                </a> |
            </li>
            <li>
                <a href="<?php echo esc_url( add_query_arg( 'status', 'unauthorized', admin_url( 'admin.php?page=pssg-api-logs' ) ) ); ?>"
                   class="<?php echo $status_filter === 'unauthorized' ? 'current' : ''; ?>">
                    <?php echo esc_html__( 'Unauthorized', 'product-sync-master-sheet' ); ?>
                    <span class="count">(<?php echo esc_html( $status_counts['unauthorized'] ); ?>)</span>
                </a>
            </li>
        </ul>

        <!-- Search Form -->
        <form method="get" class="pssg-log-search-form">
            <input type="hidden" name="page" value="pssg-api-logs">
            <?php if ( $status_filter ) : ?>
                <input type="hidden" name="status" value="<?php echo esc_attr( $status_filter ); ?>">
            <?php endif; ?>
            <input type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php echo esc_attr__( 'Search logs...', 'product-sync-master-sheet' ); ?>">
            <button type="submit" class="button"><?php echo esc_html__( 'Search', 'product-sync-master-sheet' ); ?></button>
        </form>
    </div>

    <!-- Clear All History Button -->
    <div class="pssg-clear-all-wrapper" style="margin: 10px 0;">
        <form method="post" style="display: inline;">
            <?php wp_nonce_field( 'pssg_log_bulk_action', 'pssg_log_nonce' ); ?>
            <input type="hidden" name="pssg_bulk_action" value="delete_all">
            <button type="submit" class="button button-secondary" onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to clear all API logs? This action cannot be undone.', 'product-sync-master-sheet' ) ); ?>');">
                <span class="dashicons dashicons-trash" style="vertical-align: middle;"></span>
                <?php echo esc_html__( 'Clear All History', 'product-sync-master-sheet' ); ?>
            </button>
        </form>
    </div>

    <!-- Bulk Actions Form -->
    <form method="post" id="pssg-log-bulk-form">
        <?php wp_nonce_field( 'pssg_log_bulk_action', 'pssg_log_nonce' ); ?>
        
        <div class="tablenav top">
            <div class="alignleft actions bulkactions">
                <select name="pssg_bulk_action" id="bulk-action-selector-top">
                    <option value=""><?php echo esc_html__( 'Bulk Actions', 'product-sync-master-sheet' ); ?></option>
                    <option value="delete"><?php echo esc_html__( 'Delete Selected', 'product-sync-master-sheet' ); ?></option>
                    <option value="delete_all"><?php echo esc_html__( 'Delete All', 'product-sync-master-sheet' ); ?></option>
                </select>
                <button type="submit" class="button action" onclick="return confirmBulkAction();"><?php echo esc_html__( 'Apply', 'product-sync-master-sheet' ); ?></button>
            </div>

            <!-- Pagination Top -->
            <?php if ( $total_pages > 1 ) : ?>
            <div class="tablenav-pages">
                <span class="displaying-num"><?php printf( esc_html__( '%s items', 'product-sync-master-sheet' ), number_format_i18n( $total_logs ) ); ?></span>
                <span class="pagination-links">
                    <?php
                    $base_url = admin_url( 'admin.php?page=pssg-api-logs' );
                    if ( $status_filter ) {
                        $base_url = add_query_arg( 'status', $status_filter, $base_url );
                    }
                    if ( $search ) {
                        $base_url = add_query_arg( 's', $search, $base_url );
                    }
                    
                    if ( $current_page > 1 ) :
                    ?>
                        <a class="first-page button" href="<?php echo esc_url( $base_url ); ?>"><span>«</span></a>
                        <a class="prev-page button" href="<?php echo esc_url( add_query_arg( 'paged', $current_page - 1, $base_url ) ); ?>"><span>‹</span></a>
                    <?php else : ?>
                        <span class="first-page button disabled">«</span>
                        <span class="prev-page button disabled">‹</span>
                    <?php endif; ?>
                    
                    <span class="paging-input">
                        <span class="tablenav-paging-text">
                            <?php echo esc_html( $current_page ); ?> / <span class="total-pages"><?php echo esc_html( $total_pages ); ?></span>
                        </span>
                    </span>
                    
                    <?php if ( $current_page < $total_pages ) : ?>
                        <a class="next-page button" href="<?php echo esc_url( add_query_arg( 'paged', $current_page + 1, $base_url ) ); ?>"><span>›</span></a>
                        <a class="last-page button" href="<?php echo esc_url( add_query_arg( 'paged', $total_pages, $base_url ) ); ?>"><span>»</span></a>
                    <?php else : ?>
                        <span class="next-page button disabled">›</span>
                        <span class="last-page button disabled">»</span>
                    <?php endif; ?>
                </span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Logs Table -->
        <table class="wp-list-table widefat fixed striped pssg-logs-table">
            <thead>
                <tr>
                    <td class="manage-column column-cb check-column">
                        <input type="checkbox" id="cb-select-all-1" onclick="toggleAllCheckboxes(this);">
                    </td>
                    <th class="column-id"><?php echo esc_html__( 'ID', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-direction"><?php echo esc_html__( 'Type', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-time"><?php echo esc_html__( 'Time', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-endpoint"><?php echo esc_html__( 'Endpoint', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-status"><?php echo esc_html__( 'Status', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-product"><?php echo esc_html__( 'Product', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-actions"><?php echo esc_html__( 'Actions', 'product-sync-master-sheet' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if ( empty( $logs ) ) : ?>
                    <tr>
                        <td colspan="8" class="no-logs-found">
                            <div class="pssg-no-logs">
                                <i class="pssg_icon-doc-text"></i>
                                <p><?php echo esc_html__( 'No API logs found.', 'product-sync-master-sheet' ); ?></p>
                            </div>
                        </td>
                    </tr>
                <?php else : ?>
                    <?php foreach ( $logs as $log ) : ?>
                        <?php
                        $status_class = 'status-' . esc_attr( $log['status'] );
                        $status_label = ucfirst( $log['status'] );
                        $direction = isset( $log['direction'] ) ? $log['direction'] : Request_Log::DIRECTION_INCOMING;
                        if ( $direction === Request_Log::DIRECTION_OUTGOING ) {
                            $direction_label = __( 'Outgoing', 'product-sync-master-sheet' );
                            $direction_icon  = 'dashicons-upload';
                        } elseif ( $direction === Request_Log::DIRECTION_SCHEDULED ) {
                            $direction_label = __( 'Schedule Sync', 'product-sync-master-sheet' );
                            $direction_icon  = 'dashicons-clock';
                        } else {
                            $direction_label = __( 'Incoming', 'product-sync-master-sheet' );
                            $direction_icon  = 'dashicons-download';
                        }
                        $delete_url = wp_nonce_url( 
                            add_query_arg( [
                                'page' => 'pssg-api-logs',
                                'delete_log' => $log['id'],
                            ], admin_url( 'admin.php' ) ),
                            'pssg_delete_log'
                        );
                        ?>
                        <tr class="<?php echo esc_attr( $status_class ); ?> direction-<?php echo esc_attr( $direction ); ?>">
                            <th class="check-column">
                                <input type="checkbox" name="log_ids[]" value="<?php echo esc_attr( $log['id'] ); ?>">
                            </th>
                            <td class="column-id"><?php echo esc_html( $log['id'] ); ?></td>
                            <td class="column-direction">
                                <span class="direction-badge direction-<?php echo esc_attr( $direction ); ?>" title="<?php echo esc_attr( $direction_label ); ?>">
                                    <span class="dashicons <?php echo esc_attr( $direction_icon ); ?>"></span>
                                    <?php echo esc_html( $direction_label ); ?>
                                </span>
                            </td>
                            <td class="column-time">
                                <span class="log-time" title="<?php echo esc_attr( $log['request_time'] ); ?>">
                                    <?php echo esc_html( human_time_diff( strtotime( $log['request_time'] ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'product-sync-master-sheet' ) ); ?>
                                </span>
                                <br>
                                <small><?php echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $log['request_time'] ) ) ); ?></small>
                            </td>
                            <td class="column-endpoint">
                                <?php 
                                $endpoint = $log['endpoint'];
                                $endpoint_display = strlen($endpoint) > 50 ? substr($endpoint, 0, 47) . '...' : $endpoint;
                                ?>
                                <code title="<?php echo esc_attr( $endpoint ); ?>"><?php echo esc_html( $endpoint_display ); ?></code>
                            </td>
                            <td class="column-status">
                                <span class="status-badge <?php echo esc_attr( $status_class ); ?>">
                                    <?php echo esc_html( $status_label ); ?>
                                </span>
                                <?php if ( !empty( $log['error_message'] ) ) : ?>
                                    <br><small class="error-message" title="<?php echo esc_attr( $log['error_message'] ); ?>"><?php echo esc_html( wp_trim_words( $log['error_message'], 5, '...' ) ); ?></small>
                                <?php endif; ?>
                            </td>
                            <td class="column-product">
                                <?php if ( !empty( $log['product_id'] ) ) : ?>
                                    <a href="<?php echo esc_url( get_edit_post_link( $log['product_id'] ) ); ?>" target="_blank">
                                        #<?php echo esc_html( $log['product_id'] ); ?>
                                    </a>
                                <?php else : ?>
                                    <span class="na">—</span>
                                <?php endif; ?>
                            </td>
                            <td class="column-actions">
                                <a href="#" class="view-details" data-log-id="<?php echo esc_attr( $log['id'] ); ?>" 
                                   data-request="<?php echo esc_attr( $log['request_data'] ); ?>"
                                   data-response="<?php echo esc_attr( $log['response_data'] ); ?>"
                                   title="<?php echo esc_attr__( 'View Details', 'product-sync-master-sheet' ); ?>">
                                    <span class="dashicons dashicons-visibility"></span>
                                </a>
                                <a href="<?php echo esc_url( $delete_url ); ?>" class="delete-log" onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to delete this log?', 'product-sync-master-sheet' ) ); ?>');" title="<?php echo esc_attr__( 'Delete', 'product-sync-master-sheet' ); ?>">
                                    <span class="dashicons dashicons-trash"></span>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td class="manage-column column-cb check-column">
                        <input type="checkbox" id="cb-select-all-2" onclick="toggleAllCheckboxes(this);">
                    </td>
                    <th class="column-id"><?php echo esc_html__( 'ID', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-direction"><?php echo esc_html__( 'Type', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-time"><?php echo esc_html__( 'Time', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-endpoint"><?php echo esc_html__( 'Endpoint', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-status"><?php echo esc_html__( 'Status', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-product"><?php echo esc_html__( 'Product', 'product-sync-master-sheet' ); ?></th>
                    <th class="column-actions"><?php echo esc_html__( 'Actions', 'product-sync-master-sheet' ); ?></th>
                </tr>
            </tfoot>
        </table>
    </form>
</div>

<!-- Log Details Modal -->
<div id="pssg-log-details-modal" class="pssg-modal" style="display:none;">
    <div class="pssg-modal-content">
        <span class="pssg-modal-close">&times;</span>
        <h2><?php echo esc_html__( 'Log Details', 'product-sync-master-sheet' ); ?></h2>
        <div class="pssg-modal-body">
            <div class="log-section">
                <h4><?php echo esc_html__( 'Request Data', 'product-sync-master-sheet' ); ?></h4>
                <pre id="modal-request-data"></pre>
            </div>
            <div class="log-section">
                <h4><?php echo esc_html__( 'Response Data', 'product-sync-master-sheet' ); ?></h4>
                <pre id="modal-response-data"></pre>
            </div>
        </div>
    </div>
</div>

<style>
.pssg-request-log-page .title-count {
    font-size: 14px;
    background: #0073aa;
    color: #fff;
    padding: 2px 10px;
    border-radius: 20px;
    margin-left: 10px;
}
.pssg-log-filters {
    margin: 20px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.pssg-log-filters .subsubsub {
    margin: 0;
    float: none;
}
.pssg-log-search-form {
    display: flex;
    gap: 5px;
}
.pssg-log-search-form input[type="search"] {
    width: 200px;
}
.pssg-logs-table {
    margin-top: 10px;
}
.pssg-logs-table .column-id { width: 50px; }
.pssg-logs-table .column-direction { width: 100px; }
.pssg-logs-table .column-time { width: 140px; }
.pssg-logs-table .column-endpoint { width: 180px; }
.pssg-logs-table .column-status { width: 120px; }
.pssg-logs-table .column-product { width: 70px; }
.pssg-logs-table .column-actions { width: 80px; text-align: center; }

.direction-badge {
    display: inline-flex;
    align-items: center;
    gap: 3px;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
}
.direction-badge .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}
.direction-badge.direction-incoming {
    background: #e3f2fd;
    color: #1565c0;
}
.direction-badge.direction-outgoing {
    background: #e8f5e9;
    color: #2e7d32;
}
.direction-badge.direction-scheduled {
    background: #f3e5f5;
    color: #6a1b9a;
}

.status-badge {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
}
.status-badge.status-success { background: #d4edda; color: #155724; }
.status-badge.status-error { background: #f8d7da; color: #721c24; }
.status-badge.status-unauthorized { background: #fff3cd; color: #856404; }
.status-badge.status-processing { background: #cce5ff; color: #004085; }
.status-badge.status-pending { background: #e2e3e5; color: #383d41; }

.column-actions a {
    margin: 0 3px;
    color: #0073aa;
    text-decoration: none;
}
.column-actions a .dashicons {
    font-size: 18px;
    width: 18px;
    height: 18px;
}
.column-actions a:hover {
    color: #005177;
}
.column-actions .delete-log:hover {
    color: #dc3545;
}

.pssg-no-logs {
    text-align: center;
    padding: 50px;
    color: #999;
}
.pssg-no-logs i {
    font-size: 48px;
    display: block;
    margin-bottom: 10px;
}

/* Modal Styles */
.pssg-modal {
    position: fixed;
    z-index: 100000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}
.pssg-modal-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 20px;
    border-radius: 8px;
    width: 80%;
    max-width: 800px;
    max-height: 80vh;
    overflow-y: auto;
    position: relative;
}
.pssg-modal-close {
    position: absolute;
    right: 15px;
    top: 10px;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}
.pssg-modal-close:hover {
    color: #dc3545;
}
.log-section {
    margin-bottom: 20px;
}
.log-section h4 {
    margin: 0 0 10px 0;
    padding-bottom: 5px;
    border-bottom: 1px solid #ddd;
}
.log-section pre {
    background: #f5f5f5;
    padding: 15px;
    border-radius: 5px;
    overflow-x: auto;
    max-height: 200px;
    font-size: 12px;
}
</style>

<script>
function toggleAllCheckboxes(source) {
    var checkboxes = document.querySelectorAll('input[name="log_ids[]"]');
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = source.checked;
    }
}

function confirmBulkAction() {
    var action = document.getElementById('bulk-action-selector-top').value;
    if (action === 'delete_all') {
        return confirm('<?php echo esc_js( __( 'Are you sure you want to delete ALL logs? This action cannot be undone.', 'product-sync-master-sheet' ) ); ?>');
    }
    if (action === 'delete') {
        var checked = document.querySelectorAll('input[name="log_ids[]"]:checked');
        if (checked.length === 0) {
            alert('<?php echo esc_js( __( 'Please select at least one log to delete.', 'product-sync-master-sheet' ) ); ?>');
            return false;
        }
        return confirm('<?php echo esc_js( __( 'Are you sure you want to delete the selected logs?', 'product-sync-master-sheet' ) ); ?>');
    }
    return true;
}

// Modal functionality
document.addEventListener('DOMContentLoaded', function() {
    var modal = document.getElementById('pssg-log-details-modal');
    var closeBtn = document.querySelector('.pssg-modal-close');
    
    // View details click
    document.querySelectorAll('.view-details').forEach(function(link) {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            var requestData = this.getAttribute('data-request');
            var responseData = this.getAttribute('data-response');
            
            try {
                requestData = JSON.stringify(JSON.parse(requestData), null, 2);
            } catch(e) {}
            
            try {
                responseData = JSON.stringify(JSON.parse(responseData), null, 2);
            } catch(e) {}
            
            document.getElementById('modal-request-data').textContent = requestData || 'N/A';
            document.getElementById('modal-response-data').textContent = responseData || 'N/A';
            
            modal.style.display = 'block';
        });
    });
    
    // Close modal
    closeBtn.addEventListener('click', function() {
        modal.style.display = 'none';
    });
    
    window.addEventListener('click', function(e) {
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    });
});
</script>
