<?php
if (!defined('ABSPATH')) { exit; }

final class PTMS_License {
    private static $instance = null;

    public static function instance() {
        if (self::$instance === null) { self::$instance = new self(); }
        return self::$instance;
    }

    private function __construct() {
        add_action('admin_init', array(__CLASS__, 'maybe_refresh'));
    }

    public static function data() {
        $data = get_option('ptms_trust_license', array());
        return is_array($data) ? $data : array();
    }

    public static function local_trial_data() {
        // Demo kararı yalnız PW Trust tarafından verilir. WordPress seçeneğini
        // değiştirerek süre veya ürün kotası sıfırlanamaz.
        return array(
            'type'       => 'unlicensed',
            'status'     => 'inactive',
            'starts_at'  => '',
            'expires_at' => '',
            'days_left'  => 0,
            'can_send'   => false,
            'local'      => true,
        );
    }

    public static function display_data() {
        $data = self::data();
        $type = sanitize_key((string) ($data['type'] ?? 'none'));
        $status = sanitize_key((string) ($data['status'] ?? 'inactive'));
        if (($type === 'pro' || $type === 'demo') && in_array($status, array('active', 'grace', 'expired', 'quota_exhausted', 'converted', 'revoked'), true)) {
            return $data;
        }
        return self::local_trial_data();
    }

    public static function status() {
        $data = self::display_data();
        $type = sanitize_key((string) ($data['type'] ?? 'none'));
        $status = sanitize_key((string) ($data['status'] ?? 'inactive'));
        if ($type === 'pro' && in_array($status, array('active', 'grace'), true)) return 'pro';
        if (in_array($type, array('demo', 'unlicensed'), true) && $status === 'active' && !empty($data['can_send'])) return 'demo';
        return 'expired';
    }

    public static function label() {
        $data = self::display_data();
        $type = sanitize_key((string) ($data['type'] ?? 'none'));
        $status = sanitize_key((string) ($data['status'] ?? 'inactive'));
        $days = max(0, (int) ($data['days_left'] ?? 0));
        if ($type === 'pro' && $status === 'active') return sprintf(__('Pro · %d days', 'pw-merchant-api-system'), $days);
        if ($type === 'pro' && $status === 'grace') return __('Pro · Extra time', 'pw-merchant-api-system');
        if ($type === 'demo' && $status === 'active') {
            $remaining = max(0, (int)($data['remaining'] ?? 0));
            $limit = max(0, (int)($data['product_limit'] ?? 20));
            return sprintf(__('Demo · %1$d days · %2$d/%3$d product rights', 'pw-merchant-api-system'), $days, $remaining, $limit);
        }
        if ($type === 'demo' && $status === 'expired') return __('Demo period expired', 'pw-merchant-api-system');
        if ($type === 'demo' && $status === 'converted') return __('Demo upgraded to Pro', 'pw-merchant-api-system');
        if ($type === 'unlicensed' && $status === 'active') return __('Unlicensed ·', 'pw-merchant-api-system') . $days . __('days left', 'pw-merchant-api-system');
        if ($type === 'unlicensed' && $status === 'expired') return __('License-free period expired', 'pw-merchant-api-system');
        if ($status === 'quota_exhausted') return __('Demo quota is full', 'pw-merchant-api-system');
        if ($status === 'revoked') return __('License revoked', 'pw-merchant-api-system');
        return __('License not active', 'pw-merchant-api-system');
    }

    public static function signed_request($endpoint, array $payload) {
        return PTMS_Core::trust_request($endpoint, $payload);
    }

    private static function installation() {
        $id = trim((string) get_option('ptms_trust_installation_id', ''));
        if ($id !== '') return $id;
        $result = self::signed_request('register-installation.php', array('domain'=>PTMS_Core::domain(),'fingerprint'=>PTMS_Core::domain_fingerprint(),'product_key'=>PTMS_TRUST_PRODUCT_KEY,'plugin_version'=>PTMS_VERSION,'wp_version'=>get_bloginfo('version'),'php_version'=>PHP_VERSION));
        if (is_wp_error($result)) return $result;
        $id = sanitize_text_field((string)($result['installation_id'] ?? ''));
        if ($id === '') return new WP_Error('ptms_installation', __('The license server did not return an installation ID.', 'pw-merchant-api-system'));
        update_option('ptms_trust_installation_id', $id, false);
        if (!empty($result['license']) && is_array($result['license'])) self::store($result['license']);
        return $id;
    }

    private static function is_missing_trust_installation($error) {
        if (!is_wp_error($error)) return false;

        $code = sanitize_key((string) $error->get_error_code());
        if ($code === 'ptms_connect_installation_not_found') return true;

        $message = strtolower(remove_accents((string) $error->get_error_message()));
        if (strpos($message, 'site baglanti kaydi') !== false) return false;

        return strpos($message, 'kurulum kaydi bulunamadi') !== false
            || strpos($message, 'installation record') !== false;
    }

    private static function repair_trust_installation() {
        delete_option('ptms_trust_installation_id');
        delete_option('ptms_license_checked_at');
        return self::installation();
    }

    private static function store(array $license) {
        $allowed = array('type','status','starts_at','expires_at','grace_ends_at','days_left','can_send','domain','installation_id','product_limit','used','remaining');
        $clean = array();
        foreach ($allowed as $key) if (array_key_exists($key, $license)) $clean[$key] = is_bool($license[$key]) ? $license[$key] : sanitize_text_field((string)$license[$key]);
        update_option('ptms_trust_license', $clean, false);
        update_option('ptms_license_checked_at', time(), false);
        delete_option('ptms_license_last_error');
        return $clean;
    }

    public static function activate($code) {
        $code = strtoupper((string) preg_replace('/\s+/', '', sanitize_text_field((string)$code)));
        if (!preg_match('/^PWM-[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}-[A-Z2-9]{4}$/', $code)) return new WP_Error('ptms_format', __('The license code must be in the format PWM-XXXX-XXXX-XXXX-XXXX.', 'pw-merchant-api-system'));
        $id = self::installation();
        if (is_wp_error($id)) { update_option('ptms_license_last_error', $id->get_error_message(), false); return $id; }
        $result = self::signed_request('activate-license.php', array('installation_id'=>$id,'license_code'=>$code));
        if (self::is_missing_trust_installation($result)) {
            $id = self::repair_trust_installation();
            if (is_wp_error($id)) { update_option('ptms_license_last_error', $id->get_error_message(), false); return $id; }
            $result = self::signed_request('activate-license.php', array('installation_id'=>$id,'license_code'=>$code));
        }
        if (is_wp_error($result)) { update_option('ptms_license_last_error', $result->get_error_message(), false); return $result; }
        if (empty($result['license']) || !is_array($result['license'])) return new WP_Error('ptms_license_result', __('License status could not be obtained.', 'pw-merchant-api-system'));
        return self::store($result['license']);
    }

    public static function refresh($force=false) {
        $checked=(int)get_option('ptms_license_checked_at',0);
        if (!$force && $checked && time()-$checked < 6*HOUR_IN_SECONDS) return self::data();
        $id=self::installation();
        if (is_wp_error($id)) return $id;
        $result=self::signed_request('license-status.php',array('installation_id'=>$id));
        if (self::is_missing_trust_installation($result)) {
            $id=self::repair_trust_installation();
            if (is_wp_error($id)) return $id;
            $result=self::signed_request('license-status.php',array('installation_id'=>$id));
        }
        if (is_wp_error($result)) { update_option('ptms_license_last_error',$result->get_error_message(),false); return $result; }
        if (empty($result['license']) || !is_array($result['license'])) return new WP_Error('ptms_license_status',__('License status could not be obtained.', 'pw-merchant-api-system'));
        return self::store($result['license']);
    }

    public static function maybe_refresh() {
        if (!current_user_can('manage_options') || !get_option('ptms_trust_installation_id')) return;
        self::refresh(false);
    }

    private static function error_message($error) {
        $map=array('license_not_found'=>__('License code not found.', 'pw-merchant-api-system'),'license_revoked'=>__('This license has been revoked.', 'pw-merchant-api-system'),'license_already_used'=>__('This license is being used in another installation.', 'pw-merchant-api-system'),'product_mismatch'=>__('The license was not created for this product.', 'pw-merchant-api-system'),'domain_mismatch'=>__('The license does not match this domain.', 'pw-merchant-api-system'),'installation_not_found'=>__('No installation record found.', 'pw-merchant-api-system'),'product_not_found'=>__('The PW Feed product is not active in the licensing system.', 'pw-merchant-api-system'),'rate_limit_exceeded'=>__('Too many requests have been sent. Try again soon.', 'pw-merchant-api-system'),'invalid_signature'=>__('The security signature of the license request could not be verified.', 'pw-merchant-api-system'));
        return $map[$error] ?? __('The licensing process could not be completed.', 'pw-merchant-api-system');
    }
}
