<?php
/**
 * Logs admin page – displays wp_skyemag_logs with filters and pagination.
 *
 * @package SkyEmagSync
 */

namespace SkyEmagSync\Admin;

use SkyEmagSync\Options;
use SkyEmagSync\Plugin;
use SkyEmagSync\Sync\Logger;

defined( 'ABSPATH' ) || exit;

class LogsPage {

    const PRUNE_ACTION = 'skyemag_prune_logs';
    const PRUNE_NONCE  = 'skyemag_prune_logs_nonce';
    const PER_PAGE     = 50;

    public function register(): void {
        add_action( 'admin_init', [ $this, 'handle_prune' ] );
    }

    public function handle_prune(): void {
        if ( ! isset( $_POST[ self::PRUNE_NONCE ] ) ) {
            return;
        }
        check_admin_referer( self::PRUNE_ACTION, self::PRUNE_NONCE );
        if ( ! current_user_can( Menu::CAPABILITY ) ) {
            wp_die( esc_html__( 'Unauthorized.', 'skyservers-product-sync-for-emag' ) );
        }
        $days = isset( $_POST['prune_days'] ) ? max( 1, absint( wp_unslash( $_POST['prune_days'] ) ) ) : 30;
        Logger::prune( $days );
        wp_safe_redirect( add_query_arg(
            [ 'page' => Menu::LOGS_SLUG, 'skyemag_pruned' => 1 ],
            admin_url( 'admin.php' )
        ) );
        exit;
    }

    public static function render(): void {
        if ( ! current_user_can( Menu::CAPABILITY ) ) {
            return;
        }

        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only pagination/filter state, no state mutation.
        $current_page  = isset( $_GET['paged'] ) ? max( 1, absint( wp_unslash( $_GET['paged'] ) ) ) : 1;
        $filter_result = isset( $_GET['result'] ) ? sanitize_key( wp_unslash( $_GET['result'] ) ) : '';
        $filter_action = isset( $_GET['action_filter'] ) ? sanitize_key( wp_unslash( $_GET['action_filter'] ) ) : '';
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        $filters = [
            'limit'  => self::PER_PAGE,
            'offset' => ( $current_page - 1 ) * self::PER_PAGE,
        ];
        if ( $filter_result ) {
            $filters['result'] = $filter_result;
        }
        if ( $filter_action ) {
            $filters['action'] = $filter_action;
        }

        $logs       = Logger::get_logs( $filters );
        $total      = Logger::count_logs( array_diff_key( $filters, [ 'limit' => 0, 'offset' => 0 ] ) );
        $total_pages = (int) ceil( $total / self::PER_PAGE );
        $base_url   = admin_url( 'admin.php?page=' . Menu::LOGS_SLUG );
        ?>
        <div class="wrap skyemag-logs-wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e( 'SkyServers Sync — Logs', 'skyservers-product-sync-for-emag' ); ?></h1>

            <?php
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only flash flag for the success notice, value not consumed.
            if ( ! empty( $_GET['skyemag_pruned'] ) ) : ?>
                <div class="notice notice-success is-dismissible">
                    <p><?php esc_html_e( 'Old logs have been deleted.', 'skyservers-product-sync-for-emag' ); ?></p>
                </div>
            <?php endif; ?>

            <?php self::render_retention_banner(); ?>

            <!-- Filters -->
            <form method="get" style="margin: 12px 0; display:flex; gap:8px; align-items:center;">
                <input type="hidden" name="page" value="<?php echo esc_attr( Menu::LOGS_SLUG ); ?>" />

                <select name="result" onchange="this.form.submit()">
                    <option value=""><?php esc_html_e( 'Toate rezultatele', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="success" <?php selected( $filter_result, 'success' ); ?>><?php esc_html_e( 'Success', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="fail"    <?php selected( $filter_result, 'fail' ); ?>><?php esc_html_e( 'Error', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="skip"   <?php selected( $filter_result, 'skip' ); ?>><?php esc_html_e( 'Skipped', 'skyservers-product-sync-for-emag' ); ?></option>
                </select>

                <select name="action_filter" onchange="this.form.submit()">
                    <option value=""><?php esc_html_e( 'All actions', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="price+stock" <?php selected( $filter_action, 'price+stock' ); ?>><?php esc_html_e( 'Price + Stock', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="price"       <?php selected( $filter_action, 'price' ); ?>><?php esc_html_e( 'Price', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="stock"       <?php selected( $filter_action, 'stock' ); ?>><?php esc_html_e( 'Stock', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="bootstrap"   <?php selected( $filter_action, 'bootstrap' ); ?>><?php esc_html_e( 'Import', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="sanitize"    <?php selected( $filter_action, 'sanitize' ); ?>><?php esc_html_e( 'Sanitize', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="notify"      <?php selected( $filter_action, 'notify' ); ?>><?php esc_html_e( 'Notification', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="skip"        <?php selected( $filter_action, 'skip' ); ?>><?php esc_html_e( 'Skipped', 'skyservers-product-sync-for-emag' ); ?></option>
                    <option value="<?php echo esc_attr( Logger::ACTION_AWB ); ?>" <?php selected( $filter_action, Logger::ACTION_AWB ); ?>><?php esc_html_e( 'AWB', 'skyservers-product-sync-for-emag' ); ?></option>
                </select>

                <?php if ( $filter_result || $filter_action ) : ?>
                    <a href="<?php echo esc_url( $base_url ); ?>" class="button button-secondary">
                        <?php esc_html_e( 'Reset filters', 'skyservers-product-sync-for-emag' ); ?>
                    </a>
                <?php endif; ?>

                <span style="margin-left:auto; color:#50575e;">
                    <?php printf(
                        /* translators: %1$d: number */
                        esc_html__( '%d entries', 'skyservers-product-sync-for-emag' ),
                        esc_html( $total )
                    ); ?>
                </span>
            </form>

            <!-- Logs table -->
            <table class="wp-list-table widefat fixed striped skyemag-logs-table">
                <thead>
                    <tr>
                        <th style="width:155px"><?php esc_html_e( 'Data/Ora', 'skyservers-product-sync-for-emag' ); ?></th>
                        <th style="width:80px"><?php esc_html_e( 'Rezultat', 'skyservers-product-sync-for-emag' ); ?></th>
                        <th style="width:90px"><?php esc_html_e( 'Action', 'skyservers-product-sync-for-emag' ); ?></th>
                        <th style="width:180px"><?php esc_html_e( 'Produs', 'skyservers-product-sync-for-emag' ); ?></th>
                        <th><?php esc_html_e( 'Mesaj', 'skyservers-product-sync-for-emag' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php if ( empty( $logs ) ) : ?>
                    <tr>
                        <td colspan="5" style="text-align:center; padding:20px;">
                            <?php esc_html_e( 'No logs found.', 'skyservers-product-sync-for-emag' ); ?>
                        </td>
                    </tr>
                <?php else : ?>
                    <?php foreach ( $logs as $log ) :
                        $product_id   = (int) $log['product_id'];
                        $product_name = '';
                        if ( $product_id > 0 ) {
                            $product = wc_get_product( $product_id );
                            $product_name = $product ? $product->get_name() : "#{$product_id}";
                        }
                        switch ( $log['result'] ) {
                            case 'success':
                                $result_class = 'skyemag-badge--success';
                                break;
                            case 'fail':
                                $result_class = 'skyemag-badge--error';
                                break;
                            default:
                                $result_class = 'skyemag-badge--pending';
                        }
                    ?>
                    <tr>
                        <td>
                            <span title="<?php echo esc_attr( $log['created_at'] ); ?>">
                                <?php echo esc_html( $log['created_at'] ); ?>
                            </span>
                        </td>
                        <td>
                            <span class="skyemag-badge <?php echo esc_attr( $result_class ); ?>">
                                <?php echo esc_html( $log['result'] ); ?>
                            </span>
                        </td>
                        <td><?php echo esc_html( $log['action'] ); ?></td>
                        <td>
                            <?php if ( $product_id > 0 ) : ?>
                                <a href="<?php echo esc_url( get_edit_post_link( $product_id ) ); ?>">
                                    <?php echo esc_html( $product_name ); ?>
                                </a>
                            <?php else : ?>
                                <span class="skyemag-na">—</span>
                            <?php endif; ?>
                        </td>
                        <td style="font-family:monospace; font-size:12px;">
                            <?php echo esc_html( $log['message'] ); ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>

            <!-- Pagination -->
            <?php if ( $total_pages > 1 ) : ?>
                <div class="tablenav bottom" style="margin-top:8px;">
                    <div class="tablenav-pages">
                        <?php
                        $page_links = paginate_links( [
                            'base'      => add_query_arg( 'paged', '%#%', $base_url ),
                            'format'    => '',
                            'prev_text' => '&laquo;',
                            'next_text' => '&raquo;',
                            'total'     => $total_pages,
                            'current'   => $current_page,
                        ] );
                        if ( $page_links ) {
                            // paginate_links() returns trusted markup, but
                            // run it through wp_kses_post anyway so Plugin
                            // Check stops flagging it during WP.org review.
                            echo wp_kses_post( $page_links );
                        }
                        ?>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Prune form -->
            <hr style="margin-top:24px;" />
            <h3><?php esc_html_e( 'Clean old logs', 'skyservers-product-sync-for-emag' ); ?></h3>
            <p class="description">
                <?php esc_html_e( 'One-off manual prune. The daily auto-prune already runs in the background using the configured retention.', 'skyservers-product-sync-for-emag' ); ?>
            </p>
            <form method="post" action="" style="display:flex; gap:8px; align-items:center;">
                <?php wp_nonce_field( self::PRUNE_ACTION, self::PRUNE_NONCE ); ?>
                <label>
                    <?php esc_html_e( 'Delete logs older than', 'skyservers-product-sync-for-emag' ); ?>
                    <input type="number" name="prune_days" value="<?php echo (int) Options::log_retention_days(); ?>" min="1" max="365"
                        style="width:60px; margin:0 4px;" />
                    <?php esc_html_e( 'zile', 'skyservers-product-sync-for-emag' ); ?>
                </label>
                <?php submit_button( __( 'Delete', 'skyservers-product-sync-for-emag' ), 'secondary', 'skyemag_prune_submit', false ); ?>
            </form>
        </div>
        <?php
    }

    /**
     * Info banner showing the current log-retention policy and a link
     * to the Settings page where the value can be changed.
     */
    private static function render_retention_banner(): void {
        $retention    = (int) Options::log_retention_days();
        $settings_url = admin_url( 'admin.php?page=' . Menu::SETTINGS_SLUG );
        ?>
        <div class="notice notice-info" style="margin-top:12px;">
            <p>
                <strong><?php esc_html_e( 'Log retention:', 'skyservers-product-sync-for-emag' ); ?></strong>
                <?php
                printf(
                    /* translators: %d: retention days */
                    esc_html__( 'logs older than %d days are deleted daily.', 'skyservers-product-sync-for-emag' ),
                    (int) $retention
                );
                ?>
                <a href="<?php echo esc_url( $settings_url ); ?>#skyemag_log_retention_days"><?php esc_html_e( 'Change in Settings →', 'skyservers-product-sync-for-emag' ); ?></a>
            </p>
        </div>
        <?php
    }

}
