<?php
/**
 * Localization Settings Tab
 *
 * Renders a sortable table of active columns (excluding ID and Type).
 * Users can rename column labels and drag rows to reorder them.
 * Saving the parent form persists changes into pssg_config (Admin_Base->configs).
 *
 * Variables available from the parent settings.php include scope:
 *  - $saved_data  : array  get_option( $this->config_key, [] )
 *  - $this        : Page_Loader instance
 *
 * @since 2.0.1.4
 * @package PSSG_Sync_Sheet
 */

if ( ! defined( 'ABSPATH' ) ) exit;

use PSSG_Sync_Sheet\App\Handle\Localization_Handle;
use PSSG_Sync_Sheet\App\Service\Products;

// -----------------------------------------------------------------------
// Build the "natural" column list (without localization labels/order)
// by temporarily removing this handler's filter so we see raw defaults.
// -----------------------------------------------------------------------
$_loc_handler = Localization_Handle::init();
remove_filter( 'pssg_products_columns', [ $_loc_handler, 'apply_localization' ], 99 );

$_products       = new Products();
$_natural_cols   = $_products->get_columns();

add_filter( 'pssg_products_columns', [ $_loc_handler, 'apply_localization' ], 99 );

// ID and Type are always fixed — exclude them from this UI.
$_excluded     = [ 'ID', 'type','_post_status','_permalink', 'post_edit_link' ];
$_editable_cols = array_diff_key( $_natural_cols, array_flip( $_excluded ) );

// -----------------------------------------------------------------------
// Apply saved order so rows are shown in the currently configured order.
// -----------------------------------------------------------------------
$_saved_labels    = $saved_data['column_labels'] ?? [];
$_saved_order_str = $saved_data['column_order']  ?? '';

if ( ! empty( $_saved_order_str ) ) {
    $_order_keys  = array_filter( array_map( 'trim', explode( ',', $_saved_order_str ) ) );
    $_ordered_tmp = [];

    foreach ( $_order_keys as $_ok ) {
        if ( isset( $_editable_cols[ $_ok ] ) ) {
            $_ordered_tmp[ $_ok ] = $_editable_cols[ $_ok ];
        }
    }
    // Columns added after the last save go at the end.
    foreach ( $_editable_cols as $_ok => $_col ) {
        if ( ! isset( $_ordered_tmp[ $_ok ] ) ) {
            $_ordered_tmp[ $_ok ] = $_col;
        }
    }
    $_editable_cols = $_ordered_tmp;
}

$_current_order = implode( ',', array_keys( $_editable_cols ) );

// -----------------------------------------------------------------------
// Drag & Drop ordering switch state.
// -----------------------------------------------------------------------
$_order_enabled = ! empty( $saved_data['column_order_enabled'] ) ? '1' : '0';

?>
<table class="pssg-table localization-settings" id="pssg-localization-settings-table">
    <thead>
        <tr>
            <th class="pssg-inside">
                <div class="pssg-table-header-inside">
                    <h3>
                        <i class="pssg_icon-globe-inv"></i>
                        <?php echo esc_html__( 'Localization & Drag-Drop', 'product-sync-master-sheet' ); ?>
                    </h3>
                </div>
            </th>
            <th>
                <div class="pssg-table-header-right-side"></div>
            </th>
        </tr>
    </thead>

    <tbody>

        <tr class="<?php echo esc_attr( pssg_is_premium() ? '' : 'pssg-premium-row' ); ?>">
            <td>

                <!-- Hidden input updated by JS when rows are reordered -->
                <input
                    type="hidden"
                    name="column_order"
                    id="pssg-column-order-input"
                    value="<?php echo esc_attr( $_current_order ); ?>"
                >

                <!-- ── Drag & Drop enable switch ── -->
                <div class="pssg-form-control pssg-dnd-switch-row">
                    <label class="pssg-switch-label" for="pssg-column-order-enabled">
                        <span class="pssg-switch">
                            <input
                                type="checkbox"
                                name="column_order_enabled"
                                id="pssg-column-order-enabled"
                                value="1"
                                <?php checked( '1', $_order_enabled ); ?>
                            >
                            <span class="pssg-switch-slider"></span>
                        </span>
                        <span class="pssg-switch-text">
                            <?php echo esc_html__( 'Enable Drag & Drop Column Ordering', 'product-sync-master-sheet' ); ?>
                        </span>
                    </label>
                    <p class="description pssg-dnd-switch-desc">
                        <?php echo esc_html__( 'Turn on to reorder columns by dragging rows. The saved order will only be applied when this is enabled.', 'product-sync-master-sheet' ); ?>
                    </p>
                </div><!-- /.pssg-dnd-switch-row -->

                <?php if ( empty( $_editable_cols ) ) : ?>
                    <p class="pssg-form-info">
                        <em><?php echo esc_html__( 'No editable columns found. Enable columns from the Settings tab first.', 'product-sync-master-sheet' ); ?></em>
                    </p>
                <?php else : ?>

                <div class="pssg-localization-table-wrapper">
                    <table class="pssg-locale-inner-table widefat fixed">
                        <thead>
                            <tr>
                                <th class="pssg-drag-th"></th>
                                <th><?php echo esc_html__( 'Default Label', 'product-sync-master-sheet' ); ?></th>
                                <th><?php echo esc_html__( 'Custom Label', 'product-sync-master-sheet' ); ?></th>
                            </tr>
                        </thead>
                        <tbody id="pssg-localization-sortable">

                            <?php foreach ( $_editable_cols as $_col_key => $_col ) :
                                $_default_title = $_col['title'] ?? $_col_key;
                                $_custom_label  = $_saved_labels[ $_col_key ] ?? '';
                            ?>
                            <tr class="pssg-locale-row" data-col-key="<?php echo esc_attr( $_col_key ); ?>">

                                <td class="pssg-drag-cell">
                                    <span
                                        class="pssg-drag-handle dashicons dashicons-move"
                                        title="<?php echo esc_attr__( 'Drag to reorder', 'product-sync-master-sheet' ); ?>"
                                    ></span>
                                </td>

                                <td class="pssg-default-title-cell">
                                    <span class="pssg-col-default-label">
                                        <?php echo esc_html( $_default_title ); ?> 
                                        <small style="color: #cbcbcb;font-weight: italic;">(<?php echo esc_html( $_col_key ); ?>)</small>
                                    </span>
                                </td>

                                <td class="pssg-custom-label-cell">
                                    <input
                                        type="text"
                                        name="column_labels[<?php echo esc_attr( $_col_key ); ?>]"
                                        value="<?php echo esc_attr( $_custom_label ); ?>"
                                        placeholder="<?php echo esc_attr( $_default_title ); ?>"
                                        class="pssg-locale-input regular-text"
                                        style="width:100%;max-width:500px;background:#f3f3f3;border-color:#f0f0f0;"
                                    >
                                </td>

                            </tr>
                            <?php endforeach; ?>

                        </tbody>
                    </table>
                </div><!-- /.pssg-localization-table-wrapper -->

                <div class="pssg-locale-reset-wrap">
                    <button
                        type="button"
                        id="pssg-reset-column-order-btn"
                        class="pssg-btn pssg-has-icon pssg-reset-btn pssg-reset-column-order-btn"
                        data-nonce="<?php echo esc_attr( wp_create_nonce( plugin_basename( PSSG_BASE_FILE ) ) ); ?>"
                    >
                        <span><i class="dashicons dashicons-image-rotate"></i></span>
                        <strong><?php echo esc_html__( 'Reset Column Order', 'product-sync-master-sheet' ); ?></strong>
                    </button>
                </div>

                <?php endif; ?>

            </td>
            <td>
                <div class="pssg-locale-description">
                    <p>
                        <?php echo esc_html__( 'Reorder columns by dragging rows. Set custom labels to override defaults in the product sheet and sync logs.', 'product-sync-master-sheet' ); ?>
                    </p>
                </div>
            </td>
        </tr>

    </tbody>
</table>

<style>
#pssg-localization-settings-table .pssg-localization-table-wrapper {
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
    margin-top: 8px;
}
#pssg-localization-settings-table .pssg-locale-inner-table {
    border: none;
    margin: 0;
}
#pssg-localization-settings-table .pssg-locale-inner-table thead th {
    background: #f5f5f5;
    padding: 9px 12px;
    font-weight: 600;
    border-bottom: 2px solid #ddd;
    white-space: nowrap;
}
#pssg-localization-settings-table .pssg-drag-th {
    width: 36px;
}
#pssg-localization-settings-table .pssg-locale-row td {
    padding: 9px 12px;
    border-bottom: 1px solid #eeeeee;
    vertical-align: middle;
}
#pssg-localization-settings-table .pssg-locale-row:last-child td {
    border-bottom: none;
}
#pssg-localization-settings-table .pssg-locale-row:hover {
    background: #fafbff;
}
#pssg-localization-settings-table .pssg-locale-row.ui-sortable-helper {
    background: #fff;
    box-shadow: 0 4px 14px rgba(0,0,0,0.13);
    display: table;
    width: 100%;
}
#pssg-localization-settings-table .pssg-locale-row.ui-sortable-placeholder {
    background: #e8f4fd !important;
    border: 1px dashed #2196F3 !important;
    visibility: visible !important;
    height: 42px;
}
#pssg-localization-settings-table .pssg-drag-cell {
    width: 36px;
    text-align: center;
}
#pssg-localization-settings-table .pssg-drag-handle {
    cursor: move;
    color: #000;
    font-size: 18px;
    display: inline-block;
    line-height: 1;
    transition: color 0.15s ease;
}
#pssg-localization-settings-table .pssg-drag-handle:hover {
    color: #555;
}
#pssg-localization-settings-table .pssg-drag-handle.pssg-dnd-disabled {
    cursor: default;
    color: #ccc;
    pointer-events: none;
}
#pssg-localization-settings-table .pssg-col-default-label {
    font-weight: 500;
    color: #444;
}
#pssg-localization-settings-table .pssg-locale-input {
    width: 100%;
    max-width: 300px;
}
#pssg-localization-settings-table .pssg-locale-description p {
    margin: 4px 0 0;
    color: #666;
}

/* ── Drag & Drop switch ── */
#pssg-localization-settings-table .pssg-dnd-switch-row {
    margin-bottom: 14px;
}
#pssg-localization-settings-table .pssg-switch-label {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    user-select: none;
}
#pssg-localization-settings-table .pssg-switch {
    position: relative;
    display: inline-block;
    width: 44px;
    height: 24px;
    flex-shrink: 0;
}
#pssg-localization-settings-table .pssg-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}
#pssg-localization-settings-table .pssg-switch-slider {
    position: absolute;
    inset: 0;
    background: #ccc;
    border-radius: 24px;
    transition: background 0.2s ease;
    cursor: pointer;
}
#pssg-localization-settings-table .pssg-switch-slider:before {
    content: '';
    position: absolute;
    width: 18px;
    height: 18px;
    left: 3px;
    bottom: 3px;
    background: #fff;
    border-radius: 50%;
    transition: transform 0.2s ease;
}
#pssg-localization-settings-table .pssg-switch input:checked + .pssg-switch-slider {
    background: #2196F3;
}
#pssg-localization-settings-table .pssg-switch input:checked + .pssg-switch-slider:before {
    transform: translateX(20px);
}
#pssg-localization-settings-table .pssg-switch-text {
    font-weight: 600;
    color: #333;
}
#pssg-localization-settings-table .pssg-dnd-switch-desc {
    margin: 6px 0 0 54px;
    color: #888;
    font-style: italic;
}

/* ── Reset button row ── */
#pssg-localization-settings-table .pssg-locale-reset-wrap {
    margin-top: 12px;
}
</style>

<script>
jQuery(document).ready(function ($) {
    var $sortable    = $('#pssg-localization-sortable');
    var $orderInput  = $('#pssg-column-order-input');
    var $dndSwitch   = $('#pssg-column-order-enabled');
    var $resetBtn    = $('#pssg-reset-column-order-btn');
    var sortableInit = false;

    if ( ! $sortable.length ) return;

    // ── helpers ──────────────────────────────────────────────────────────
    function pssg_update_column_order() {
        var order = [];
        $sortable.find('.pssg-locale-row').each(function () {
            var key = $(this).data('col-key');
            if ( key ) order.push( key );
        });
        $orderInput.val( order.join(',') );
    }

    function pssg_enable_dnd() {
        if ( ! sortableInit ) {
            $sortable.sortable({
                handle              : '.pssg-drag-handle',
                axis                : 'y',
                placeholder         : 'pssg-locale-row ui-sortable-placeholder',
                forcePlaceholderSize: true,
                tolerance           : 'pointer',
                stop: function () {
                    pssg_update_column_order();
                }
            });
            sortableInit = true;
        } else {
            $sortable.sortable('enable');
        }
        $sortable.find('.pssg-drag-handle').removeClass('pssg-dnd-disabled');
    }

    function pssg_disable_dnd() {
        if ( sortableInit ) {
            $sortable.sortable('disable');
        }
        $sortable.find('.pssg-drag-handle').addClass('pssg-dnd-disabled');
    }

    // ── Init state ───────────────────────────────────────────────────────
    if ( $dndSwitch.is(':checked') ) {
        pssg_enable_dnd();
    } else {
        pssg_disable_dnd();
    }

    // ── Toggle switch ────────────────────────────────────────────────────
    $dndSwitch.on('change', function () {
        if ( $(this).is(':checked') ) {
            pssg_enable_dnd();
        } else {
            pssg_disable_dnd();
        }
    });

    // ── Reset Column Order button ─────────────────────────────────────────
    $resetBtn.on('click', function () {
        var confirmMsg = ( typeof PSSG_DATA !== 'undefined' && PSSG_DATA.text && PSSG_DATA.text.reset_column_order_confirm )
            ? PSSG_DATA.text.reset_column_order_confirm
            : '<?php echo esc_js( __( 'Reset column order to default? This cannot be undone.', 'product-sync-master-sheet' ) ); ?>';

        if ( ! confirm( confirmMsg ) ) return;

        var $btn = $(this);
        $btn.prop('disabled', true);

        $.post(
            ajaxurl,
            {
                action : 'pssg_reset_column_order',
                nonce  : $btn.data('nonce'),
            },
            function ( res ) {
                if ( res.success ) {
                    window.location.reload();
                } else {
                    alert( res.data && res.data.message ? res.data.message : '<?php echo esc_js( __( 'Reset failed.', 'product-sync-master-sheet' ) ); ?>' );
                    $btn.prop('disabled', false);
                }
            }
        ).fail(function () {
            alert( '<?php echo esc_js( __( 'Request failed. Please try again.', 'product-sync-master-sheet' ) ); ?>' );
            $btn.prop('disabled', false);
        });
    });
});
</script>
