<?php

namespace LinkFiliate\App\Services\Importers;

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



class ClickWhaleImporter implements ImporterInterface
{
    public function import(array $options): array
    {
        global $wpdb;

        $batch_size = intval($options['limit'] ?? 100);
        $offset     = intval($options['offset'] ?? 0);

        $source_links  = $wpdb->prefix . 'clickwhale_links';
        $source_clicks = $wpdb->prefix . 'clickwhale_visitors';
        $source_terms  = $wpdb->prefix . 'clickwhale_categories';

        $target_links  = $wpdb->prefix . 'linkfiliate_campaigns';
        $target_clicks = $wpdb->prefix . 'linkfiliate_clicks';
        $target_cats   = $wpdb->prefix . 'linkfiliate_categories';

        $duplicateHandling = $options['duplicateHandling'] ?? 'skip';
        $importCategories  = !empty($options['categories']);
        $importClickStats  = !empty($options['click_stats']);

        // --- Total links for progress ---
        $total_links = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM %i", $source_links));

        // --- Fetch one batch ---
        $links = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM %i ORDER BY id ASC LIMIT %d OFFSET %d",
                $source_links,
                $batch_size,
                $offset
            )
        );

        $imported = 0;
        $skipped  = 0;
        $updated  = 0;

        foreach ($links as $link) {
            // --- Check for duplicate by slug ---
            $existing = $wpdb->get_row(
                $wpdb->prepare("SELECT id FROM %i WHERE slug = %s", $target_links, $link->link_slug)
            );

            $link_status = $link->link_status === 'publish' ? 'active' : ($link->link_status === 'disabled' ? 'inactive' : 'draft');

            if ($existing) {
                switch ($duplicateHandling) {
                    case 'overwrite':
                        $wpdb->update(
                            $target_links,
                            [
                                'name'       => $link->link_title,
                                'target_url' => $link->target_url,
                                'description' => $link->link_note,
                                'redirect_type' => $link->redirect_type,
                                'nofollow' => $link->nofollow,
                                'sponsored' => $link->sponsored,
                                'status' => $link_status,
                                'updated_at' => current_time('mysql'),
                            ],
                            ['id' => $existing->id]
                        );
                        $updated++;
                        break;

                    case 'create_new':
                        $wpdb->insert($target_links, [
                            'name'       => $link->link_title,
                            'slug'       => $link->link_slug,
                            'target_url' => $link->target_url,
                            'redirect_type' => $link->redirect_type,
                            'description' => $link->link_note,
                            'nofollow' => $link->nofollow,
                            'sponsored' => $link->sponsored,
                            'status' => $link_status,
                            'created_at' => current_time('mysql'),
                        ]);
                        $imported++;
                        break;

                    default: // skip
                        $skipped++;
                        break;
                }
                $target_id = $existing->id ?? $wpdb->insert_id;
            } else {
                $wpdb->insert($target_links, [
                    'name'       => $link->link_title,
                    'slug'       => $link->link_slug,
                    'target_url' => $link->target_url,
                    'redirect_type' => $link->redirect_type,
                    'nofollow' => $link->nofollow,
                    'sponsored' => $link->sponsored,
                    'status' => $link_status,
                    'description' => $link->link_note,
                    'created_at' => current_time('mysql'),
                ]);
                $imported++;
                $target_id = $wpdb->insert_id;
            }

            // --- Import clicks ---
            if ($importClickStats) {
                $clicks = $wpdb->get_results(
                    $wpdb->prepare("SELECT * FROM %i WHERE link_id = %d", $source_clicks, $link->id)
                );
                foreach ($clicks as $click) {
                    $wpdb->insert($target_clicks, [
                        'link_id'    => $target_id,
                        'click_time' => $click->created_at ?? current_time('mysql'),
                        'ip_address' => $click->ip ?? '',
                        'referrer'   => $click->referrer ?? '',
                        'user_agent' => $click->user_agent ?? '',
                    ]);
                }
            }


            // --- Import categories ---
            if ($importCategories) {
                $terms = $wpdb->get_results(
                    "SELECT ID, term_name, term_slug, term_type, term_order 
         FROM %i 
         WHERE term_type = 'category' 
         ORDER BY term_order ASC",
                    $source_terms
                );

                foreach ($terms as $term) {
                    $existing_cat = $wpdb->get_row(
                        $wpdb->prepare("SELECT id, slug FROM %i WHERE slug = %s", $target_cats, $term->term_slug)
                    );

                    if ($existing_cat) {
                        switch ($duplicateHandling) {
                            case 'overwrite':
                                $wpdb->update(
                                    $target_cats,
                                    [
                                        'name'       => $term->term_name,
                                        'sort_order' => intval($term->term_order),
                                        'updated_at' => current_time('mysql'),
                                    ],
                                    ['id' => $existing_cat->id]
                                );
                                break;

                            case 'create_new':
                                $new_slug = $term->term_slug . '-copy';
                                $wpdb->insert($target_cats, [
                                    'name'       => $term->term_name,
                                    'slug'       => $new_slug,
                                    'sort_order' => intval($term->term_order),
                                    'created_at' => current_time('mysql'),
                                ]);
                                break;

                            default: // skip
                                continue 2; // skip to next term
                        }
                    } else {
                        // No duplicate, safe to insert
                        $wpdb->insert($target_cats, [
                            'name'       => $term->term_name,
                            'slug'       => $term->term_slug,
                            'sort_order' => intval($term->term_order),
                            'created_at' => current_time('mysql'),
                        ]);
                    }
                }
            }
        }

        // --- Progress calculation ---
        $next_offset = $offset + $batch_size;
        $progress = min(100, round(($next_offset / $total_links) * 100));

        return [
            'imported'  => $imported,
            'updated'   => $updated,
            'skipped'   => $skipped,
            'total'     => $total_links,
            'offset'    => $next_offset,
            'progress'  => $progress,
            'done'      => $progress >= 100,
            'summary'   => [
                'links'     => $imported + $updated,
                'categories' => $importCategories ? 'processed' : 'skipped',
                'clicks'    => $importClickStats ? 'processed' : 'skipped',
            ],
        ];
    }
}
