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

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

// Group exports by type
$exports_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_export_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'][3]['schedule'] ?? array();
    $is_sched  = ! empty( $schedule['enabled'] );
    $next_run  = isset( $schedule['next_run'] ) ? absint( $schedule['next_run'] ) : 0;
    
    // Get export type
    $export_type = $draft['type'] ?? ($draft['step_data'][1]['export_type'] ?? 'products');
    // Normalize type
    if ( $export_type === 'order' ) {
        $export_type = 'orders';
    } elseif ( $export_type === 'customer' ) {
        $export_type = 'customers';
    } elseif ( $export_type === 'coupon' ) {
        $export_type = 'coupons';
    } elseif ( $export_type === 'category' ) {
        $export_type = 'categories';
    } elseif ( $export_type === 'tag' ) {
        $export_type = 'tags';
    } elseif ( $export_type === 'attribute' ) {
        $export_type = 'attributes';
        } elseif ( $export_type === 'variation' ) {
            $export_type = 'variations';
        } elseif ( $export_type === 'review' ) {
            $export_type = 'reviews';
        } elseif ( $export_type === 'download' ) {
            $export_type = 'downloads';
        } elseif ( $export_type === 'product' ) {
        $export_type = 'products';
    }
    // Default to products if unknown
    if ( !isset($exports_by_type[$export_type]) ) {
        $export_type = 'products';
    }

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

    $category = $is_sched ? 'scheduled' : 'manual';
    $exports_by_type[$export_type][$category][] = $row;
}

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

// Sort each category
foreach ( $exports_by_type as $type => $categories ) {
    usort( $exports_by_type[$type]['manual'], $sort );
    usort( $exports_by_type[$type]['scheduled'], $sort );
}
?>
<div class="wrap mt-primelink-wrap">
    <?php
    ob_start();
    ?>
    <button type="button" class="button mt_primelink-exports-refresh" id="mt_primelink-exports-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-export' ) ); ?>" class="button button-primary">
        <?php esc_html_e( 'New Export', 'primelink' ); ?>
    </a>
    <?php
    $header_actions     = ob_get_clean();
    $header_eyebrow     = __( 'Exports Hub', 'primelink' );
    $header_title       = __( 'Manage Exports', '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' ),
    );
    
    foreach ( $exports_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] . ' Exports' ); ?></h3>
            </div>
        </div>

        <!-- Manual Exports -->
        <div class="mt_primelink-import-section">
            <h4><?php esc_html_e( 'Manual Exports', 'primelink' ); ?></h4>
            <?php if ( empty( $manual_rows ) ) : ?>
                <div class="mt_primelink-empty"><?php esc_html_e( 'No manual exports 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-exports-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'];
                                $wizard_url = add_query_arg(
                                    array( 'page' => 'mt-primelink-new-export', 'export_id' => $row['id'], 'step' => $step, 'export_type' => $row['type'] ),
                                    admin_url( 'admin.php' )
                                );
                                // Get state for this specific export
                                $export_state = get_option( 'mt_primelink_export_state_' . absint( $row['id'] ), array() );
                                $file_url = isset( $export_state['file_url'] ) ? $export_state['file_url'] : '';
                                $file_path = isset( $export_state['file_path'] ) ? $export_state['file_path'] : '';
                                
                                // Build download URL using REST API endpoint
                                $download_url = '';
                                if ( $status === 'completed' ) {
                                    if ( ! empty( $file_url ) ) {
                                        $download_url = $file_url;
                                    } elseif ( ! empty( $file_path ) && file_exists( $file_path ) ) {
                                        $download_url = rest_url( 'primelink/v1/export/download' ) . '?export_id=' . absint( $row['id'] ) . '&_wpnonce=' . wp_create_nonce( 'wp_rest' );
                                    }
                                }
                            ?>
                            <tr class="mt_primelink-export-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>
                                    <?php if ( $status !== 'completed' && $status !== 'error' ) : ?>
                                        <button type="button" class="button mt_primelink-export-start" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                            <?php esc_html_e( 'Start', 'primelink' ); ?>
                                        </button>
                                        <button type="button" class="button mt_primelink-export-pause" data-id="<?php echo esc_attr( $row['id'] ); ?>" style="display:none;">
                                            <?php esc_html_e( 'Pause', 'primelink' ); ?>
                                        </button>
                                        <button type="button" class="button mt_primelink-export-resume" data-id="<?php echo esc_attr( $row['id'] ); ?>" style="display:none;">
                                            <?php esc_html_e( 'Resume', 'primelink' ); ?>
                                        </button>
                                    <?php endif; ?>
                                    <?php if ( $status === 'completed' && ! empty( $download_url ) ) : ?>
                                        <a href="<?php echo esc_url( $download_url ); ?>" class="button button-primary" download>
                                            <?php esc_html_e( 'Download', 'primelink' ); ?>
                                        </a>
                                    <?php endif; ?>
                                    <?php if ( ! empty( $export_state['log'] ) && is_array( $export_state['log'] ) && count( $export_state['log'] ) > 0 ) : ?>
                                        <button type="button" class="button mt_primelink-export-log" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                            <?php esc_html_e( 'Download log', 'primelink' ); ?>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            <td class="mt_primelink-checkbox-cell">
                                <input type="checkbox" class="mt_primelink-export-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-export-delete-selected" data-type="<?php echo esc_attr( $type ); ?>">
                        <?php esc_html_e( 'Delete selected', 'primelink' ); ?>
                    </button>
                </div>
            <?php endif; ?>
        </div>

        <!-- Scheduled Exports -->
        <div class="mt_primelink-import-section-scheduled">
            <h4><?php esc_html_e( 'Scheduled Exports', 'primelink' ); ?></h4>
            <?php if ( empty( $scheduled_rows ) ) : ?>
                <div class="mt_primelink-empty"><?php esc_html_e( 'No scheduled exports 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( 'Next Run', '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-exports-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'];
                                $wizard_url = add_query_arg(
                                    array( 'page' => 'mt-primelink-new-export', 'export_id' => $row['id'], 'step' => $step, 'export_type' => $row['type'] ),
                                    admin_url( 'admin.php' )
                                );
                                $next_run_label = $row['next_run'] ? date_i18n( 'Y-m-d H:i:s', $row['next_run'] ) : __( 'Not set', 'primelink' );
                                
                                // Get state for this specific export
                                $export_state = get_option( 'mt_primelink_export_state_' . absint( $row['id'] ), array() );
                                $file_url = isset( $export_state['file_url'] ) ? $export_state['file_url'] : '';
                                $file_path = isset( $export_state['file_path'] ) ? $export_state['file_path'] : '';
                                
                                // Build download URL using REST API endpoint
                                $download_url = '';
                                if ( $status === 'completed' ) {
                                    if ( ! empty( $file_url ) ) {
                                        $download_url = $file_url;
                                    } elseif ( ! empty( $file_path ) && file_exists( $file_path ) ) {
                                        $download_url = rest_url( 'primelink/v1/export/download' ) . '?export_id=' . absint( $row['id'] ) . '&_wpnonce=' . wp_create_nonce( 'wp_rest' );
                                    }
                                }
                            ?>
                            <tr class="mt_primelink-export-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( $next_run_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>
                                    <?php if ( $status !== 'completed' && $status !== 'error' ) : ?>
                                        <button type="button" class="button mt_primelink-export-start" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                            <?php esc_html_e( 'Start', 'primelink' ); ?>
                                        </button>
                                        <button type="button" class="button mt_primelink-export-pause" data-id="<?php echo esc_attr( $row['id'] ); ?>" style="display:none;">
                                            <?php esc_html_e( 'Pause', 'primelink' ); ?>
                                        </button>
                                        <button type="button" class="button mt_primelink-export-resume" data-id="<?php echo esc_attr( $row['id'] ); ?>" style="display:none;">
                                            <?php esc_html_e( 'Resume', 'primelink' ); ?>
                                        </button>
                                    <?php endif; ?>
                                    <?php if ( $status === 'completed' && ! empty( $download_url ) ) : ?>
                                        <a href="<?php echo esc_url( $download_url ); ?>" class="button button-primary" download>
                                            <?php esc_html_e( 'Download', 'primelink' ); ?>
                                        </a>
                                    <?php endif; ?>
                                    <?php if ( ! empty( $export_state['log'] ) && is_array( $export_state['log'] ) && count( $export_state['log'] ) > 0 ) : ?>
                                        <button type="button" class="button mt_primelink-export-log" data-id="<?php echo esc_attr( $row['id'] ); ?>">
                                            <?php esc_html_e( 'Download log', 'primelink' ); ?>
                                        </button>
                                    <?php endif; ?>
                                </td>
                                <td class="mt_primelink-checkbox-cell">
                                    <input type="checkbox" class="mt_primelink-export-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-export-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>

