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

if ( defined('WP_CLI') && WP_CLI ) {
    /**
     * KNS Dynamic Discounts - WP-CLI Komutları
     */
    class KNSDD_CLI {
        /**
         * usage_log meta içinde snapshot olmayan line_item kayıtlarına snapshot ekler.
         *
         * ## OPTIONS
         * [--order_id=<id>]
         * : Belirli bir siparişe sınırlamak için.
         *
         * [--batch=<n>]
         * : Her döngüde işlenecek kayıt sayısı (varsayılan 500).
         *
         * [--dry-run]
         * : Yazmadan sadece sayım/önizleme yapar.
         *
         * ## EXAMPLES
         * wp knsdd backfill-snapshots --batch=200 --dry-run
         * wp knsdd backfill-snapshots --order_id=1234
         */
        public function backfill_snapshots( $args, $assoc_args ) {
            global $wpdb;
            $usage_table = $wpdb->prefix . 'knsdd_usage_log';
            $oi_table    = $wpdb->prefix . 'woocommerce_order_items';
            $oim_table   = $wpdb->prefix . 'woocommerce_order_itemmeta';

            $target_order_id = isset($assoc_args['order_id']) ? (int)$assoc_args['order_id'] : 0;
            $batch           = isset($assoc_args['batch']) ? max(1, (int)$assoc_args['batch']) : 500;
            $dry             = isset($assoc_args['dry-run']);

            $where = "WHERE meta LIKE '%\"type\":\"line_item\"%' AND meta NOT LIKE '%\"snapshot\"%'";
            $params = [];
            if ( $target_order_id > 0 ) {
                $where .= " AND order_id = %d";
                $params[] = $target_order_id;
            }

            $offset = 0; $updated = 0; $seen = 0;
            do {
                $sql = "SELECT id, order_id, meta FROM {$usage_table} {$where} ORDER BY id ASC LIMIT %d OFFSET %d";
                $query_params = $params; $query_params[] = $batch; $query_params[] = $offset;
                $rows = $wpdb->get_results( empty($query_params) ? $sql : $wpdb->prepare($sql, $query_params) );
                if ( empty($rows) ) { break; }

                foreach ( $rows as $row ) {
                    $seen++;
                    $meta = json_decode( $row->meta, true );
                    if ( !is_array($meta) ) { continue; }
                    $order_id = (int)$row->order_id;
                    $order_item_id = isset($meta['order_item_id']) ? (int)$meta['order_item_id'] : 0;
                    if ( $order_item_id <= 0 ) { continue; }

                    // Order item name ve product_id oku
                    $oi = $wpdb->get_row( $wpdb->prepare(
                        "SELECT order_item_name FROM {$oi_table} WHERE order_item_id = %d",
                        $order_item_id
                    ) );
                    $product_id = (int)$wpdb->get_var( $wpdb->prepare(
                        "SELECT meta_value FROM {$oim_table} WHERE order_item_id = %d AND meta_key = '_product_id' LIMIT 1",
                        $order_item_id
                    ) );

                    $product_name = '';
                    if ( $oi && isset($oi->order_item_name) ) { $product_name = (string)$oi->order_item_name; }
                    // Kategori bilgileri (tarihsel olarak tutulmaz; mevcut taksonomiye göre yaklaşık doldurulur)
                    $category_ids = [];
                    $category_names = [];
                    if ( $product_id > 0 && function_exists('wc_get_product_term_ids') ) {
                        $term_ids = (array) wc_get_product_term_ids( $product_id, 'product_cat' );
                        $category_ids = array_map('intval', $term_ids);
                        foreach ( $category_ids as $cid ) {
                            if ( function_exists('get_term') ) {
                                $term = get_term( $cid, 'product_cat' );
                                if ( $term && ! is_wp_error($term) ) {
                                    $category_names[] = (string)$term->name;
                                } else {
                                    $category_names[] = (string)$cid;
                                }
                            } else {
                                $category_names[] = (string)$cid;
                            }
                        }
                    }

                    $meta['snapshot'] = array(
                        'product_id'     => $product_id,
                        'product_name'   => $product_name,
                        'category_ids'   => $category_ids,
                        'category_names' => $category_names,
                    );

                    if ( $dry ) { continue; }
                    $new_meta = wp_json_encode( $meta );
                    $ok = $wpdb->update( $usage_table, [ 'meta' => $new_meta ], [ 'id' => (int)$row->id ], [ '%s' ], [ '%d' ] );
                    if ( $ok !== false ) { $updated++; }
                }

                $offset += $batch;
                if ( $dry ) { WP_CLI::log( sprintf('Dry-run: processed %d so far, next offset %d', $seen, $offset) ); }
            } while ( true );

            if ( $dry ) {
                WP_CLI::success( sprintf('Dry-run tamamlandı. İşlenen kayıt: %d', $seen) );
            } else {
                WP_CLI::success( sprintf('Backfill tamamlandı. Güncellenen kayıt: %d / İşlenen: %d', $updated, $seen) );
            }
        }

        /**
         * ID alias/merge ekler (eski -> yeni). Tür: product|category
         *
         * ## OPTIONS
         * <type>
         * : 'product' veya 'category'
         *
         * <old_id>
         * : Eski ID (int)
         *
         * <new_id>
         * : Yeni ID (int)
         *
         * ## EXAMPLES
         * wp knsdd alias-add product 12 34
         */
        public function alias_add( $args, $assoc_args ) {
            list($type, $old_id, $new_id) = array_pad($args, 3, null);
            $type = in_array($type, ['product','category'], true) ? $type : 'product';
            $old_id = (int)$old_id; $new_id = (int)$new_id;
            if ( $old_id <= 0 || $new_id <= 0 ) { WP_CLI::error('Geçersiz ID'); return; }
            if ( $old_id === $new_id ) { WP_CLI::error('old_id ve new_id aynı olamaz'); return; }
            $ok = KNSDD_Alias::set_mapping( $type, $old_id, $new_id );
            if ( $ok ) { WP_CLI::success( sprintf('%s alias eklendi: %d -> %d', ucfirst($type), $old_id, $new_id) ); }
            else { WP_CLI::error('Alias kaydedilemedi'); }
        }

        /**
         * ID alias/merge kaldırır.
         *
         * ## OPTIONS
         * <type>
         * : 'product' veya 'category'
         *
         * <old_id>
         * : Silinecek eski ID (int)
         *
         * ## EXAMPLES
         * wp knsdd alias-remove product 12
         */
        public function alias_remove( $args, $assoc_args ) {
            list($type, $old_id) = array_pad($args, 2, null);
            $type = in_array($type, ['product','category'], true) ? $type : 'product';
            $old_id = (int)$old_id;
            if ( $old_id <= 0 ) { WP_CLI::error('Geçersiz ID'); return; }
            $ok = KNSDD_Alias::remove_mapping( $type, $old_id );
            if ( $ok ) { WP_CLI::success( sprintf('%s alias kaldırıldı: %d', ucfirst($type), $old_id) ); }
            else { WP_CLI::error('Alias kaldırılamadı'); }
        }

        /**
         * Kayıtlı tüm alias eşlemelerini listeler.
         *
         * ## EXAMPLES
         * wp knsdd alias-list
         */
        public function alias_list( $args, $assoc_args ) {
            $map = KNSDD_Alias::list_mappings();
            $out = [
                [ 'type' => 'product',  'old_id' => '', 'new_id' => '' ],
            ];
            $rows = [];
            foreach ( ['product','category'] as $t ) {
                if ( !isset($map[$t]) || !is_array($map[$t]) ) { continue; }
                foreach ( $map[$t] as $old => $new ) {
                    $rows[] = [ 'type' => $t, 'old_id' => (int)$old, 'new_id' => (int)$new ];
                }
            }
            if ( empty($rows) ) {
                WP_CLI::log('Alias eşlemesi yok.');
                return;
            }
            // Basit tablo yazdır
            WP_CLI\Utils\format_items( 'table', $rows, [ 'type','old_id','new_id' ] );
        }
    }

    // Komutu kaydet
    WP_CLI::add_command( 'knsdd', 'KNSDD_CLI' );
}
