<?php

function ds1_register_dynamic_columns($columns_config) {
    foreach ($columns_config as $config) {
        $post_type = $config['post_type'];
        $cols = $config['cols'];

        add_filter("manage_{$post_type}_posts_columns", function ($defaults) use ($cols) {
            foreach ($cols as $col) {
                $defaults[$col['id']] = $col['title'];
            }
            return $defaults;
        });

        add_action("manage_{$post_type}_posts_custom_column", function ($column_name, $post_ID) use ($cols) {
            foreach ($cols as $col) {
                if ($col['id'] !== $column_name) continue;
                $q_type = $col['q_type'] ?? '';
                $q_id = $col['q_id'] ?? '';

                switch ($q_type) {
                    case 'terms':
                        $terms = get_the_terms($post_ID, $q_id);
                        if ($terms && is_array($terms)) {
                            echo esc_html($terms[0]->name);
                        }
                        break;

                    case 'post_meta':
                        echo esc_html(get_post_meta($post_ID, $q_id, true));
                        break;

                    case 'acf':
                        if (function_exists('get_field')) {
                            echo esc_html(get_field($q_id, $post_ID));
                        }
                        break;

                    case 'image':
                        echo get_the_post_thumbnail($post_ID, [60, 60]);
                        break;

                    case 'modified_date':
                        echo get_the_modified_date('Y/m/d', $post_ID) . '<br>' . get_the_modified_author();
                        break;

                    case 'author':
                        $author = get_post_field('post_author', $post_ID);
                        echo esc_html(get_the_author_meta('display_name', $author));
                        break;

                    case 'post_status':
                        echo esc_html(get_post_status($post_ID));
                        break;

                    case 'post_date':
                        echo get_the_date('', $post_ID);
                        break;

                    case 'custom_callback':
                        if (is_callable($col['callback'])) {
                            call_user_func($col['callback'], $post_ID);
                        }
                        break;
                }
            }
        }, 10, 2);
    }
}

// نفّذ عند init أو admin_init
add_action('init', function () {
    ds1_register_dynamic_columns( checkSettings("types_table_columns") );
});