<?php
namespace Unlockafe_addons\Classes;

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

class Popup_Click_Tracker {
    private static $instance = null;
    private $table_name;

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'unlockafe_popup_clicks';
        add_action('wp_ajax_unlockafe_popup_anywhere_track', array($this, 'handle_ajax'));
        add_action('wp_ajax_nopriv_unlockafe_popup_anywhere_track', array($this, 'handle_ajax'));
        $this->maybe_create_table();
        add_action('rest_api_init', array($this, 'register_rest_routes'));
    }

    private function maybe_create_table() {
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE IF NOT EXISTS `{$this->table_name}` (
            `id` bigint(20) NOT NULL AUTO_INCREMENT,
            `popup_id` varchar(100) NOT NULL,
            `cta_url` text,
            `page_url` text,
            `ip_address` varchar(45) DEFAULT '',
            `user_agent` text,
            `created_at` datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
            PRIMARY KEY (`id`)
        ) $charset_collate;";
        dbDelta($sql);
    }

    public function handle_ajax() {
        global $wpdb;
        $popup_id = isset($_POST['popup_id']) ? sanitize_text_field($_POST['popup_id']) : '';
        $cta_url = isset($_POST['cta_url']) ? esc_url_raw($_POST['cta_url']) : '';
        $page_url = isset($_POST['page_url']) ? esc_url_raw($_POST['page_url']) : '';
        $ip_address = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field($_SERVER['REMOTE_ADDR']) : '';
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field($_SERVER['HTTP_USER_AGENT']) : '';
        if (!$popup_id) {
            wp_send_json_error(['message' => 'Missing popup_id']);
        }
        $wpdb->insert($this->table_name, [
            'popup_id' => $popup_id,
            'cta_url' => $cta_url,
            'page_url' => $page_url,
            'ip_address' => $ip_address,
            'user_agent' => $user_agent,
            'created_at' => current_time('mysql'),
        ]);
        wp_send_json_success(['message' => 'Tracked']);
    }

    // Fetch stats for dashboard (basic example)
    public function get_stats($args = []) {
        global $wpdb;
        $where = '1=1';
        $params = [];
        if (!empty($args['popup_id'])) {
            $where .= ' AND popup_id = %s';
            $params[] = $args['popup_id'];
        }
        $sql = "SELECT COUNT(*) as total, popup_id FROM {$this->table_name} WHERE $where GROUP BY popup_id";
        if ($params) {
            return $wpdb->get_results($wpdb->prepare($sql, ...$params));
        } else {
            return $wpdb->get_results($sql);
        }
    }

    public function register_rest_routes() {
        register_rest_route('unlockafe/v1', '/popup-stats', array(
            'methods' => 'GET',
            'callback' => array($this, 'rest_get_stats'),
            'permission_callback' => function() {
                return current_user_can('manage_options');
            }
        ));

        register_rest_route('unlockafe/v1', '/popup-stats-detailed', array(
            'methods' => 'GET',
            'callback' => array($this, 'rest_get_detailed_stats'),
            'permission_callback' => function() {
                return current_user_can('manage_options');
            }
        ));
    }

    public function rest_get_stats($request) {
        $stats = $this->get_stats();
        return rest_ensure_response($stats);
    }

    public function rest_get_detailed_stats($request) {
        global $wpdb;
        $days = intval($request->get_param('days')) ?: 7;
        
        $date_threshold = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        // Get daily breakdown
        $daily_stats = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                DATE(created_at) as date,
                COUNT(*) as clicks,
                COUNT(DISTINCT popup_id) as unique_popups
             FROM {$this->table_name} 
             WHERE created_at >= %s
             GROUP BY DATE(created_at)
             ORDER BY date DESC",
            $date_threshold
        ));

        // Get hourly breakdown for recent data
        $hourly_stats = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                HOUR(created_at) as hour,
                COUNT(*) as clicks
             FROM {$this->table_name} 
             WHERE created_at >= %s
             GROUP BY HOUR(created_at)
             ORDER BY hour",
            date('Y-m-d H:i:s', strtotime('-24 hours'))
        ));

        // Get top performing popups with additional metrics
        $top_popups = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                popup_id,
                COUNT(*) as total_clicks,
                COUNT(DISTINCT DATE(created_at)) as active_days,
                MIN(created_at) as first_click,
                MAX(created_at) as last_click
             FROM {$this->table_name} 
             WHERE created_at >= %s
             GROUP BY popup_id
             ORDER BY total_clicks DESC
             LIMIT 10",
            $date_threshold
        ));

        return rest_ensure_response([
            'period_days' => $days,
            'daily_breakdown' => $daily_stats,
            'hourly_breakdown' => $hourly_stats,
            'top_performers' => $top_popups,
            'summary' => [
                'total_clicks' => array_sum(array_column($daily_stats, 'clicks')),
                'avg_daily_clicks' => count($daily_stats) > 0 ? round(array_sum(array_column($daily_stats, 'clicks')) / count($daily_stats), 1) : 0,
                'peak_day' => !empty($daily_stats) ? max($daily_stats) : null
            ]
        ]);
    }
}

// Initialize on load
Popup_Click_Tracker::getInstance(); 