<?php

if (!defined('ABSPATH')) { exit; }
require_once __DIR__ . '/class-aieo-dmm-insights-report.php';

class AIEO_DMM_Insights_Manage extends AIEO_DMM_Insights_Base {

    const DEFAULT_MENU_ID = 9684;

    public function get_id()       { return 'insights_manage'; }
    public function get_label()    { return __('⚙ Manage tables', 'ai-eshop-optimizer'); }
    public function get_priority() { return 200; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_insights_save_map', array($this, 'ajax_save_map'));
        add_action('wp_ajax_aieo_insights_seed',     array($this, 'ajax_seed'));
    }

    

    public function ajax_save_map() {
        AIEO_DMM::verify_ajax_request();
        $raw     = isset($_POST['map_json']) ? json_decode((string) wp_unslash($_POST['map_json']), true) : array(); 
        $old     = self::get_map();
        $catalog = self::catalog();

        
        
        $known = array();
        foreach ($old as $rows) {
            foreach ($rows as $r) {
                if (!empty($r['label'])) { $known[(int) $r['id']] = (string) $r['label']; }
            }
        }

        $out = array();
        foreach (self::section_keys() as $sk) {
            $ids  = (is_array($raw) && isset($raw[$sk]) && is_array($raw[$sk]))
                ? array_values(array_unique(array_filter(array_map('intval', $raw[$sk]))))
                : array();
            $rows = array();
            foreach ($ids as $id) {
                $rows[] = array('id' => $id, 'label' => self::label_for($id, isset($known[$id]) ? $known[$id] : ''));
            }
            $out[$sk] = $rows;
        }
        update_option(self::OPTION, $out, false);
        wp_send_json_success(array('message' => __('Saved.', 'ai-eshop-optimizer')));
    }

    public function ajax_seed() {
        AIEO_DMM::verify_ajax_request();
        $menu_id = isset($_POST['menu_id']) ? (int) $_POST['menu_id'] : self::DEFAULT_MENU_ID;
        $map     = self::seed_from_menu($menu_id);
        if ($map === null) {
            wp_send_json_error(array('message' => sprintf( __('Menu %d not found or empty.', 'ai-eshop-optimizer'), $menu_id)));
        }
        update_option(self::OPTION, $map, false);
        wp_send_json_success(array(
            'message' => sprintf( __('Seeded from menu %d.', 'ai-eshop-optimizer'), $menu_id),
            'map'     => $map,
        ));
    }

    
    public static function seed_from_menu($menu_id) {
        $items = wp_get_nav_menu_items((int) $menu_id);
        if (empty($items)) { return null; }

        $sections = self::section_keys();
        $map      = array();
        foreach ($sections as $sk) { $map[$sk] = array(); }

        $sec_idx = -1;
        $cur     = null;
        foreach ($items as $it) {
            $url       = isset($it->url) ? trim((string) $it->url) : '';
            $is_header = ($it->type === 'custom' && ($url === '#' || $url === ''));
            if ($is_header) {
                $sec_idx++;
                $cur = isset($sections[$sec_idx]) ? $sections[$sec_idx] : null;
                continue;
            }
            if (!$cur) { continue; }

            
            $page_id = 0;
            if ($it->type === 'post_type' && (int) $it->object_id > 0) {
                $page_id = (int) $it->object_id;
            } elseif ($url !== '') {
                $path = (strpos($url, 'http') === 0) ? (string) wp_parse_url($url, PHP_URL_PATH) : $url;
                $slug = trim((string) $path, '/');
                if ($slug !== '') {
                    $pg = get_page_by_path($slug);
                    if ($pg) { $page_id = (int) $pg->ID; }
                    if ($page_id <= 0) { $page_id = (int) url_to_postid(home_url('/' . $slug . '/')); }
                }
            }
            if ($page_id <= 0) { continue; }

            $post = get_post($page_id);
            if (!$post) { continue; }
            
            
            
            
            if (!preg_match_all('/\[wpdatatable\b[^\]]*\bid\s*=\s*["\']?(\d+)/i', (string) $post->post_content, $mm)) {
                continue; 
            }
            $first = true;
            foreach (array_values(array_unique(array_map('intval', $mm[1]))) as $tid) {
                if ($tid <= 0) { continue; }
                $fallback = $first ? (string) $it->title : '';
                $map[$cur][] = array('id' => $tid, 'label' => self::label_for($tid, $fallback));
                $first = false;
            }
        }

        
        foreach ($map as $sk => $rows) {
            $seen = array(); $clean = array();
            foreach ($rows as $r) {
                if (isset($seen[$r['id']])) { continue; }
                $seen[$r['id']] = true; $clean[] = $r;
            }
            $map[$sk] = $clean;
        }
        return $map;
    }

    

    public function render_subtab() {
        $catalog  = self::catalog();
        $map      = self::get_map();
        $sections = self::section_labels();
        $nonce    = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax     = admin_url('admin-ajax.php');

        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Manage e-Shop Insights', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description" style="max-width:840px;">'
            . esc_html__('Assign wpDataTables to each section. Every assigned table becomes its own report page, linked under its section in the e-Shop Insights panel. “Seed from logistics menu” pre-fills everything (using your menu’s labels) so the panel mirrors it.', 'ai-eshop-optimizer')
            . '</p>';

        if (empty($catalog)) {
            echo '<div class="aieo-dmm-card"><p style="color:#b91c1c;">' . esc_html__('wpDataTables is not active / no tables found.', 'ai-eshop-optimizer') . '</p></div>';
            echo '</div>';
            return;
        }

        echo '<div class="aieo-dmm-card">';
        echo '<h3 style="margin-top:0;">' . esc_html__('Seed from logistics menu', 'ai-eshop-optimizer') . '</h3>';
        echo '<p class="description">' . esc_html__('Reads a WP nav menu (its section headers map in order onto the six sections) and detects each linked page’s wpDataTable. Overwrites the assignments below.', 'ai-eshop-optimizer') . '</p>';
        echo '<p><label>' . esc_html__('Menu ID', 'ai-eshop-optimizer') . ' '
            . '<input type="number" id="aieo-ins-menu" value="' . esc_attr(self::DEFAULT_MENU_ID) . '" style="width:100px;"></label> ';
        echo '<button type="button" class="button" id="aieo-ins-seed">' . esc_html__('Seed from menu', 'ai-eshop-optimizer') . '</button> ';
        echo '<span id="aieo-ins-seed-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p>';
        echo '</div>';

        echo '<div class="aieo-dmm-card" style="margin-top:14px;">';
        echo '<h3 style="margin-top:0;">' . esc_html__('Section → reports', 'ai-eshop-optimizer') . '</h3>';
        echo '<table class="form-table" role="presentation"><tbody>';
        foreach ($sections as $sk => $label) {
            $sel = array();
            if (isset($map[$sk])) { foreach ($map[$sk] as $r) { $sel[] = (int) $r['id']; } }
            echo '<tr>';
            echo '<th scope="row" style="width:200px;">' . esc_html($label) . '</th>';
            echo '<td><select multiple size="12" class="aieo-ins-sel" data-section="' . esc_attr($sk) . '" style="width:100%;max-width:620px;">';
            foreach ($catalog as $id => $title) {
                $opt = ($title !== '' ? $title : ('#' . $id)) . ' (#' . $id . ')';
                echo '<option value="' . esc_attr($id) . '" ' . (in_array((int) $id, $sel, true) ? 'selected' : '') . '>' . esc_html($opt) . '</option>';
            }
            echo '</select></td></tr>';
        }
        echo '</tbody></table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-ins-save">' . esc_html__('Save assignments', 'ai-eshop-optimizer') . '</button> '
            . '<span id="aieo-ins-save-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p>';
        echo '<p class="description">' . esc_html__('Reports use the seeded menu label, or the wpDataTable title. Hold Ctrl/Cmd to select multiple. Reload after saving to see the panel update.', 'ai-eshop-optimizer') . '</p>';
        echo '</div>';
        ?>
        <script>
        (function(){
            var ajax = <?php echo wp_json_encode($ajax); ?>;
            var nonce = <?php echo wp_json_encode($nonce); ?>;
            function post(action, extra){
                var fd = new FormData(); fd.set('action', action); fd.set('nonce', nonce);
                if (extra) { Object.keys(extra).forEach(function(k){ fd.set(k, extra[k]); }); }
                return fetch(ajax, {method:'POST', body:fd, credentials:'same-origin'}).then(function(r){return r.json();});
            }
            // Native multi-select list box (size=12) — shows all tables inline,
            // selected rows highlighted; no confusing collapsed widget.
            var saveBtn = document.getElementById('aieo-ins-save');
            var saveStatus = document.getElementById('aieo-ins-save-status');
            saveBtn && saveBtn.addEventListener('click', function(){
                var map = {};
                document.querySelectorAll('.aieo-ins-sel').forEach(function(sel){
                    map[sel.getAttribute('data-section')] = Array.prototype.filter.call(sel.options, function(o){return o.selected;}).map(function(o){return parseInt(o.value,10);});
                });
                saveStatus.style.color='#646970'; saveStatus.textContent='<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>';
                post('aieo_insights_save_map', {map_json: JSON.stringify(map)}).then(function(j){
                    if (j && j.success) { saveStatus.style.color='#15803d'; saveStatus.textContent=j.data.message+' — '+'<?php echo esc_js(__('reloading…', 'ai-eshop-optimizer')); ?>'; setTimeout(function(){location.reload();},900); }
                    else { saveStatus.style.color='#b91c1c'; saveStatus.textContent=(j&&j.data&&j.data.message)||'error'; }
                }).catch(function(){ saveStatus.style.color='#b91c1c'; saveStatus.textContent='network error'; });
            });

            var seedBtn = document.getElementById('aieo-ins-seed');
            var seedStatus = document.getElementById('aieo-ins-seed-status');
            seedBtn && seedBtn.addEventListener('click', function(){
                if (!confirm('<?php echo esc_js(__('Seed from the menu? This overwrites the current assignments.', 'ai-eshop-optimizer')); ?>')) return;
                var menuId = document.getElementById('aieo-ins-menu').value || '<?php echo esc_js((string) self::DEFAULT_MENU_ID); ?>';
                seedBtn.disabled=true; seedStatus.style.color='#646970'; seedStatus.textContent='<?php echo esc_js(__('Seeding…', 'ai-eshop-optimizer')); ?>';
                post('aieo_insights_seed', {menu_id: menuId}).then(function(j){
                    seedBtn.disabled=false;
                    if (j && j.success) { seedStatus.style.color='#15803d'; seedStatus.textContent=j.data.message+' — '+'<?php echo esc_js(__('reloading…', 'ai-eshop-optimizer')); ?>'; setTimeout(function(){location.reload();},900); }
                    else { seedStatus.style.color='#b91c1c'; seedStatus.textContent=(j&&j.data&&j.data.message)||'error'; }
                }).catch(function(){ seedBtn.disabled=false; seedStatus.style.color='#b91c1c'; seedStatus.textContent='network error'; });
            });
        })();
        </script>
        <?php
        echo '</div>';
    }
}
