<?php
class cppl {
    private $config;
    private $api_url;
    private $api_key;
    private $license_code;
    private $config_name;
    private $config_owner;
    private $config_address;
    private $config_telephone;
    private $name;
    private $owner;
    private $address;
    private $email;
    private $telephone;
    private $current_domain;

    public function __construct() {
        $this->api_url = 'https://www.againtheme.com/index.php?route=';
        $this->current_domain = $_SERVER['SERVER_NAME'];
        $this->api_key = 'a1d902b6213ac8e34fd5d5e8a97e8d88';
    }

    public function valid($form_data) {
        $this->name = isset($form_data['config_name']) ? $form_data['config_name'] : '';
        $this->owner = isset($form_data['config_owner']) ? $form_data['config_owner'] : '';
        $this->address = isset($form_data['config_address']) ? $form_data['config_address'] : '';
        $this->email = isset($form_data['config_email']) ? $form_data['config_email'] : '';
        $this->telephone = isset($form_data['config_telephone']) ? $form_data['config_telephone'] : '';
        $this->license_code = isset($form_data['ac5_key']) ? $form_data['ac5_key'] : '';

        $post_data = [
            'store_name'    => $this->name,
            'store_owner'   => $this->owner,
            'address'       => $this->address,
            'email'         => $this->email,
            'telephone'     => $this->telephone,
            'domain'        => $this->current_domain,
            'api_key'       => $this->api_key,
            'license_code'  => $this->license_code,
            'ip_address'    => $this->getUserIP(),
        ];

        $response = $this->call_api('api/license/validate', $post_data);
        return $response;
    }

    private function call_api($endpoint, $post_data) {
        $full_url = $this->api_url . $endpoint;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $full_url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            curl_close($ch);
            return ['status' => false, 'message' => 'cURL error: ' . $error_msg];
        }

        curl_close($ch);

        $result = json_decode($response, true);
        if ($result === null) {
            return ['status' => false, 'message' => 'Invalid JSON response from API.'];
        }

        return $result;
    }

    private function getUserIP() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } else {
            return $_SERVER['REMOTE_ADDR'];
        }
    }
}
