<?php

if (!defined('ABSPATH')) {
    exit;
}

abstract class AIEO_DMM_Insights_Base extends AIEO_DMM_Module_Base {

    
    const OPTION = 'aieo_insights_tables';

    
    public function get_group() { return 'eshop_insights'; }

    
    public static function section_defs() {
        return array(
            array('id' => 'stock_management',     'label' => __('Stock Management', 'ai-eshop-optimizer')),
            array('id' => 'behavioural',          'label' => __('Behavioural', 'ai-eshop-optimizer')),
            array('id' => 'sales_reports',        'label' => __('Sales Reports', 'ai-eshop-optimizer')),
            array('id' => 'comparative_turnover', 'label' => __('Comparative Turnover', 'ai-eshop-optimizer')),
            array('id' => 'stock_reordering',     'label' => __('Stock Reordering', 'ai-eshop-optimizer')),
            array('id' => 'helpers',              'label' => __('Helpers', 'ai-eshop-optimizer')),
        );
    }

    
    public static function section_keys() {
        return array_map(static function ($s) { return $s['id']; }, self::section_defs());
    }

    
    public static function section_labels() {
        $out = array();
        foreach (self::section_defs() as $s) { $out[$s['id']] = $s['label']; }
        return $out;
    }

    
    public static function get_map() {
        $raw = get_option(self::OPTION, array());
        if (!is_array($raw)) { return array(); }
        $out = array();
        foreach (self::section_keys() as $sk) {
            $rows = isset($raw[$sk]) && is_array($raw[$sk]) ? $raw[$sk] : array();
            $clean = array();
            foreach ($rows as $r) {
                if (is_array($r)) {
                    $id = isset($r['id']) ? (int) $r['id'] : 0;
                    $lb = isset($r['label']) ? (string) $r['label'] : '';
                } else {
                    $id = (int) $r; $lb = ''; 
                }
                if ($id > 0) { $clean[] = array('id' => $id, 'label' => $lb); }
            }
            $out[$sk] = $clean;
        }
        return $out;
    }

    
    public static function catalog() {
        static $cache = null;
        if ($cache !== null) { return $cache; }
        global $wpdb;
        $t = $wpdb->prefix . 'wpdatatables';
        
        if ((string) $wpdb->get_var("SHOW TABLES LIKE '{$t}'") !== $t) { $cache = array(); return $cache; }
        
        $rows = $wpdb->get_results("SELECT id, title FROM `{$t}` ORDER BY title", ARRAY_A);
        $out  = array();
        foreach ((array) $rows as $r) { $out[(int) $r['id']] = isset($r['title']) ? (string) $r['title'] : ''; }
        $cache = $out;
        return $cache;
    }

    
    public static function curated_labels() {
        return array(
            18 => __('Out of Stock Date', 'ai-eshop-optimizer'),
            20 => __('Out of Stock Products', 'ai-eshop-optimizer'),
            27 => __('Out of Stock Variations', 'ai-eshop-optimizer'),
            26 => __('Out of Stock Variations Ratio', 'ai-eshop-optimizer'),
            14 => __('Stock Fast Finder', 'ai-eshop-optimizer'),
            15 => __('Stock Not Set — Fast Finder', 'ai-eshop-optimizer'),
            8  => __('Single Choice in Cart', 'ai-eshop-optimizer'),
            6  => __('First Choice in Cart', 'ai-eshop-optimizer'),
            7  => __('Last Choice in Cart', 'ai-eshop-optimizer'),
            43 => __('Google Analytics — View Product Events', 'ai-eshop-optimizer'),
            32 => __('Total Unit Sales Statistics', 'ai-eshop-optimizer'),
            33 => __('ERP Raw Order Data', 'ai-eshop-optimizer'),
            5  => __('All Products in Carts', 'ai-eshop-optimizer'),
            3  => __('Order Patterns', 'ai-eshop-optimizer'),
            4  => __('Order Cumulative Statistics', 'ai-eshop-optimizer'),
            13 => __('Order Survey Stats', 'ai-eshop-optimizer'),
            41 => __('Woo vs ERP Turnover — Current Month', 'ai-eshop-optimizer'),
            40 => __('Woo vs ERP Turnover — Previous Month', 'ai-eshop-optimizer'),
            42 => __('Woo vs ERP Turnover — Historical', 'ai-eshop-optimizer'),
            35 => __('Reorder Summary', 'ai-eshop-optimizer'),
            34 => __('Reorders — Keratsini', 'ai-eshop-optimizer'),
            28 => __('Needs Filter Management', 'ai-eshop-optimizer'),
        );
    }

    
    public static function label_for($table_id, $fallback = '') {
        $table_id = (int) $table_id;
        $curated  = self::curated_labels();
        if (isset($curated[$table_id]) && $curated[$table_id] !== '') { return $curated[$table_id]; }
        $cat = self::catalog();
        if (isset($cat[$table_id]) && $cat[$table_id] !== '') { return $cat[$table_id]; }
        $fallback = trim((string) $fallback);
        return $fallback !== '' ? $fallback : ('#' . $table_id);
    }

    
    protected function render_table($id) {
        $id = (int) $id;
        if ($id <= 0) { return; }
        self::print_report_table_styles();
        
        echo do_shortcode('[wpdatatable id=' . $id . ' table_view=regular]');
    }

    
    protected static function print_report_table_styles() {
        static $done = false;
        if ($done) { return; }
        $done = true;
        echo '<style id="aieo-insights-table-css">'
            . '.aieo-dmm-card table.wpDataTable img,'
            . '.aieo-dmm-card .wpDataTablesWrapper img,'
            . '.aieo-dmm-card .wpdt-c img{'
            . 'max-height:100px!important;width:auto!important;height:auto!important;'
            . 'max-width:100px;object-fit:contain;display:inline-block;}'
            . '.aieo-dmm-card table.wpDataTable td{vertical-align:top;}'
            . '.aieo-dmm-card table.wpDataTable td a{display:inline-block;}'
            
            
            
            . '.aieo-dmm-card .wpDataTablesWrapper{position:relative;z-index:0;isolation:isolate;}'
            . '</style>';
    }
}
