<?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;

        // Hook up the async webhook handler
        add_action('linkcentral_send_webhook_async', array($this, 'send_webhook_async'), 10, 3);
    }

    /**
     * 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;
        }

        // Check delivery mode setting - defaults to immediate for reliability
        $delivery_mode = get_option('linkcentral_webhook_delivery_mode');

        if ($delivery_mode !== 'async') {
            // Send webhook immediately (synchronous) - may slow down redirect but most reliable/straightforward
            $this->send_webhook_immediate($webhook_url, $payload, get_option('linkcentral_webhook_method', 'POST'));
        } else {
            // Schedule webhook to be sent asynchronously after redirect
            // This ensures the redirect happens immediately without waiting for webhook response
            wp_schedule_single_event(time() + 1, 'linkcentral_send_webhook_async', array(
                'webhook_url' => $webhook_url,
                'payload' => $payload,
                'method' => get_option('linkcentral_webhook_method', 'POST')
            ));
        }
    }

    /**
     * Send webhook immediately (synchronously)
     */
    private function send_webhook_immediate($webhook_url, $payload, $method) {
        $args = array(
            'method' => $method,
            'body' => wp_json_encode($payload),
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'LinkCentral-Webhook/1.0'
            ),
            'timeout' => 5, // Shorter timeout for immediate execution
            'redirection' => 0
        );

        wp_remote_request($webhook_url, $args);
    }

    /**
     * Send webhook asynchronously via WordPress cron
     */
    public function send_webhook_async($webhook_url, $payload, $method) {
        $args = array(
            'method' => $method,
            'body' => wp_json_encode($payload),
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'LinkCentral-Webhook/1.0'
            ),
            'timeout' => 10, // Longer timeout for async execution
            'redirection' => 0
        );

        wp_remote_request($webhook_url, $args);
    }

    /**
     * Get user country (delegates to geolocation if available).
     */
    private function get_country() {
        if ($this->geolocation) {
            $location = $this->geolocation->get_user_location();
            return isset($location['country']) ? $location['country'] : null;
        }
        return null;
    }
}
