<?php
namespace PSSG_Sync_Sheet\App\Handle;

use PSSG_Sync_Sheet\App\Core\Admin_Base;
use PSSG_Sync_Sheet\App\Service\Standalone;

/**
 * Localization Handle
 *
 * Adds a "Localization" tab to the Settings page where users can:
 *  - Rename column labels (leave empty to keep the default)
 *  - Reorder columns via drag-and-drop
 *
 * ID and Type columns are always first and are excluded from this UI.
 * Data is stored inside Admin_Base->configs (pssg_config option).
 *
 * @since 2.0.1.4
 * @author CodeAstrology Team <codersaiful@gmail.com>
 * @package PSSG_Sync_Sheet
 */
class Localization_Handle extends Admin_Base
{
    use Standalone;

    public function __construct()
    {
        parent::__construct();

        // Add "Localization" tab to the Settings page
        add_filter( 'pssg_admin_pages_arr', [ $this, 'add_localization_tab' ], 10, 2 );

        // Apply custom labels and column order (late priority — runs after all other column filters)
        add_filter( 'pssg_products_columns', [ $this, 'apply_localization' ], 99 );

        // Enqueue jQuery UI Sortable on plugin admin pages
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
    }

    /**
     * Inject the Localization tab into the Settings page tab list.
     *
     * @param array  $pages      Existing pages array from pssg_admin_pages_arr filter.
     * @param object $page_loader Page_Loader instance.
     * @return array
     */
    public function add_localization_tab( $pages, $page_loader )
    {
        $pages['localization'] = [
            'icon' => 'pssg_icon-globe-inv',
            'file' => '',  // auto-resolved to admin/pages/incs/localization.php
        ];

        //I want to add this tab before the security tab, so I will reorder the array here.
        if ( isset( $pages['security'] ) ) {
            $security_page = [ 'security' => $pages['security'] ];
            unset( $pages['security'] );
            $pages = array_merge( $pages, $security_page );
        }
        return $pages;
    }

    /**
     * Enqueue jQuery UI Sortable on plugin pages.
     *
     * @param string $hook Current admin page hook.
     * @return void
     */
    public function enqueue_scripts( $hook )
    {
        if ( strpos( $hook, 'pssg' ) === false ) {
            return;
        }
        wp_enqueue_script( 'jquery-ui-sortable' );
    }

    /**
     * Apply saved column order and custom labels to the columns array.
     *
     * Runs at priority 99 so it executes after all other pssg_products_columns filters.
     * ID and Type columns are handled separately by Products::get_columns() and
     * are never passed through this filter.
     *
     * @param array $columns Columns array (without ID/Type).
     * @return array
     */
    public function apply_localization( $columns )
    {

        if( ! $this->is_premium ) return $columns;
        $saved_order  = $this->configs['column_order']  ?? '';
        $saved_labels = $this->configs['column_labels'] ?? [];
        $order_enabled = ! empty( $this->configs['column_order_enabled'] );

        // 1. Apply custom order (only when the Drag & Drop switch is enabled) ----
        if ( $order_enabled && ! empty( $saved_order ) ) {
            $order_keys = array_filter( array_map( 'trim', explode( ',', $saved_order ) ) );

            $ordered = [];
            foreach ( $order_keys as $key ) {
                if ( isset( $columns[ $key ] ) ) {
                    $ordered[ $key ] = $columns[ $key ];
                }
            }
            // Append any columns that were added after the order was last saved
            foreach ( $columns as $key => $col ) {
                if ( ! isset( $ordered[ $key ] ) ) {
                    $ordered[ $key ] = $col;
                }
            }
            $columns = $ordered;
        }

        // 2. Apply custom labels ------------------------------------------------
        if ( is_array( $saved_labels ) ) {
            foreach ( $saved_labels as $key => $label ) {
                $label = trim( (string) $label );
                if ( isset( $columns[ $key ] ) && $label !== '' ) {
                    $columns[ $key ]['title'] = $label;
                }
            }
        }

        return $columns;
    }
}
