<?php

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

if (defined('AIEO_DIR')) {
    foreach (array(
        'includes/dmm/catalog-importer/interface-aieo-catalog-source.php',
        'includes/dmm/catalog-importer/class-aieo-efood-catalog-source.php',
        'includes/dmm/catalog-importer/class-aieo-etsy-catalog-source.php',
        'includes/dmm/catalog-importer/class-aieo-wolt-catalog-source.php',
        'includes/dmm/catalog-importer/class-aieo-amazon-catalog-source.php',
        'includes/dmm/catalog-importer/class-aieo-catalog-import-runner.php',
    ) as $aieo_cati_rel) {
        $aieo_cati_path = AIEO_DIR . $aieo_cati_rel;
        if (file_exists($aieo_cati_path)) { require_once $aieo_cati_path; }
    }
}

class AIEO_DMM_Catalog_Importer extends AIEO_DMM_Module_Base {

    const NONCE     = 'aieo_catalog_import';
    const PAGE_SIZE = 50;

    public function get_id()       { return 'catalog_importer'; }
    public function get_label()    { return __('Catalogue Importer', 'ai-eshop-optimizer'); }
    public function get_priority() { return 66; } 
    public function get_group()    { return 'import_export'; } 

    public function register_hooks() {
        add_action('wp_ajax_aieo_catalog_import_save_conn', array($this, 'ajax_save_conn'));
        add_action('wp_ajax_aieo_catalog_import_test',      array($this, 'ajax_test'));
        add_action('wp_ajax_aieo_catalog_import_start',     array($this, 'ajax_import_start'));
        add_action('wp_ajax_aieo_catalog_import_process',   array($this, 'ajax_import_process'));
    }

    
    private function sources() {
        $list = array();
        foreach (array('AIEO_Efood_Catalog_Source', 'AIEO_Etsy_Catalog_Source', 'AIEO_Wolt_Catalog_Source', 'AIEO_Amazon_Catalog_Source') as $cls) {
            if (class_exists($cls)) {
                $s = new $cls();
                $list[$s->slug()] = $s;
            }
        }
        return apply_filters('aieo_catalog_import_sources', $list);
    }

    private function source($slug) {
        $all = $this->sources();
        return isset($all[$slug]) ? $all[$slug] : null;
    }

    
    
    

    private function creds_option($slug) { return 'aieo_catalog_import_' . sanitize_key($slug); }

    
    private function get_creds($slug) {
        $creds = get_option($this->creds_option($slug), array());
        if (!is_array($creds)) { $creds = array(); }
        $needed  = array('chain_id', 'vendor_id', 'client_id', 'client_secret');
        $missing = false;
        foreach ($needed as $k) { if (empty($creds[$k])) { $missing = true; break; } }
        if ($missing) {
            $v = $this->moi_vendor_creds($slug);
            foreach (array('chain_id', 'vendor_id', 'client_id', 'client_secret', 'base_url') as $k) {
                if (empty($creds[$k]) && !empty($v[$k])) { $creds[$k] = $v[$k]; }
            }
        }
        return $creds;
    }

    
    private function moi_vendor_creds($provider) {
        global $wpdb;
        $tbl = $wpdb->prefix . 'aieo_moi_vendors';
        if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $tbl)) !== $tbl) { return array(); }
        $json = $wpdb->get_var($wpdb->prepare("SELECT credentials_json FROM {$tbl} WHERE provider = %s AND enabled = 1 ORDER BY id ASC LIMIT 1", $provider));
        if (!$json) { return array(); }
        $d = json_decode((string) $json, true);
        return is_array($d) ? $d : array();
    }

    private function can() {
        return current_user_can('manage_woocommerce') || current_user_can('manage_options');
    }

    private function check($ok = true) {
        if (!check_ajax_referer(self::NONCE, 'nonce', false)) { wp_send_json_error(array('message' => __('Security check failed.', 'ai-eshop-optimizer'))); }
        if (!$this->can()) { wp_send_json_error(array('message' => __('Not allowed.', 'ai-eshop-optimizer'))); }
    }

    
    
    

    public function ajax_save_conn() {
        $this->check();
        $slug   = isset($_POST['slug']) ? sanitize_key(wp_unslash($_POST['slug'])) : '';
        $source = $this->source($slug);
        if (!$source) { wp_send_json_error(array('message' => __('Unknown source.', 'ai-eshop-optimizer'))); }

        $existing = get_option($this->creds_option($slug), array());
        if (!is_array($existing)) { $existing = array(); }
        $new = $existing;
        foreach ($source->credential_fields() as $f) {
            $name = (string) $f['name'];
            $key  = 'cred_' . $name;
            if (!isset($_POST[$key])) { continue; }
            $val = sanitize_text_field(wp_unslash($_POST[$key]));
            
            if (($f['type'] ?? 'text') === 'password' && $val === '') { continue; }
            $new[$name] = $val;
        }
        update_option($this->creds_option($slug), $new, false);
        wp_send_json_success(array('saved' => true));
    }

    public function ajax_test() {
        $this->check();
        $slug   = isset($_POST['slug']) ? sanitize_key(wp_unslash($_POST['slug'])) : '';
        $source = $this->source($slug);
        if (!$source) { wp_send_json_error(array('message' => __('Unknown source.', 'ai-eshop-optimizer'))); }
        $creds = $this->get_creds($slug);
        $valid = $source->validate_credentials($creds);
        if (is_wp_error($valid)) { wp_send_json_error(array('message' => $valid->get_error_message())); }

        $cats = $source->fetch_categories($creds);
        if (is_wp_error($cats)) { wp_send_json_error(array('message' => $cats->get_error_message())); }
        $page = $source->fetch_page($creds, 1, 5);
        if (is_wp_error($page)) { wp_send_json_error(array('message' => $page->get_error_message())); }

        $ctx     = array('categories' => $cats, 'options' => array());
        $samples = '';
        foreach (array_slice((array) $page['products'], 0, 5) as $raw) {
            if (!is_array($raw)) { continue; }
            $m = $source->map_product($raw, $ctx);
            $p = isset($m['payload']) ? $m['payload'] : array();
            $samples .= '<tr><td>' . esc_html((string) ($p['title'] ?? '')) . '</td>'
                      . '<td><code>' . esc_html((string) ($p['match']['sku'] ?? '')) . '</code></td>'
                      . '<td>' . esc_html((string) ($p['regular_price'] ?? '')) . '</td>'
                      . '<td>' . esc_html((string) ($p['stock']['status'] ?? '')) . '</td>'
                      . '<td>' . (int) count((array) ($p['category_terms'] ?? array())) . '</td></tr>';
        }
        $html  = '<p style="margin:6px 0;color:#1a7f37;">' . esc_html(sprintf(
            
            __('Connected ✓ — %1$s categories, %2$s product page(s) of catalogue.', 'ai-eshop-optimizer'),
            number_format_i18n(count((array) $cats)),
            number_format_i18n((int) $page['total_pages'])
        )) . '</p>';
        $html .= '<table class="widefat striped" style="max-width:760px;"><thead><tr>'
               . '<th>' . esc_html__('Title', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('SKU', 'ai-eshop-optimizer') . '</th>'
               . '<th>' . esc_html__('Price', 'ai-eshop-optimizer') . '</th><th>' . esc_html__('Stock', 'ai-eshop-optimizer') . '</th>'
               . '<th>' . esc_html__('Cats', 'ai-eshop-optimizer') . '</th></tr></thead><tbody>'
               . ($samples !== '' ? $samples : '<tr><td colspan="5">' . esc_html__('No products returned.', 'ai-eshop-optimizer') . '</td></tr>')
               . '</tbody></table>';
        wp_send_json_success(array('html' => $html));
    }

    
    
    

    public function ajax_import_start() {
        $this->check();
        $slug   = isset($_POST['slug']) ? sanitize_key(wp_unslash($_POST['slug'])) : '';
        $source = $this->source($slug);
        if (!$source) { wp_send_json_error(array('message' => __('Unknown source.', 'ai-eshop-optimizer'))); }
        $creds = $this->get_creds($slug);
        $valid = $source->validate_credentials($creds);
        if (is_wp_error($valid)) { wp_send_json_error(array('message' => $valid->get_error_message())); }

        $options = array(
            'status'        => (isset($_POST['opt_status']) && $_POST['opt_status'] === 'publish') ? 'publish' : 'draft',
            'mode'          => isset($_POST['opt_mode']) ? sanitize_key(wp_unslash($_POST['opt_mode'])) : 'new_only',
            'images'        => !empty($_POST['opt_images']) ? 1 : 0,
            'categories'    => !empty($_POST['opt_categories']) ? 1 : 0,
            'option_groups' => !empty($_POST['opt_option_groups']) ? 1 : 0,
        );
        if (!in_array($options['mode'], array('new_only', 'enrich', 'create_update', 'update_only'), true)) { $options['mode'] = 'new_only'; }

        $cats = $source->fetch_categories($creds);
        if (is_wp_error($cats)) { wp_send_json_error(array('message' => $cats->get_error_message())); }
        $page1 = $source->fetch_page($creds, 1, self::PAGE_SIZE);
        if (is_wp_error($page1)) { wp_send_json_error(array('message' => $page1->get_error_message())); }
        $total_pages = max(1, (int) $page1['total_pages']);

        global $wpdb;
        $job_id = wp_generate_password(16, false, false);
        $wpdb->insert($wpdb->prefix . 'aieo_dmm_export_jobs', array(
            'job_id'    => $job_id,
            'type'      => 'catalog_import',
            'status'    => 'running',
            'total'     => $total_pages,
            'processed' => 0,
            'params'    => wp_json_encode(array(
                'slug'         => $slug,
                'options'      => $options,
                'category_map' => $cats,
                'page_size'    => self::PAGE_SIZE,
                'totals'       => array('processed' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'errors' => 0, 'error_samples' => array()),
            )),
            'user_id'   => get_current_user_id(),
        ), array('%s', '%s', '%s', '%d', '%d', '%s', '%d'));

        wp_send_json_success(array('job_id' => $job_id, 'total_pages' => $total_pages));
    }

    public function ajax_import_process() {
        $this->check();
        $job_id = isset($_POST['job_id']) ? sanitize_text_field(wp_unslash($_POST['job_id'])) : '';
        global $wpdb;
        $jobs = $wpdb->prefix . 'aieo_dmm_export_jobs';
        $job  = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$jobs} WHERE job_id = %s", $job_id), ARRAY_A);
        if (!$job || $job['type'] !== 'catalog_import') { wp_send_json_error(array('message' => __('Invalid job.', 'ai-eshop-optimizer'))); }
        $params = json_decode((string) $job['params'], true);
        if (!is_array($params)) { wp_send_json_error(array('message' => __('Corrupted job.', 'ai-eshop-optimizer'))); }

        $slug   = (string) ($params['slug'] ?? '');
        $source = $this->source($slug);
        if (!$source) { wp_send_json_error(array('message' => __('Unknown source.', 'ai-eshop-optimizer'))); }

        $total_pages = max(1, (int) $job['total']);
        $page        = (int) $job['processed'] + 1;

        if ($page > $total_pages) {
            $wpdb->update($jobs, array('status' => 'done'), array('job_id' => $job_id));
            wp_send_json_success($this->progress($params, $total_pages, $total_pages, true));
        }

        $res = AIEO_Catalog_Import_Runner::run_batch(
            $source,
            $this->get_creds($slug),
            (array) $params['options'],
            (array) $params['category_map'],
            $page,
            (int) ($params['page_size'] ?? self::PAGE_SIZE)
        );
        if (is_wp_error($res)) {
            
            $params['totals']['errors']++;
            if (count($params['totals']['error_samples']) < 50) {
                $params['totals']['error_samples'][] = array('sku' => 'page ' . $page, 'error' => $res->get_error_message());
            }
        } else {
            $t = $res['tally'];
            foreach (array('processed', 'created', 'updated', 'skipped', 'errors') as $k) {
                $params['totals'][$k] = (int) $params['totals'][$k] + (int) $t[$k];
            }
            foreach ((array) $t['error_samples'] as $e) {
                if (count($params['totals']['error_samples']) < 50) { $params['totals']['error_samples'][] = $e; }
            }
            
            if ((int) $res['total_pages'] > $total_pages) { $total_pages = (int) $res['total_pages']; }
        }

        $complete = $page >= $total_pages;
        $wpdb->update($jobs, array(
            'processed' => $page,
            'total'     => $total_pages,
            'status'    => $complete ? 'done' : 'running',
            'params'    => wp_json_encode($params),
        ), array('job_id' => $job_id));

        wp_send_json_success($this->progress($params, $page, $total_pages, $complete));
    }

    private function progress($params, $page, $total_pages, $complete) {
        $pct = $total_pages > 0 ? (int) round(100 * min($page, $total_pages) / $total_pages) : 100;
        return array(
            'page'        => (int) $page,
            'total_pages' => (int) $total_pages,
            'percentage'  => $pct,
            'complete'    => (bool) $complete,
            'totals'      => $params['totals'],
        );
    }

    
    
    

    public function enqueue_admin_assets() {
        $cfg = 'window.aieoCati=' . wp_json_encode(array(
            'nonce'   => wp_create_nonce(self::NONCE),
            'ajaxurl' => admin_url('admin-ajax.php'),
        )) . ';';
        wp_register_script('aieo-cati-admin', false, array('jquery'), defined('AIEO_VERSION') ? AIEO_VERSION : '1', true);
        wp_enqueue_script('aieo-cati-admin');
        
        
        
        $js = <<<'JS'
jQuery(function($){
  var n=window.aieoCati.nonce, u=window.aieoCati.ajaxurl;
  function source(){ return $('#aieo-cati-source').val(); }
  function panel(slug){ return $('.aieo-cati-panel[data-slug="'+slug+'"]'); }
  $('#aieo-cati-source').on('change', function(){ var s=$(this).val(); $('.aieo-cati-panel').hide(); panel(s).show(); });
  $(document).on('click','.aieo-cati-save', function(){
    var slug=$(this).data('slug'), b=$(this), p=panel(slug); b.prop('disabled',true);
    var data={action:'aieo_catalog_import_save_conn', nonce:n, slug:slug};
    p.find('.aieo-cati-cred').each(function(){ data['cred_'+$(this).data('name')]=$(this).val(); });
    $.post(u, data, function(r){ p.find('.aieo-cati-conn-status').text(r&&r.success?'Saved ✓':'Error'); b.prop('disabled',false); })
     .fail(function(){ p.find('.aieo-cati-conn-status').text('Error'); b.prop('disabled',false); });
  });
  $(document).on('click','.aieo-cati-test', function(){
    var slug=$(this).data('slug'), b=$(this), p=panel(slug); b.prop('disabled',true); p.find('.aieo-cati-test-out').html('Testing…');
    $.post(u, {action:'aieo_catalog_import_test', nonce:n, slug:slug}, function(r){
      b.prop('disabled',false);
      if(r&&r.success){ p.find('.aieo-cati-test-out').html(r.data.html); }
      else { p.find('.aieo-cati-test-out').html('<span style="color:#b32d2e;">'+((r&&r.data&&r.data.message)||'Error')+'</span>'); }
    }).fail(function(){ b.prop('disabled',false); p.find('.aieo-cati-test-out').text('Request failed'); });
  });
  var importing=false;
  function fmt(t){ return 'created '+t.created+' · updated '+t.updated+' · skipped '+t.skipped+' · errors '+t.errors; }
  function errs(s){ if(!s||!s.length){$('#aieo-cati-errors').html('');return;} var h='<strong>Issues (first '+s.length+'):</strong><ul style="margin:4px 0 0 18px;">'; s.forEach(function(e){ h+='<li><code>'+(e.sku||'')+'</code>: '+(e.error||'')+'</li>'; }); h+='</ul>'; $('#aieo-cati-errors').html(h); }
  function proc(job){
    $.post(u, {action:'aieo_catalog_import_process', nonce:n, job_id:job}, function(r){
      if(!r||!r.success){ importing=false; $('#aieo-cati-import').prop('disabled',false); $('#aieo-cati-prog-msg').text((r&&r.data&&r.data.message)||'Error'); return; }
      var d=r.data;
      $('#aieo-cati-bar').css('width', d.percentage+'%').text(d.percentage+'%');
      $('#aieo-cati-prog-msg').text('Page '+d.page+'/'+d.total_pages+' · '+fmt(d.totals));
      errs(d.totals.error_samples);
      if(d.complete){ importing=false; $('#aieo-cati-import').prop('disabled',false); $('#aieo-cati-prog-msg').append('  — done.'); }
      else { proc(job); }
    }).fail(function(){ importing=false; $('#aieo-cati-import').prop('disabled',false); $('#aieo-cati-prog-msg').text('Request failed'); });
  }
  $('#aieo-cati-import').on('click', function(){
    if(importing){return;} importing=true; var b=$(this); b.prop('disabled',true);
    $('#aieo-cati-prog').show(); $('#aieo-cati-bar').css('width','0%').text('0%'); $('#aieo-cati-prog-msg').text('Starting…'); $('#aieo-cati-errors').html('');
    var data={action:'aieo_catalog_import_start', nonce:n, slug:source(),
      opt_status:$('#aieo-cati-status').val(), opt_mode:$('#aieo-cati-mode').val(),
      opt_images:$('#aieo-cati-images').is(':checked')?1:0, opt_categories:$('#aieo-cati-categories').is(':checked')?1:0,
      opt_option_groups:1};
    $.post(u, data, function(r){
      if(!r||!r.success){ importing=false; b.prop('disabled',false); $('#aieo-cati-prog-msg').text((r&&r.data&&r.data.message)||'Could not start'); return; }
      proc(r.data.job_id);
    }).fail(function(){ importing=false; b.prop('disabled',false); $('#aieo-cati-prog-msg').text('Request failed'); });
  });
});
JS;
        wp_add_inline_script('aieo-cati-admin', $cfg . "\n" . $js);
    }

    public function render_subtab() {
        $sources = $this->sources();

        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Catalogue Importer', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Pull your live catalogue from a marketplace into WooCommerce in one click — products plus the category hierarchy they belong to are created automatically. Matched by SKU, so it is safe to re-run.', 'ai-eshop-optimizer') . '</p>';

        if (empty($sources)) {
            echo '<div class="aieo-dmm-card"><p>' . esc_html__('No catalogue sources are available.', 'ai-eshop-optimizer') . '</p></div></div>';
            return;
        }

        $slugs   = array_keys($sources);
        $current = $slugs[0];

        
        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('1. Choose a source', 'ai-eshop-optimizer') . '</h3>';
        echo '<select id="aieo-cati-source" style="min-width:240px;">';
        foreach ($sources as $slug => $src) {
            echo '<option value="' . esc_attr($slug) . '">' . esc_html($src->label()) . '</option>';
        }
        echo '</select>';
        echo '<p class="description">' . esc_html__('Pick the marketplace to import from, fill in its credentials below, then run the import.', 'ai-eshop-optimizer') . '</p>';
        echo '</div>';

        
        foreach ($sources as $slug => $src) {
            $creds  = $this->get_creds($slug);
            $hidden = ($slug === $current) ? '' : ' style="display:none;"';
            echo '<div class="aieo-dmm-card aieo-cati-panel" data-slug="' . esc_attr($slug) . '"' . $hidden . '>';
            echo '<h3>' . esc_html(sprintf( __('Connect to %s', 'ai-eshop-optimizer'), $src->label())) . '</h3>';
            echo '<table class="form-table"><tbody>';
            foreach ($src->credential_fields() as $f) {
                $name = (string) $f['name'];
                $type = ($f['type'] ?? 'text') === 'password' ? 'password' : 'text';
                $val  = ($type === 'password') ? '' : (string) ($creds[$name] ?? '');
                $ph   = ($type === 'password' && !empty($creds[$name])) ? esc_attr__('•••••• (saved — leave blank to keep)', 'ai-eshop-optimizer') : '';
                echo '<tr><th>' . esc_html((string) $f['label']) . (!empty($f['required']) ? ' <span style="color:#b32d2e;">*</span>' : '') . '</th><td>';
                echo '<input type="' . esc_attr($type) . '" class="regular-text aieo-cati-cred" data-name="' . esc_attr($name) . '" value="' . esc_attr($val) . '" placeholder="' . $ph . '" autocomplete="off">';
                if (!empty($f['description'])) { echo '<p class="description">' . esc_html((string) $f['description']) . '</p>'; }
                echo '</td></tr>';
            }
            echo '</tbody></table>';
            echo '<p><button type="button" class="button button-primary aieo-cati-save" data-slug="' . esc_attr($slug) . '">' . esc_html__('Save connection', 'ai-eshop-optimizer') . '</button>';
            echo ' <button type="button" class="button aieo-cati-test" data-slug="' . esc_attr($slug) . '">' . esc_html__('Test connection', 'ai-eshop-optimizer') . '</button>';
            echo ' <span class="aieo-cati-conn-status" style="color:#646970;font-size:12px;margin-left:8px;"></span></p>';
            echo '<div class="aieo-cati-test-out" style="margin-top:8px;"></div>';
            echo '</div>';
        }

        
        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html__('3. Import', 'ai-eshop-optimizer') . '</h3>';
        echo '<table class="form-table"><tbody>';
        echo '<tr><th>' . esc_html__('Create products as', 'ai-eshop-optimizer') . '</th><td><select id="aieo-cati-status">'
            . '<option value="draft">' . esc_html__('Draft (review before publishing)', 'ai-eshop-optimizer') . '</option>'
            . '<option value="publish">' . esc_html__('Published (live immediately)', 'ai-eshop-optimizer') . '</option>'
            . '</select></td></tr>';
        echo '<tr><th>' . esc_html__('When a product already exists', 'ai-eshop-optimizer') . '</th><td><select id="aieo-cati-mode">'
            . '<option value="new_only">' . esc_html__('Skip it — only add new products', 'ai-eshop-optimizer') . '</option>'
            . '<option value="enrich">' . esc_html__('Enrich it — fill blanks only (barcode, missing image/categories); keep prices, names & modifiers', 'ai-eshop-optimizer') . '</option>'
            . '<option value="create_update">' . esc_html__('Update it (add new + update existing)', 'ai-eshop-optimizer') . '</option>'
            . '<option value="update_only">' . esc_html__('Only update existing — add nothing new', 'ai-eshop-optimizer') . '</option>'
            . '</select><p class="description">' . esc_html__('Matched by SKU.', 'ai-eshop-optimizer') . '</p></td></tr>';
        echo '<tr><th>' . esc_html__('Images', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" id="aieo-cati-images" checked> ' . esc_html__('Download product images into the Media Library', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '<tr><th>' . esc_html__('Categories', 'ai-eshop-optimizer') . '</th><td><label><input type="checkbox" id="aieo-cati-categories" checked> ' . esc_html__('Create the marketplace category hierarchy and assign products to it', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '</tbody></table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-cati-import">' . esc_html__('Import catalogue', 'ai-eshop-optimizer') . '</button></p>';
        echo '<div id="aieo-cati-prog" style="display:none;margin-top:10px;">';
        echo '<div style="background:#f0f0f1;border-radius:4px;overflow:hidden;height:20px;max-width:480px;"><div id="aieo-cati-bar" style="height:20px;width:0;background:#2271b1;color:#fff;font-size:12px;line-height:20px;text-align:center;">0%</div></div>';
        echo '<p id="aieo-cati-prog-msg" style="margin:6px 0;color:#1f2937;"></p>';
        echo '<div id="aieo-cati-errors" style="font-size:12px;color:#b32d2e;"></div>';
        echo '</div>';
        echo '<p class="description" style="margin-top:10px;">' . esc_html__('Runs in your browser page-by-page — keep this tab open until it finishes. Imports run safely against your live catalogue; new products land as Draft by default.', 'ai-eshop-optimizer') . '</p>';
        echo '</div>';

        echo '</div>';
    }
}
