<?php

namespace LinkFiliate\Libs\Utils;

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

use LinkFiliate\App\Traits\Singleton;

class Widget
{
    use Singleton;

    public function init()
    {
        add_action('wp_dashboard_setup', [$this, 'register_widget']);
    }

    public function register_widget()
    {
        wp_add_dashboard_widget(
            'linkfiliate_dashboard_summary',
            'LinkFiliate Analytics Summary',
            [$this, 'render_widget']
        );
    }

    public function render_widget()
    {
        global $wpdb;

        $clicks_table    = $wpdb->prefix . 'linkfiliate_clicks';
        $campaigns_table = $wpdb->prefix . 'linkfiliate_campaigns';

        // --- Time ranges ---
        $now  = current_time('mysql');
        $from_24h = gmdate('Y-m-d H:i:s', strtotime('-24 hours'));
        $from_7d  = gmdate('Y-m-d H:i:s', strtotime('-7 days'));

        // --- Total & unique clicks (24h) ---
        $total_24h = (int) $wpdb->get_var($wpdb->prepare("
			SELECT COUNT(*) 
			FROM %i
			WHERE created_at BETWEEN %s AND %s
		", $clicks_table, $from_24h, $now)); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

        $unique_24h = (int) $wpdb->get_var($wpdb->prepare("
			SELECT COUNT(DISTINCT ip_address)
			FROM %i
			WHERE created_at BETWEEN %s AND %s
		", $clicks_table, $from_24h, $now)); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        // --- Total & unique clicks (7d) ---
        $total_7d = (int) $wpdb->get_var($wpdb->prepare("
			SELECT COUNT(*) 
			FROM %i
			WHERE created_at BETWEEN %s AND %s
		", $clicks_table, $from_7d, $now)); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        $unique_7d = (int) $wpdb->get_var($wpdb->prepare("
			SELECT COUNT(DISTINCT ip_address)
			FROM %i
			WHERE created_at BETWEEN %s AND %s
		", $clicks_table, $from_7d, $now)); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        // --- Top 5 campaigns by clicks in last 7 days ---
        $query = $wpdb->prepare("
			SELECT 
				c.id,
				c.name,
				c.slug,
				c.target_url,
				COUNT(l.id) AS total_clicks
			FROM %i AS c
			LEFT JOIN %i AS l 
				ON c.id = l.campaign_id
				AND l.created_at BETWEEN %s AND %s
			GROUP BY c.id
			ORDER BY total_clicks DESC
			LIMIT 5
		", $campaigns_table, $clicks_table, $from_7d, $now);

        $popular_links = $wpdb->get_results($query, ARRAY_A) ?: []; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        // Render view
        $view_data = [
            'total_24h'     => $total_24h,
            'unique_24h'    => $unique_24h,
            'total_7d'      => $total_7d,
            'unique_7d'     => $unique_7d,
            'popular_links' => $popular_links,
        ];

        \LinkFiliate\Core\View::Render('widget-dashboard', $view_data);
    }
}
