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

$templates = get_option( 'mt_primelink_import_templates', array() );
$templates = is_array( $templates ) ? $templates : array();

// Group templates by type
$templates_by_type = array(
    'products'  => array(),
    'orders'    => array(),
    'customers' => array(),
    'coupons'   => array(),
    'categories' => array(),
    'tags' => array(),
    'attributes' => array(),
        'variations' => array(),
        'reviews' => array(),
        'downloads' => array(),
    );

foreach ( $templates as $name => $template_data ) {
    $type = $template_data['type'] ?? '';
    
    // Determine type from prefix if not stored
    if ( empty( $type ) ) {
        if ( strpos( $name, 'order:' ) === 0 ) {
            $type = 'orders';
        } elseif ( strpos( $name, 'customer:' ) === 0 ) {
            $type = 'customers';
        } elseif ( strpos( $name, 'coupon:' ) === 0 ) {
            $type = 'coupons';
        } elseif ( strpos( $name, 'category:' ) === 0 ) {
            $type = 'categories';
        } elseif ( strpos( $name, 'tag:' ) === 0 ) {
            $type = 'tags';
        } elseif ( strpos( $name, 'attribute:' ) === 0 ) {
            $type = 'attributes';
        } elseif ( strpos( $name, 'variation:' ) === 0 ) {
            $type = 'variations';
        } elseif ( strpos( $name, 'review:' ) === 0 ) {
            $type = 'reviews';
        } elseif ( strpos( $name, 'download:' ) === 0 ) {
            $type = 'downloads';
        } elseif ( strpos( $name, 'product:' ) === 0 ) {
            $type = 'products';
        } else {
            $type = 'products'; // Default for old templates without prefix
        }
    }
    
    // Normalize type
    if ( $type === 'product' ) {
        $type = 'products';
    } elseif ( $type === 'order' ) {
        $type = 'orders';
    } elseif ( $type === 'customer' ) {
        $type = 'customers';
    } elseif ( $type === 'coupon' ) {
        $type = 'coupons';
    } elseif ( $type === 'category' ) {
        $type = 'categories';
    } elseif ( $type === 'tag' ) {
        $type = 'tags';
    } elseif ( $type === 'attribute' ) {
        $type = 'attributes';
        } elseif ( $type === 'variation' ) {
            $type = 'variations';
        } elseif ( $type === 'review' ) {
            $type = 'reviews';
        } elseif ( $type === 'download' ) {
            $type = 'downloads';
        }
    
    if ( ! isset( $templates_by_type[ $type ] ) ) {
        $type = 'products';
    }
    
    // Remove prefix for display name
        $display_name = preg_replace( '/^(order|product|customer|coupon|category|tag|attribute|variation|review|download):/', '', $name );
    
    // Count mapped fields
    $mapped_count = 0;
    if ( isset( $template_data['data']['mapping'] ) && is_array( $template_data['data']['mapping'] ) ) {
        $mapped_count = count( array_filter( $template_data['data']['mapping'], function( $slot ) {
            return ! empty( $slot['source'] );
        } ) );
    }
    
    $templates_by_type[ $type ][] = array(
        'name'         => $name,
        'display_name' => $display_name,
        'type'         => $type,
        'updated_at'   => $template_data['updated_at'] ?? '',
        'mapped_count' => $mapped_count,
        'data'         => $template_data['data'] ?? array(),
    );
}

// Sort templates by name within each type
foreach ( $templates_by_type as $type => &$templates_list ) {
    usort( $templates_list, function( $a, $b ) {
        return strcmp( $a['display_name'], $b['display_name'] );
    } );
}
unset( $templates_list );
?>

<div class="wrap mt-primelink-wrap">
    <?php
    ob_start();
    ?>
    <input type="text" id="mt-primelink-template-search" class="mt-primelink-search-input" placeholder="<?php esc_attr_e( 'Search templates...', 'primelink' ); ?>" style="margin-right:8px;padding:6px 12px;border:1px solid rgba(0,0,0,0.1);border-radius:6px;min-width:200px;" />
    <button type="button" class="button" id="mt-primelink-export-all-templates">
        <?php esc_html_e( 'Export All', 'primelink' ); ?>
    </button>
    <button type="button" class="button" id="mt-primelink-import-templates">
        <?php esc_html_e( 'Import', 'primelink' ); ?>
    </button>
    <input type="file" id="mt-primelink-import-file" accept=".json" style="display:none;" />
    <?php
    $header_actions     = ob_get_clean();
    $header_eyebrow     = __( 'Templates Hub', 'primelink' );
    $header_title       = __( 'Template Manager', 'primelink' );
    $header_description = __( 'Manage and organize your import mapping templates', '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( 'Product Categories', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="tags"><?php esc_html_e( 'Product Tags', 'primelink' ); ?></button>
        <button class="button mt_primelink-tab-btn" data-tab="attributes"><?php esc_html_e( 'Product Attributes', 'primelink' ); ?></button>
            <button class="button mt_primelink-tab-btn" data-tab="variations"><?php esc_html_e( 'Product Variations', 'primelink' ); ?></button>
            <button class="button mt_primelink-tab-btn" data-tab="reviews"><?php esc_html_e( 'Product Reviews', 'primelink' ); ?></button>
            <button class="button mt_primelink-tab-btn" data-tab="downloads"><?php esc_html_e( 'Product Downloads', 'primelink' ); ?></button>
        </div>

    <?php
    $type_labels = array(
        'products'  => __( 'Products', 'primelink' ),
        'orders'    => __( 'Orders', 'primelink' ),
        'customers' => __( 'Customers', 'primelink' ),
        'coupons'   => __( 'Coupons', 'primelink' ),
        'categories' => __( 'Product Categories', 'primelink' ),
        'attributes' => __( 'Product Attributes', 'primelink' ),
        'tags'      => __( 'Product Tags', 'primelink' ),
        'variations' => __( 'Product Variations', 'primelink' ),
        'reviews' => __( 'Product Reviews', 'primelink' ),
        'downloads' => __( 'Product Downloads', 'primelink' ),
    );
    
    foreach ( $templates_by_type as $type => $templates_list ) :
        $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 ] . ' Templates' ); ?></h3>
            </div>
            <div style="display:flex;align-items:center;gap:12px;">
                <select class="mt-primelink-sort-select" data-type="<?php echo esc_attr( $type ); ?>" style="padding:6px 10px;border:1px solid rgba(0,0,0,0.1);border-radius:6px;font-size:13px;">
                    <option value="name-asc"><?php esc_html_e( 'Name (A-Z)', 'primelink' ); ?></option>
                    <option value="name-desc"><?php esc_html_e( 'Name (Z-A)', 'primelink' ); ?></option>
                    <option value="date-desc"><?php esc_html_e( 'Recent First', 'primelink' ); ?></option>
                    <option value="date-asc"><?php esc_html_e( 'Oldest First', 'primelink' ); ?></option>
                    <option value="fields-desc"><?php esc_html_e( 'Most Fields', 'primelink' ); ?></option>
                    <option value="fields-asc"><?php esc_html_e( 'Least Fields', 'primelink' ); ?></option>
                </select>
            </div>
        </div>

        <?php if ( empty( $templates_list ) ) : ?>
            <div class="mt_primelink-empty">
                <p><?php esc_html_e( 'No templates found for this type.', 'primelink' ); ?></p>
                <p class="muted"><?php esc_html_e( 'Create templates from the import wizard (Step 5).', 'primelink' ); ?></p>
            </div>
        <?php else : ?>
            <div class="mt_primelink-import-section">
                <div class="mt_primelink-table-wrapper">
                <table class="mt_primelink-dash-table mt_primelink-imports-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Template Name', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Mapped Fields', 'primelink' ); ?></th>
                            <th><?php esc_html_e( 'Last Modified', '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-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 ( $templates_list as $template ) : ?>
                            <tr class="mt-primelink-template-row" data-name="<?php echo esc_attr( $template['name'] ); ?>" data-type="<?php echo esc_attr( $type ); ?>">
                                <td>
                                    <strong><?php echo esc_html( $template['display_name'] ); ?></strong>
                                </td>
                                <td>
                                    <span class="muted"><?php echo esc_html( $template['mapped_count'] ); ?> <?php esc_html_e( 'fields', 'primelink' ); ?></span>
                                </td>
                                <td>
                                    <?php if ( ! empty( $template['updated_at'] ) ) : ?>
                                        <?php
                                        $date = strtotime( $template['updated_at'] );
                                        echo esc_html( human_time_diff( $date, current_time( 'timestamp' ) ) . ' ago' );
                                        ?>
                                    <?php else : ?>
                                        <span class="muted">&mdash;</span>
                                    <?php endif; ?>
                                </td>
                                <td class="mt_primelink-import-actions">
                                    <button type="button" class="button mt-primelink-template-preview" data-name="<?php echo esc_attr( $template['name'] ); ?>">
                                        <?php esc_html_e( 'Preview', 'primelink' ); ?>
                                    </button>
                                    <button type="button" class="button mt-primelink-template-load" data-name="<?php echo esc_attr( $template['name'] ); ?>" data-type="<?php echo esc_attr( $type ); ?>">
                                        <?php esc_html_e( 'Load', 'primelink' ); ?>
                                    </button>
                                    <button type="button" class="button mt-primelink-template-duplicate" data-name="<?php echo esc_attr( $template['name'] ); ?>">
                                        <?php esc_html_e( 'Duplicate', 'primelink' ); ?>
                                    </button>
                                    <button type="button" class="button button-link-delete mt-primelink-template-delete" data-name="<?php echo esc_attr( $template['name'] ); ?>">
                                        <?php esc_html_e( 'Delete', 'primelink' ); ?>
                                    </button>
                                </td>
                                <td class="mt_primelink-checkbox-cell">
                                    <input type="checkbox" class="mt-primelink-template-select" value="<?php echo esc_attr( $template['name'] ); ?>" 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-bulk-delete" data-type="<?php echo esc_attr( $type ); ?>">
                        <?php esc_html_e( 'Delete Selected', 'primelink' ); ?>
                    </button>
                    <button type="button" class="button mt-primelink-bulk-duplicate" data-type="<?php echo esc_attr( $type ); ?>">
                        <?php esc_html_e( 'Duplicate Selected', 'primelink' ); ?>
                    </button>
                </div>
            </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
</div>

<!-- Preview Modal -->
<div id="mt-primelink-template-preview-modal" class="mt-primelink-modal" style="display:none;">
    <div class="mt-primelink-modal__overlay"></div>
    <div class="mt-primelink-modal__content glass">
        <div class="mt-primelink-modal__header">
            <h2><?php esc_html_e( 'Template Preview', 'primelink' ); ?></h2>
            <button type="button" class="mt-primelink-modal__close">
                <span class="dashicons dashicons-no-alt"></span>
            </button>
        </div>
        <div class="mt-primelink-modal__body" id="mt-primelink-template-preview-content">
            <!-- Content loaded via JS -->
        </div>
        <div class="mt-primelink-modal__footer">
            <button type="button" class="button mt-primelink-modal__close"><?php esc_html_e( 'Close', 'primelink' ); ?></button>
        </div>
    </div>
</div>
