<?php
/**
 * LinkCentral Geolocation
 *
 * Handles geolocation services for premium users.
 */
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class LinkCentral_Geolocation {
    private $visitor_manager;

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

    /**
     * Get the user's country.
     */
    public function get_user_country() {
        // Check cache first
        $cached_country = $this->visitor_manager->get_cached('user_country');
        if ($cached_country !== null) {
            return $cached_country;
        }

        $geolocation_service = get_option('linkcentral_geolocation_service', 'none');

        $country = '';
        switch ($geolocation_service) {
            case 'cloudflare':
                $country = $this->get_country_from_cloudflare();
                break;
            case 'maxmind':
                $country = $this->get_country_from_maxmind();
                break;
            default:
                $country = '';
        }

        // Cache the result
        $this->visitor_manager->set_cached('user_country', $country);
        return $country;
    }

    /**
     * Get the country code from Cloudflare headers.
     */
    private function get_country_from_cloudflare() {
        return isset($_SERVER['HTTP_CF_IPCOUNTRY']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_CF_IPCOUNTRY'])) : '';
    }

    /**
     * Get the country code using MaxMind GeoIP2.
     */
    private function get_country_from_maxmind() {
        $upload_dir = wp_upload_dir();
        $maxmind_database_path = $upload_dir['basedir'] . '/linkcentral/GeoLite2-Country/GeoLite2-Country.mmdb';

        if (!file_exists($maxmind_database_path)) {
            return '';
        }

        try {
            require_once LINKCENTRAL_PLUGIN_DIR . 'vendor/autoload.php';
            $reader = new \GeoIp2\Database\Reader($maxmind_database_path);
            $record = $reader->country($this->visitor_manager->get_ip_address());
            return $record->country->isoCode;
        } catch (\Exception $e) {
            return '';
        }
    }

}
