<?php

declare(strict_types=1);

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
?>
<?php
    $prodexfo_page_slug_value = 'badamsoft-product-exporter-for-woocommerce-history';

    $prodexfo_pagination = isset( $history_pagination ) ? $history_pagination : [
        'total'    => count( $runs ),
        'current'  => 1,
        'per_page' => 20,
        'pages'    => 1,
        'offset'   => 0,
        'page_slug' => $prodexfo_page_slug_value ?: 'badamsoft-product-exporter-for-woocommerce-history',
        'query_args' => [
            'history_status'   => $filters['status'] ?? '',
            'history_template' => $filters['template_id'] ?? '',
            'history_per_page' => 20,
        ],
    ];

    $prodexfo_per_page_value = isset( $prodexfo_pagination['per_page'] ) ? (int) $prodexfo_pagination['per_page'] : 20;
?>
<div class="wrap wc-pce-export-history">
    <h1><?php esc_html_e( 'Export History', 'badamsoft-product-exporter-for-woocommerce' ); ?></h1>
    <p class="description"><?php esc_html_e( 'Review recent export runs, download files, and inspect logs.', 'badamsoft-product-exporter-for-woocommerce' ); ?></p>

    <?php settings_errors( 'prodexfo_history' ); ?>

    <form method="get" class="wc-pce-export-history__filters">
        <?php wp_nonce_field( 'prodexfo_history_filters', 'prodexfo_history_filters_nonce', false ); ?>
        <input type="hidden" name="page" value="<?php echo esc_attr( $prodexfo_page_slug_value ); ?>" />
        <input type="hidden" name="history_page" value="1" />
        <label>
            <?php esc_html_e( 'Status', 'badamsoft-product-exporter-for-woocommerce' ); ?>
            <select name="history_status">
                <option value=""><?php esc_html_e( 'Any', 'badamsoft-product-exporter-for-woocommerce' ); ?></option>
                <option value="success" <?php selected( 'success', $filters['status'] ?? '' ); ?>><?php esc_html_e( 'Success', 'badamsoft-product-exporter-for-woocommerce' ); ?></option>
                <option value="failed" <?php selected( 'failed', $filters['status'] ?? '' ); ?>><?php esc_html_e( 'Failed', 'badamsoft-product-exporter-for-woocommerce' ); ?></option>
            </select>
        </label>
        <label>
            <?php esc_html_e( 'Template', 'badamsoft-product-exporter-for-woocommerce' ); ?>
            <select name="history_template">
                <option value=""><?php esc_html_e( 'Any', 'badamsoft-product-exporter-for-woocommerce' ); ?></option>
                <?php foreach ( $templates as $prodexfo_template ) : ?>
                    <option value="<?php echo esc_attr( $prodexfo_template['id'] ); ?>" <?php selected( $prodexfo_template['id'], $filters['template_id'] ?? '' ); ?>>
                        <?php echo esc_html( $prodexfo_template['name'] ?? $prodexfo_template['id'] ); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </label>
        <label>
            <?php esc_html_e( 'Run type', 'badamsoft-product-exporter-for-woocommerce' ); ?>
            <select name="history_run_type">
                <option value=""><?php esc_html_e( 'Any', 'badamsoft-product-exporter-for-woocommerce' ); ?></option>
                <option value="manual" <?php selected( 'manual', $filters['run_type'] ?? '' ); ?>><?php esc_html_e( 'Manual', 'badamsoft-product-exporter-for-woocommerce' ); ?></option>
                <option value="scheduled" <?php selected( 'scheduled', $filters['run_type'] ?? '' ); ?>><?php esc_html_e( 'Scheduled', 'badamsoft-product-exporter-for-woocommerce' ); ?></option>
            </select>
        </label>
        <label>
            <?php esc_html_e( 'Date from', 'badamsoft-product-exporter-for-woocommerce' ); ?>
            <input type="date" name="history_date_from" value="<?php echo esc_attr( $filters['date_from'] ?? '' ); ?>" />
        </label>
        <label>
            <?php esc_html_e( 'Date to', 'badamsoft-product-exporter-for-woocommerce' ); ?>
            <input type="date" name="history_date_to" value="<?php echo esc_attr( $filters['date_to'] ?? '' ); ?>" />
        </label>
        <label>
            <?php esc_html_e( 'Per page', 'badamsoft-product-exporter-for-woocommerce' ); ?>
            <select name="history_per_page">
                <option value="20" <?php selected( 20, $prodexfo_per_page_value ); ?>>20</option>
                <option value="50" <?php selected( 50, $prodexfo_per_page_value ); ?>>50</option>
            </select>
        </label>
        <button type="submit" class="button"><?php esc_html_e( 'Filter', 'badamsoft-product-exporter-for-woocommerce' ); ?></button>
    </form>

    <table class="widefat fixed striped">
        <thead>
            <tr>
                <th><?php esc_html_e( 'Date', 'badamsoft-product-exporter-for-woocommerce' ); ?></th>
                <th><?php esc_html_e( 'Task / Template', 'badamsoft-product-exporter-for-woocommerce' ); ?></th>
                <th><?php esc_html_e( 'Run type', 'badamsoft-product-exporter-for-woocommerce' ); ?></th>
                <th><?php esc_html_e( 'Status', 'badamsoft-product-exporter-for-woocommerce' ); ?></th>
                <th><?php esc_html_e( 'Rows', 'badamsoft-product-exporter-for-woocommerce' ); ?></th>
                <th><?php esc_html_e( 'File', 'badamsoft-product-exporter-for-woocommerce' ); ?></th>
                <th><?php esc_html_e( 'Actions', 'badamsoft-product-exporter-for-woocommerce' ); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php if ( empty( $runs ) ) : ?>
                <tr>
                    <td colspan="7"><?php esc_html_e( 'No runs recorded yet.', 'badamsoft-product-exporter-for-woocommerce' ); ?></td>
                </tr>
            <?php else : ?>
                <?php foreach ( $runs as $prodexfo_run ) : ?>
                    <tr>
                        <td>
                            <?php
                            $prodexfo_started_at_raw = isset( $prodexfo_run['started_at'] ) ? trim( (string) $prodexfo_run['started_at'] ) : '';
                            $prodexfo_started_at     = '—';

                            if ( '' !== $prodexfo_started_at_raw ) {
                                $prodexfo_ts = strtotime( $prodexfo_started_at_raw . ' UTC' );

                                if ( false !== $prodexfo_ts ) {
                                    $prodexfo_started_at = wp_date( 'Y-m-d H:i:s', $prodexfo_ts, wp_timezone() );
                                } else {
                                    $prodexfo_started_at = $prodexfo_started_at_raw;
                                }
                            }
                            echo esc_html( $prodexfo_started_at );
                            ?>
                        </td>
                        <td>
                            <?php
                            printf(
                                '%s (#%d)',
                                esc_html( $prodexfo_run['template_id'] ?? '—' ),
                                isset( $prodexfo_run['task_id'] ) ? (int) $prodexfo_run['task_id'] : 0
                            );
                            ?>
                        </td>
                        <td>
                            <?php
                            $prodexfo_run_type_key   = isset( $prodexfo_run['run_type'] ) ? sanitize_key( $prodexfo_run['run_type'] ) : '';
                            $prodexfo_run_type_label = $prodexfo_run_type_key === 'manual'
                                ? esc_html__( 'Manual', 'badamsoft-product-exporter-for-woocommerce' )
                                : esc_html__( 'Scheduled', 'badamsoft-product-exporter-for-woocommerce' );
                            echo esc_html( $prodexfo_run_type_label );
                            ?>
                        </td>
                        <td>
                            <?php if ( 'success' === ( $prodexfo_run['status'] ?? '' ) ) : ?>
                                <span class="status status-success"><?php esc_html_e( 'Success', 'badamsoft-product-exporter-for-woocommerce' ); ?></span>
                            <?php elseif ( 'failed' === ( $prodexfo_run['status'] ?? '' ) ) : ?>
                                <span class="status status-error"><?php esc_html_e( 'Failed', 'badamsoft-product-exporter-for-woocommerce' ); ?></span>
                            <?php else : ?>
                                <span class="status status-info"><?php echo esc_html( $prodexfo_run['status'] ?? '—' ); ?></span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo isset( $prodexfo_run['rows_exported'] ) ? (int) $prodexfo_run['rows_exported'] : 0; ?></td>
                        <td>
                            <?php
                            $prodexfo_has_main_file = ! empty( $prodexfo_run['file_path'] );
                            $prodexfo_zip_url       = ! empty( $prodexfo_run['images_zip_url'] ) ? $prodexfo_run['images_zip_url'] : ( $prodexfo_run['images_zip_path'] ?? '' );
                            ?>
                            <?php if ( $prodexfo_has_main_file ) : ?>
                                <a class="button button-small" href="<?php echo esc_url( $prodexfo_run['file_path'] ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Download', 'badamsoft-product-exporter-for-woocommerce' ); ?></a>
                            <?php endif; ?>

                            <?php if ( $prodexfo_zip_url ) : ?>
                                <a class="button button-small" href="<?php echo esc_url( $prodexfo_zip_url ); ?>" target="_blank" rel="noopener noreferrer">
                                    <?php esc_html_e( 'Download images ZIP', 'badamsoft-product-exporter-for-woocommerce' ); ?>
                                    <?php if ( ! empty( $prodexfo_run['images_zip_size'] ) ) : ?>
                                        <span class="description">
                                            (<?php echo esc_html( size_format( (int) $prodexfo_run['images_zip_size'] ) ); ?>)
                                        </span>
                                    <?php endif; ?>
                                </a>
                            <?php endif; ?>

                            <?php if ( ! $prodexfo_has_main_file && ! $prodexfo_zip_url ) : ?>
                                —
                            <?php endif; ?>
                        </td>
                        <td class="wc-pce-export-history__actions">
                            <form method="post">
                                <?php wp_nonce_field( 'prodexfo_history_action', 'prodexfo_history_nonce' ); ?>
                                <input type="hidden" name="run_id" value="<?php echo (int) $prodexfo_run['id']; ?>" />
                                <button class="button button-small" name="prodexfo_history_action" value="retry_actions"><?php esc_html_e( 'Retry actions', 'badamsoft-product-exporter-for-woocommerce' ); ?></button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

    <?php
    $prodexfo_total_runs   = isset( $prodexfo_pagination['total'] ) ? (int) $prodexfo_pagination['total'] : count( $runs );
    $prodexfo_current_page = isset( $prodexfo_pagination['current'] ) ? (int) $prodexfo_pagination['current'] : 1;
    $prodexfo_pages_total  = isset( $prodexfo_pagination['pages'] ) ? (int) $prodexfo_pagination['pages'] : 1;
    $prodexfo_offset       = isset( $prodexfo_pagination['offset'] ) ? (int) $prodexfo_pagination['offset'] : 0;

    if ( $prodexfo_total_runs > 0 ) {
        $prodexfo_range_start = $prodexfo_offset + 1;
        $prodexfo_range_end   = $prodexfo_offset + count( $runs );
    } else {
        $prodexfo_range_start = 0;
        $prodexfo_range_end   = 0;
    }

    if ( $prodexfo_pages_total > 1 && $prodexfo_pagination['page_slug'] ) :
        $prodexfo_base_args = array_merge(
            [ 'page' => $prodexfo_pagination['page_slug'] ],
            array_filter( $prodexfo_pagination['query_args'] )
        );
        $prodexfo_base_url = add_query_arg( $prodexfo_base_args, admin_url( 'admin.php' ) );
        $prodexfo_paginate_links = paginate_links(
            [
                'base'      => add_query_arg( 'history_page', '%#%', $prodexfo_base_url ),
                'format'    => '',
                'current'   => $prodexfo_current_page,
                'total'     => $prodexfo_pages_total,
                'type'      => 'array',
                'prev_next' => true,
            ]
        );
    else :
        $prodexfo_paginate_links = [];
    endif;
    ?>

    <div class="wc-pce-pagination">
        <div class="wc-pce-pagination__summary">
            <?php if ( $prodexfo_total_runs > 0 ) : ?>
                <?php
                printf(
                    /* translators: 1: first run number, 2: last run number, 3: total number of export runs */
                    esc_html__( 'Showing %1$d–%2$d of %3$d export runs', 'badamsoft-product-exporter-for-woocommerce' ),
                    (int) $prodexfo_range_start,
                    (int) $prodexfo_range_end,
                    (int) $prodexfo_total_runs
                );
                ?>
            <?php else : ?>
                <?php esc_html_e( 'No export runs to display.', 'badamsoft-product-exporter-for-woocommerce' ); ?>
            <?php endif; ?>
        </div>
        <?php if ( ! empty( $prodexfo_paginate_links ) ) : ?>
            <nav class="wc-pce-pagination__nav" aria-label="<?php esc_attr_e( 'Export history pagination', 'badamsoft-product-exporter-for-woocommerce' ); ?>">
                <ul class="wc-pce-pagination__links">
                    <?php foreach ( $prodexfo_paginate_links as $link ) : ?>
                        <li><?php echo wp_kses_post( $link ); ?></li>
                    <?php endforeach; ?>
                </ul>
            </nav>
        <?php endif; ?>
    </div>
</div>
