<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

$drafts = get_option( 'mt_primelink_import_drafts', array() );
$drafts = is_array( $drafts ) ? $drafts : array();

// Group imports by type
$imports_by_type = array(
    'products'  => array( 'manual' => array(), 'scheduled' => array() ),
    'orders'    => array( 'manual' => array(), 'scheduled' => array() ),
    'customers' => array( 'manual' => array(), 'scheduled' => array() ),
    'coupons'   => array( 'manual' => array(), 'scheduled' => array() ),
    'categories' => array( 'manual' => array(), 'scheduled' => array() ),
    'tags' => array( 'manual' => array(), 'scheduled' => array() ),
    'attributes' => array( 'manual' => array(), 'scheduled' => array() ),
    'variations' => array( 'manual' => array(), 'scheduled' => array() ),
    'reviews' => array( 'manual' => array(), 'scheduled' => array() ),
    'downloads' => array( 'manual' => array(), 'scheduled' => array() ),
);

foreach ( $drafts as $id => $draft ) {
    $state     = get_option( 'mt_primelink_import_state_' . absint( $id ), array() );
    $status    = $state['status'] ?? 'idle';
    $progress  = isset( $state['progress'] ) ? (int) $state['progress'] : 0;
    $current   = isset( $state['current'] ) ? (int) $state['current'] : 0;
    $total     = isset( $state['total'] ) ? (int) $state['total'] : 0;
    $schedule  = $draft['step_data'][6]['schedule'] ?? array();
    $is_sched  = ! empty( $schedule['enabled'] );
    $interval  = $schedule['interval'] ?? '';
    $start     = $schedule['start_time'] ?? '';
    
    // Get import type
    $import_type = $draft['type'] ?? ($draft['step_data'][1]['type'] ?? 'product');
    // Normalize type
    if ( $import_type === 'order' ) {
        $import_type = 'orders';
    } elseif ( $import_type === 'customer' ) {
        $import_type = 'customers';
    } elseif ( $import_type === 'coupon' ) {
        $import_type = 'coupons';
    } elseif ( $import_type === 'category' ) {
        $import_type = 'categories';
    } elseif ( $import_type === 'tag' ) {
        $import_type = 'tags';
    } elseif ( $import_type === 'attribute' ) {
        $import_type = 'attributes';
        } elseif ( $import_type === 'variation' ) {
            $import_type = 'variations';
        } elseif ( $import_type === 'review' ) {
            $import_type = 'reviews';
        } elseif ( $import_type === 'download' ) {
            $import_type = 'downloads';
        } elseif ( $import_type === 'product' ) {
        $import_type = 'products';
    }
    // Default to products if unknown
    if ( !isset($imports_by_type[$import_type]) ) {
        $import_type = 'products';
    }

    $row = array(
        'id'        => $id,
        'created'   => $draft['created_at'] ?? '',
        'step'      => $draft['current_step'] ?? 1,
        'status'    => $status,
        'progress'  => $progress,
        'current'   => $current,
        'total'     => $total,
        'interval'  => $interval,
        'start'     => $start,
        'sched_on'  => $is_sched,
        'type'      => $import_type,
    );

    $category = $is_sched ? 'scheduled' : 'manual';
    $imports_by_type[$import_type][$category][] = $row;
}

$sort = function( $a, $b ) {
    $at = strtotime( $a['created'] ?? '' );
    $bt = strtotime( $b['created'] ?? '' );
    return $bt <=> $at;
};

// Sort each category
foreach ( $imports_by_type as $type => $categories ) {
    usort( $imports_by_type[$type]['manual'], $sort );
    usort( $imports_by_type[$type]['scheduled'], $sort );
}
?>
<div class="wrap mt-primelink-wrap">
    <?php
    ob_start();
    ?>
    <button type="button" class="button mt_primelink-imports-refresh" id="mt_primelink-imports-refresh" title="<?php esc_attr_e( 'Refresh', 'primelink' ); ?>">
        <span class="dashicons dashicons-update"></span>
    </button>
    <a href="<?php echo esc_url( admin_url( 'admin.php?page=mt-primelink-new-import' ) ); ?>" class="button button-primary">
        <?php esc_html_e( 'New Import', 'primelink' ); ?>
    </a>
    <?php
    $header_actions     = ob_get_clean();
    $header_eyebrow     = __( 'Imports Hub', 'primelink' );
    $header_title       = __( 'Manage Imports', 'primelink' );
    $header_description = __( 'View progress, resume paused jobs, or jump back into the wizard.', 'primelink' );

    include MT_PRIMELINK_PATH . 'templates/admin/partials/header.php';
    ?>

    <div class="mt_primelink-settings-tabs">
        <button class="button mt_primelink-tab-btn is-active" data-tab="products"><?php esc_html_e( 'Products', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="orders"><?php esc_html_e( 'Orders', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="customers"><?php esc_html_e( 'Customers', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="coupons"><?php esc_html_e( 'Coupons', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="categories"><?php esc_html_e( 'Categories', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="tags"><?php esc_html_e( 'Tags', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="attributes"><?php esc_html_e( 'Attributes', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="variations"><?php esc_html_e( 'Variations', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="reviews"><?php esc_html_e( 'Reviews', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="downloads"><?php esc_html_e( 'Downloads', 'primelink' ); ?></button>
    </div>

    <?php
    $type_labels = array(
        'products'  => __( 'Products', 'primelink' ),
        'orders'    => __( 'Orders', 'primelink' ),
        'customers' => __( 'Customers', 'primelink' ),
        'coupons'   => __( 'Coupons', 'primelink' ),
        'categories' => __( 'Categories', 'primelink' ),
        'tags' => __( 'Tags', 'primelink' ),
    'attributes' => __( 'Attributes', 'primelink' ),
    'variations' => __( 'Variations', 'primelink' ),
    'reviews' => __( 'Reviews', 'primelink' ),
    'downloads' => __( 'Downloads', 'primelink' ),
    );
    
    $delete_labels = array(
        'products'  => __( 'Delete products', 'primelink' ),
        'orders'    => __( 'Delete orders', 'primelink' ),
        'customers' => __( 'Delete customers', 'primelink' ),
        'coupons'   => __( 'Delete coupons', 'primelink' ),
    );
    
    foreach ( $imports_by_type as $type => $categories ) :
        $manual_rows = $categories['manual'];
        $scheduled_rows = $categories['scheduled'];
        $is_first = ( $type === 'products' );
    ?>
    <div class="mt_primelink-dash-panel glass mt_primelink-tab-panel <?php echo $is_first ? 'is-active' : ''; ?>" data-tab-panel="<?php echo esc_attr( $type ); ?>">
        <div class="mt_primelink-dash-panel__header">
            <div>
                <div class="mt_primelink-summary-eyebrow"><?php echo esc_html( $type_labels[$type] ); ?></div>
                <h3><?php echo esc_html( $type_labels[$type] . ' Imports' ); ?></h3>
            </div>
        </div>

        <!-- Manual Imports -->
        <div class="mt_primelink-import-section">
            <h4><?php esc_html_e( 'Manual Imports', 'primelink' ); ?></h4>
            <?php if ( empty( $manual_rows ) ) : ?>
                <div class="mt_primelink-empty"><?php esc_html_e( 'No manual imports yet.', 'primelink' ); ?></div>
            <?php else : ?>
                <div class="mt_primelink-table-wrapper">
                <table class="mt_primelink-dash-table mt_primelink-imports-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'ID', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Created', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Step', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Status', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Progress', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Actions', 'primelink' ); ?></th>
                        <th class="mt_primelink-checkbox-col">
                            <label class="mt_primelink-checkbox-label">
                                <input type="checkbox" class="mt_primelink-imports-select-all" data-type="<?php echo esc_attr( $type ); ?>" />
                                <span class="muted"><?php esc_html_e( 'All', 'primelink' ); ?></span>
                            </label>
                        </th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $manual_rows as $row ) : ?>
                            <?php
                                $progress = max( 0, min( 100, (int) $row['progress'] ) );
                                $current  = (int) $row['current'];
                                $total    = (int) $row['total'];
                                $status   = $row['status'] ? $row['status'] : 'idle';
                                $step     = (int) $row['step'];
                                $anomalies_data = get_post_meta( $row['id'], '_mt_primelink_anomalies', true );
                                $anomalies_count = is_array( $anomalies_data ) ? count( $anomalies_data ) : 0;
                                $wizard_url = add_query_arg(
                                    array( 'page' => 'mt-primelink-new-import', 'import_id' => $row['id'], 'step' => $step, 'import_type' => $row['type'] ),
                                    admin_url( 'admin.php' )
                                );
                            ?>
                            <tr class="mt_primelink-import-row" data-id="<?php echo esc_attr( $row['id'] ); ?>" data-type="<?php echo esc_attr( $type ); ?>">
                                <td>#<?php echo (int) $row['id']; ?></td>
                                <td><?php echo $row['created'] ? esc_html( $row['created'] ) : '&mdash;'; ?></td>
                                <td><?php echo $step; ?></td>
                                <td>
                                    <span class="mt_primelink-status-pill mt_primelink-status-<?php echo esc_attr( $status ); ?>">
                                        <?php echo esc_html( ucfirst( $status ) ); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="mt_primelink-dash-progress">
                                        <div class="mt_primelink-dash-progress__bar" style="width:<?php echo $progress; ?>%;"></div>
                                    </div>
                                    <small class="muted">
                                        <?php echo esc_html( $current . ' / ' . $total ); ?>
                                    </small>
                                </td>
                                <td class="mt_primelink-import-actions">
                                    <a class="button" href="<?php echo esc_url( $wizard_url ); ?>">
                                        <?php esc_html_e( 'Open', 'primelink' ); ?>
                                    </a>
                                    <button type="button" class="button mt_primelink-import-start" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                        <?php esc_html_e( 'Start', 'primelink' ); ?>
                                    </button>
                                    <button type="button" class="button mt_primelink-import-pause" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                        <?php esc_html_e( 'Pause', 'primelink' ); ?>
                                    </button>
                                    <button type="button" class="button mt_primelink-import-resume" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                        <?php esc_html_e( 'Resume', 'primelink' ); ?>
                                    </button>
                                    <button type="button" class="button mt_primelink-import-log" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                        <?php esc_html_e( 'Download log', 'primelink' ); ?>
                                    </button>
                                    <?php
                                    // Check if rollback is available
                                    $can_rollback = \PrimeLink\Modules\Imports\Service\ImportTrackingService::can_rollback( $row['id'] );
                                    if ( $can_rollback ) :
                                        $rollback_summary = \PrimeLink\Modules\Imports\Service\ImportTrackingService::get_rollback_summary( $row['id'] );
                                    ?>
                                        <button type="button" class="button button-link-delete mt_primelink-import-rollback" data-id="<?php echo esc_attr( $row['id'] ); ?>" title="<?php esc_attr_e( 'Rollback this import', 'primelink' ); ?>">
                                            <?php esc_html_e( 'Rollback', 'primelink' ); ?>
                                            <span class="mt_primelink-summary-pill" style="margin-left:6px;font-size:10px;">
                                                <?php echo esc_html( $rollback_summary['total_created'] + $rollback_summary['total_updated'] ); ?>
                                            </span>
                                        </button>
                                    <?php endif; ?>
                                    <?php if ( $type === 'products' ) : ?>
                                        <button type="button" class="button mt_primelink-import-delete-products" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                            <?php esc_html_e( 'Delete products', 'primelink' ); ?>
                                        </button>
                                    <?php endif; ?>
                                    <?php if ( $status === 'finished' ) : ?>
                                        <button type="button" class="button mt_primelink-import-reload" data-id="<?php echo esc_attr( $row['id'] ); ?>" title="<?php esc_attr_e( 'Create a new import with the same settings', 'primelink' ); ?>">
                                            <?php esc_html_e( 'Reload Import', 'primelink' ); ?>
                                        </button>
                                    <?php endif; ?>
                                    <?php if ( $anomalies_count > 0 ) : ?>
                                        <button type="button" class="button mt-primelink-review-anomalies" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                            <?php
                                            printf(
                                                /* translators: %d: anomaly count */
                                                esc_html__( 'Review Anomalies (%d)', 'primelink' ),
                                                (int) $anomalies_count
                                            );
                                            ?>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            <td class="mt_primelink-checkbox-cell">
                                <input type="checkbox" class="mt_primelink-import-select" value="<?php echo esc_attr( $row['id'] ); ?>" data-type="<?php echo esc_attr( $type ); ?>" />
                            </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
                <div class="mt_primelink-import-bulk-actions">
                    <button type="button" class="button mt_primelink-import-delete-selected" data-type="<?php echo esc_attr( $type ); ?>">
                        <?php esc_html_e( 'Delete selected', 'primelink' ); ?>
                    </button>
                </div>
            <?php endif; ?>
        </div>

        <!-- Scheduled Imports -->
        <div class="mt_primelink-import-section-scheduled">
            <h4><?php esc_html_e( 'Scheduled Imports', 'primelink' ); ?></h4>
            <?php if ( empty( $scheduled_rows ) ) : ?>
                <div class="mt_primelink-empty"><?php esc_html_e( 'No scheduled imports yet.', 'primelink' ); ?></div>
            <?php else : ?>
                <div class="mt_primelink-table-wrapper">
                <table class="mt_primelink-dash-table mt_primelink-imports-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'ID', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Created', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Interval', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Start time', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Status', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Actions', 'primelink' ); ?></th>
                            <th class="mt_primelink-checkbox-col">
                                <label class="mt_primelink-checkbox-label">
                                    <input type="checkbox" class="mt_primelink-imports-select-all-scheduled" data-type="<?php echo esc_attr( $type ); ?>" />
                                    <span class="muted"><?php esc_html_e( 'All', 'primelink' ); ?></span>
                                </label>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $scheduled_rows as $row ) : ?>
                            <?php
                                $progress = max( 0, min( 100, (int) $row['progress'] ) );
                                $current  = (int) $row['current'];
                                $total    = (int) $row['total'];
                                $status   = $row['status'] ? $row['status'] : 'idle';
                                $step     = (int) $row['step'];
                                $anomalies_data = get_post_meta( $row['id'], '_mt_primelink_anomalies', true );
                                $anomalies_count = is_array( $anomalies_data ) ? count( $anomalies_data ) : 0;
                                $wizard_url = add_query_arg(
                                    array( 'page' => 'mt-primelink-new-import', 'import_id' => $row['id'], 'step' => $step, 'import_type' => $row['type'] ),
                                    admin_url( 'admin.php' )
                                );
                                $interval_labels = array(
                                    'hourly'     => __( 'Hourly', 'primelink' ),
                                    'twicedaily' => __( 'Twice Daily', 'primelink' ),
                                    'daily'      => __( 'Daily', 'primelink' ),
                                    'weekly'     => __( 'Weekly', 'primelink' ),
                                    'monthly'    => __( 'Monthly', 'primelink' ),
                                );
                                $interval_label = $interval_labels[ $row['interval'] ] ?? ( $row['interval'] ?: 'daily' );
                                $start_label    = $row['start'] ? $row['start'] : __( 'Not set', 'primelink' );
                            ?>
                            <tr class="mt_primelink-import-row" data-id="<?php echo esc_attr( $row['id'] ); ?>" data-type="<?php echo esc_attr( $type ); ?>">
                                <td>#<?php echo (int) $row['id']; ?></td>
                                <td><?php echo $row['created'] ? esc_html( $row['created'] ) : '&mdash;'; ?></td>
                                <td><?php echo esc_html( $interval_label ); ?></td>
                                <td><?php echo esc_html( $start_label ); ?></td>
                                <td>
                                    <span class="mt_primelink-status-pill mt_primelink-status-<?php echo esc_attr( $status ); ?>">
                                        <?php echo esc_html( ucfirst( $status ) ); ?>
                                    </span>
                                    <div class="mt_primelink-dash-progress" style="margin-top:4px;">
                                        <div class="mt_primelink-dash-progress__bar" style="width:<?php echo $progress; ?>%;"></div>
                                    </div>
                                    <small class="muted">
                                        <?php echo esc_html( $current . ' / ' . $total ); ?>
                                    </small>
                                </td>
                                <td class="mt_primelink-import-actions">
                                    <a class="button" href="<?php echo esc_url( $wizard_url ); ?>">
                                        <?php esc_html_e( 'Open', 'primelink' ); ?>
                                    </a>
                                    <button type="button" class="button mt_primelink-import-start" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                        <?php esc_html_e( 'Start', 'primelink' ); ?>
                                    </button>
                                    <button type="button" class="button mt_primelink-import-pause" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                        <?php esc_html_e( 'Pause', 'primelink' ); ?>
                                    </button>
                                    <button type="button" class="button mt_primelink-import-resume" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                        <?php esc_html_e( 'Resume', 'primelink' ); ?>
                                    </button>
                                    <?php
                                    // Check if rollback is available for scheduled imports too
                                    $can_rollback = \PrimeLink\Modules\Imports\Service\ImportTrackingService::can_rollback( $row['id'] );
                                    if ( $can_rollback ) :
                                        $rollback_summary = \PrimeLink\Modules\Imports\Service\ImportTrackingService::get_rollback_summary( $row['id'] );
                                    ?>
                                        <button type="button" class="button button-link-delete mt_primelink-import-rollback" data-id="<?php echo esc_attr( $row['id'] ); ?>" title="<?php esc_attr_e( 'Rollback this import', 'primelink' ); ?>">
                                            <?php esc_html_e( 'Rollback', 'primelink' ); ?>
                                            <span class="mt_primelink-summary-pill" style="margin-left:6px;font-size:10px;">
                                                <?php echo esc_html( $rollback_summary['total_created'] + $rollback_summary['total_updated'] ); ?>
                                            </span>
                                        </button>
                                    <?php endif; ?>
                                    <?php if ( $status === 'finished' ) : ?>
                                        <button type="button" class="button mt_primelink-import-reload" data-id="<?php echo esc_attr( $row['id'] ); ?>" title="<?php esc_attr_e( 'Create a new import with the same settings', 'primelink' ); ?>">
                                            <?php esc_html_e( 'Reload Import', 'primelink' ); ?>
                                        </button>
                                    <?php endif; ?>
                                    <?php if ( $anomalies_count > 0 ) : ?>
                                        <button type="button" class="button mt-primelink-review-anomalies" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                            <?php
                                            printf(
                                                /* translators: %d: anomaly count */
                                                esc_html__( 'Review Anomalies (%d)', 'primelink' ),
                                                (int) $anomalies_count
                                            );
                                            ?>
                                        </button>
                                    <?php endif; ?>
                                </td>
                                <td class="mt_primelink-checkbox-cell">
                                    <input type="checkbox" class="mt_primelink-import-select" value="<?php echo esc_attr( $row['id'] ); ?>" data-type="<?php echo esc_attr( $type ); ?>" />
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
                <div class="mt_primelink-import-bulk-actions">
                    <button type="button" class="button mt_primelink-import-delete-selected" data-type="<?php echo esc_attr( $type ); ?>">
                        <?php esc_html_e( 'Delete selected', 'primelink' ); ?>
                    </button>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>

</div>

<!-- Anomalies Review Modal -->
<div id="mt-primelink-anomalies-modal" class="mt-primelink-modal-overlay" style="display:none;">
    <div class="mt-primelink-modal glass">
        <div class="mt-primelink-modal__header">
            <div style="display: flex; align-items: center; gap: 12px; flex: 1;">
                <h2 style="margin: 0; flex: 1;"><?php esc_html_e( 'Anomalies Detected During Import', 'primelink' ); ?></h2>
                <div class="mt-primelink-anomalies-export-wrapper" style="display: none;">
                    <div class="mt-primelink-dropdown">
                        <button type="button" class="button mt-primelink-export-button">
                            <?php esc_html_e( 'Export to', 'primelink' ); ?>
                        </button>
                        <ul class="mt-primelink-dropdown-menu">
                            <li><a href="#" class="mt-primelink-export-csv" data-format="csv"><?php esc_html_e( 'CSV', 'primelink' ); ?></a></li>
                            <li><a href="#" class="mt-primelink-export-excel" data-format="xlsx"><?php esc_html_e( 'Excel (XLSX)', 'primelink' ); ?></a></li>
                        </ul>
                    </div>
                </div>
            </div>
            <button type="button" class="mt-primelink-modal__close" id="mt-primelink-anomalies-modal-close">
                <span class="dashicons dashicons-no-alt"></span>
            </button>
        </div>
        <div class="mt-primelink-modal__body">
            <div id="mt-primelink-anomalies-loading" style="text-align:center;padding:40px;">
                <span class="spinner is-active"></span>
                <p><?php esc_html_e( 'Loading anomalies...', 'primelink' ); ?></p>
            </div>
            <div id="mt-primelink-anomalies-content" style="display:none;">
                <div class="mt-primelink-anomalies-summary" style="margin-bottom:20px;padding:15px;background:#fff3cd;border-left:4px solid #ffc107;border-radius:4px;">
                    <p style="margin:0;"><strong><?php esc_html_e( 'Summary:', 'primelink' ); ?></strong> <span id="mt-primelink-anomalies-count">0</span> <?php esc_html_e( 'items were skipped due to detected anomalies. Review them below and decide how to proceed.', 'primelink' ); ?></p>
                </div>
                <div id="mt-primelink-anomalies-list"></div>
            </div>
            <div id="mt-primelink-anomalies-empty" style="display:none;text-align:center;padding:40px;">
                <p><?php esc_html_e( 'No anomalies found.', 'primelink' ); ?></p>
            </div>
        </div>
        <div class="mt-primelink-modal__footer">
            <button type="button" class="button" id="mt-primelink-anomalies-modal-close-btn"><?php esc_html_e( 'Close', 'primelink' ); ?></button>
        </div>
    </div>
</div>
