<?php

class Eurostocks_Analytics {

    public $page_action;
    public $user_action;
    public $make;
    public $model;
    public $car_id;
    public $blocked;
    public $ip_address;
    

    public function __construct($page_action, $user_action, $make, $model, $car_id, $blocked = 0){
        $this->page_action = $page_action;
        $this->user_action = $user_action;
        $this->make = $make;
        $this->model = $model;
        $this->car_id = $car_id;
        $this->blocked = (int) $blocked;
        $this->ip_address = $this->resolve_client_ip();
    }

    public function register_visit(){
        global $wpdb;
        $table_name_eurostocks_analytics = $wpdb->prefix . 'eurostocks_requests';

        $query = $wpdb->prepare("INSERT INTO %i (page_action, user_action, car_make, car_model, car_id, blocked, ip_address) 
            VALUES (%s, %s, %s, %s, %s, %d, %s)",
            $table_name_eurostocks_analytics,
            $this->page_action,
            $this->user_action,
            $this->make,
            $this->model,
            $this->car_id,
            $this->blocked,
            $this->ip_address
        );

        $wpdb->query($query);
    }

    private function resolve_client_ip() {
        $options = class_exists('Eurostocks_Anti_Spam_Settings') ? Eurostocks_Anti_Spam_Settings::get_options() : array();
        $use_cloudflare_ip = isset($options['use_cloudflare_ip']) && (int) $options['use_cloudflare_ip'] === 1;

        $ip = '';
        if ($use_cloudflare_ip && isset($_SERVER['HTTP_CF_CONNECTING_IP']) && $_SERVER['HTTP_CF_CONNECTING_IP'] !== '') {
            $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CF_CONNECTING_IP']));
            if (!filter_var($ip, FILTER_VALIDATE_IP)) {
                $ip = '';
            }
        }

        if ('' === $ip && isset($_SERVER['REMOTE_ADDR'])) {
            $ip = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
            if (!filter_var($ip, FILTER_VALIDATE_IP)) {
                $ip = '';
            }
        }

        if ('' === $ip) {
            return '';
        }

        if (strpos($ip, ':ffff:') !== false) {
            $ip = substr($ip, strrpos($ip, ':') + 1);
        }

        return substr($ip, 0, 100);
    }
}
