<?php
/**
 * LinkCentral Webhook Handler
 *
 * Handles webhook functionality for premium users.
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class LinkCentral_Webhook_Handler {
    private $visitor_manager;
    private $geolocation;

    public function __construct($visitor_manager, $geolocation = null) {
        $this->visitor_manager = $visitor_manager;
        $this->geolocation = $geolocation;
    }

    /**
     * Send webhook if enabled (premium feature)
     */
    public function send_webhook($link_id, $slug, $title, $destination_url) {
        // Early returns for efficiency
        $webhook_url = get_option('linkcentral_webhook_url', '');
        if (empty($webhook_url)) {
            return;
        }

        $payload_fields = get_option('linkcentral_webhook_payload_fields', array());
        if (empty($payload_fields)) {
            return;
        }

        // Build payload
        $payload = array();
        foreach ($payload_fields as $field) {
            switch ($field) {
                case 'link_id':
                    $payload[$field] = $link_id;
                    break;

                case 'slug':
                    $payload[$field] = $slug;
                    break;

                case 'title':
                    $payload[$field] = $title;
                    break;

                case 'redirection_url':
                    $payload[$field] = $destination_url;
                    break;

                case 'user_agent':
                    $payload[$field] = $this->visitor_manager->get_user_agent() ?: null;
                    break;

                case 'unique_visitor_id':
                    // Include visitor ID only if visitor tracking is enabled AND reporting is not disabled
                    // This ensures no visitor identification happens when tracking is globally disabled
                    if (get_option('linkcentral_track_unique_visitors', true) && !get_option('linkcentral_disable_reporting', false)) {
                        $visitor_id = $this->visitor_manager->get_or_set_visitor_id();
                        $payload[$field] = !empty($visitor_id) ? $visitor_id : null;
                    } else {
                        $payload[$field] = null;
                    }
                    break;

                case 'country':
                    $country = $this->get_country();
                    $payload[$field] = !empty($country) ? $country : null;
                    break;

                case 'referring_url':
                    $referring_url = wp_get_referer();
                    $payload[$field] = $referring_url ? $referring_url : null;
                    break;

                case 'click_datetime':
                    $payload[$field] = current_time('mysql');
                    break;

                case 'user_id':
                    $current_user = wp_get_current_user();
                    $payload[$field] = $current_user->ID ? $current_user->ID : null;
                    break;
            }
        }

        if (empty($payload)) {
            return;
        }

        // Send webhook request
        $webhook_method = get_option('linkcentral_webhook_method', 'POST');

        $args = array(
            'method' => $webhook_method,
            'body' => wp_json_encode($payload),
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'LinkCentral-Webhook/1.0'
            ),
            'blocking' => false, // Asynchronous - no delay to redirect
            'timeout' => 5,
            'redirection' => 0
        );

        wp_remote_request($webhook_url, $args);
    }

    /**
     * Get user country (delegates to geolocation if available)
     */
    private function get_country() {
        if ($this->geolocation) {
            return $this->geolocation->get_user_country();
        }
        return null;
    }
}
