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

class KNSDD_Alias {
    const OPTION_KEY = 'knsdd_alias_map';

    /**
     * Harita yapısı:
     * [ 'product' => [ old_id => new_id, ... ], 'category' => [ old_id => new_id, ... ] ]
     */
    public static function get_mappings() : array {
        $map = get_option( self::OPTION_KEY, [] );
        if ( ! is_array( $map ) ) { $map = []; }
        $map['product']  = isset($map['product']) && is_array($map['product']) ? array_map('intval', $map['product']) : [];
        $map['category'] = isset($map['category']) && is_array($map['category']) ? array_map('intval', $map['category']) : [];
        return $map;
    }

    public static function save_mappings( array $map ) : bool {
        return update_option( self::OPTION_KEY, $map, false );
    }

    public static function apply( int $id, string $type ) : int {
        $type = ($type === 'category') ? 'category' : 'product';
        $map = self::get_mappings();
        if ( !isset($map[$type]) || !is_array($map[$type]) ) { return $id; }
        // Zinciri son hedefe kadar çöz (A->B->C ise C dön)
        $visited = [];
        $cur = (int)$id;
        while ( isset($map[$type][$cur]) ) {
            if ( isset($visited[$cur]) ) { break; } // güvenlik
            $visited[$cur] = true;
            $cur = (int)$map[$type][$cur];
        }
        return $cur;
    }

    public static function set_mapping( string $type, int $old_id, int $new_id ) : bool {
        $type = ($type === 'category') ? 'category' : 'product';
        $map = self::get_mappings();
        if ( ! isset($map[$type]) || ! is_array($map[$type]) ) { $map[$type] = []; }
        // Basit doğrulamalar
        if ( $old_id <= 0 || $new_id <= 0 ) { return false; }
        if ( $old_id === $new_id ) { return false; }
        // Döngü kontrolü: new_id'den başlayan zinciri takip et, old_id'ye ulaşılırsa engelle
        $visited = [];
        $cur = (int)$new_id;
        while ( isset($map[$type][$cur]) ) {
            if ( $cur === $old_id ) { return false; }
            if ( isset($visited[$cur]) ) { break; } // mevcut haritada hali hazırda döngü varsa kır
            $visited[$cur] = true;
            $cur = (int)$map[$type][$cur];
        }
        $map[$type][$old_id] = $new_id;
        return self::save_mappings( $map );
    }

    public static function remove_mapping( string $type, int $old_id ) : bool {
        $type = ($type === 'category') ? 'category' : 'product';
        $map = self::get_mappings();
        if ( isset($map[$type][$old_id]) ) { unset($map[$type][$old_id]); }
        return self::save_mappings( $map );
    }

    public static function list_mappings() : array {
        return self::get_mappings();
    }
}
