<?php

/**
 * Class Scanner
 *
 * Represents the Scanner model
 *
 * @package LinkFiliate\Models
 * @since 1.0.0
 */

namespace LinkFiliate\App\Models;

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

class Scanner
{
    public function scan($source)
    {
        switch ($source) {
            case 'pretty-links':
                return $this->scanPrettyLinks();

            case 'better-links':
                return $this->scanBetterLinks();

            case 'thirsty-affiliates':
                return $this->scanThirstyAffiliates();

            default:
                return ['error' => "Unknown source '{$source}'"];
        }
    }

    /**
     * Scan Pretty Links plugin
     */
    private function scanPrettyLinks()
    {
        global $wpdb;
        $table_links  = $wpdb->prefix . 'prli_links';
        $table_clicks = $wpdb->prefix . 'prli_clicks';
        $table_metas  = $wpdb->prefix . 'prli_link_metas';

        // Check if installed
        if (!$this->tableExists($table_links)) {
            return ['found' => false, 'message' => 'Pretty Links not detected on this site.'];
        }

        $sql_links = $wpdb->prepare("SELECT COUNT(*) FROM %i", $table_links);
        $total_links = (int) $wpdb->get_var($sql_links); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        $sql_clicks = $wpdb->prepare("SELECT COUNT(*) FROM %i", $table_clicks);
        $total_clicks = (int) $wpdb->get_var($sql_clicks); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        $sql_cats = $wpdb->prepare(
            "SELECT COUNT(DISTINCT meta_value)
     FROM %i
     WHERE meta_key = 'group_id' AND meta_value != ''",
            $table_metas
        );
        $total_categories = (int) $wpdb->get_var($sql_cats); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared


        return [
            'found' => true,
            'plugin' => 'Pretty Links',
            'totals' => [
                'links'      => $total_links,
                'categories' => $total_categories,
                'clicks'     => $total_clicks,
            ],

            'message' => 'Pretty Links detected successfully.',
        ];
    }

    /**
     * Scan Better Links plugin
     */
    private function scanBetterLinks()
    {
        global $wpdb;
        $table_links  = $wpdb->prefix . 'betterlinks';
        $table_clicks = $wpdb->prefix . 'betterlinks_clicks';
        $table_terms  = $wpdb->prefix . 'betterlinks_terms';

        if (!$this->tableExists($table_links)) {
            return ['found' => false, 'message' => 'Better Links not detected on this site.'];
        }

        $sql_links = $wpdb->prepare("SELECT COUNT(*) FROM %i", $table_links);
        $total_links = (int) $wpdb->get_var($sql_links); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $sql_clicks = $wpdb->prepare("SELECT COUNT(*) FROM %i", $table_clicks);
        $total_clicks = (int) $wpdb->get_var($sql_clicks); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        $sql_cats = $wpdb->prepare("SELECT COUNT(*) FROM %i", $table_terms);
        $total_categories = (int) $wpdb->get_var($sql_cats); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        return [
            'found' => true,
            'plugin' => 'Better Links',
            'totals' => [
                'links'      => $total_links,
                'categories' => $total_categories,
                'clicks'     => $total_clicks,
            ],
            'message' => 'Better Links detected successfully.',
        ];
    }

    /**
     * Scan Thirsty Affiliates plugin
     */
    private function scanThirstyAffiliates()
    {
        global $wpdb;

        $table_links  = $wpdb->prefix . 'posts';
        $table_clicks = $wpdb->prefix . 'ta_link_clicks';

        // Check if ThirstyAffiliates is installed by looking for the 'thirstylink' post type
        $link_counts = $wpdb->get_row("
        SELECT
            COUNT(*) AS total_links,
            SUM(CASE WHEN post_status = 'publish' THEN 1 ELSE 0 END) AS published_links
        FROM {$wpdb->prefix}posts
        WHERE post_type = 'thirstylink'
    ", ARRAY_A);

        $total_links     = (int) ($link_counts['total_links'] ?? 0);
        $published_links = (int) ($link_counts['published_links'] ?? 0);

        // If no ThirstyAffiliates data exists, return early
        if ($total_links === 0) {
            return [
                'found'      => false,
                'plugin'     => 'Thirsty Affiliates',
                'links'      => 0,
                'categories' => 0,
                'clicks'      => 0,
                'message'    => 'Thirsty Affiliates not detected on this site.',
            ];
        }

        // Count categories
        $categories_count = (int) $wpdb->get_var("
        SELECT COUNT(DISTINCT t.term_id)
        FROM {$wpdb->terms} t
        INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
        WHERE tt.taxonomy = 'thirstylink-category'
    ");

        // Count stats 
        $stats_count = 0;
        if ($this->tableExists($table_clicks)) {

            $stats_count = (int) $wpdb->get_var(
                $wpdb->prepare(
                    'SELECT COUNT(*) FROM %i',
                    $table_clicks
                )
            );
        }

        return [
            'found'      => true,
            'plugin'     => 'Thirsty Affiliates',
            'totals'     => [
                'links'      => $total_links,
                'published'  => $published_links,
                'categories' => $categories_count,
                'clicks'      => $stats_count,
            ],
            'message' => 'Thirsty Affiliates detected successfully.',
        ];
    }

    /**
     * Helper: check table existence
     */
    private function tableExists($table_name)
    {
        global $wpdb;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        return (bool) $wpdb->get_var(
            $wpdb->prepare("SHOW TABLES LIKE %s", $wpdb->esc_like($table_name))
        );
    }
}
