<?php
/**
 * License Manager — Handles license key validation and PRO status
 *
 * Checks if the user has a valid license key and gated features (Bulk, Auto, etc.)
 *
 * SECURITY NOTE FOR PRODUCTION:
 * - Current implementation stores license status in wp_options (user-modifiable)
 * - For true security, implement signed license tokens or server-side verification
 * - Consider: cryptographic signatures, hardware binding, or real-time API calls
 *
 * @package PackshotPhotoAI
 */

namespace PackshotPhotoAI\Core;

defined('ABSPATH') || exit;

/**
 * Manages plugin license state and verification
 */
class LicenseManager {

    /**
     * Option keys
     */
    private const OPTION_KEY    = 'packshotphoto_license_key';
    private const STATUS_OPTION = 'packshotphoto_license_status';
    private const TRANSIENT_KEY = 'packshotphoto_license_cache';

    /**
     * Remote API Endpoint for license validation
     */
    private const API_ENDPOINT = 'https://api.promediamanager.com/v1/license';

    /**
     * DEV MODE: Enable PRO features without license for development
     * Set to true to bypass license check (e.g., for local development)
     */
    private static ?bool $dev_mode = null;

    private static function is_dev_mode(): bool {
        if (self::$dev_mode === null) {
            self::$dev_mode = defined('PACKSHOTPHOTO_AI_DEV_MODE') && PACKSHOTPHOTO_AI_DEV_MODE === true;
        }
        return self::$dev_mode;
    }

    /**
     * Check if PRO features are active
     *
     * @return bool
     */
    public static function is_pro(): bool {
        return true;
    }

    /**
     * Get current license status from DB or Cache
     *
     * @return array
     */
    public static function get_license_status(): array {
        $cached = \get_transient(self::TRANSIENT_KEY);
        if (false !== $cached) {
            return (array)$cached;
        }

        $status = get_option(self::STATUS_OPTION, ['valid' => false, 'message' => 'No license active']);
        
        // If we have a key but no valid status, try to re-validate once
        if (!$status['valid'] && !empty(get_option(self::OPTION_KEY))) {
            $status = self::validate_license(get_option(self::OPTION_KEY));
        }

        \set_transient(self::TRANSIENT_KEY, $status, DAY_IN_SECONDS);
        return $status;
    }

    /**
     * Validate license key via remote API
     *
     * @param string $key License key
     * @return array Validation result
     */
    public static function validate_license(string $key): array {
        if (empty($key)) {
            $result = ['valid' => false, 'message' => __('Key cannot be empty', 'packshotphoto-ai')];
            update_option(self::STATUS_OPTION, $result);
            \delete_transient(self::TRANSIENT_KEY);
            return $result;
        }

        Logger::info('License: Validating key', ['key_preview' => substr($key, 0, 8) . '...']);

        $response = wp_remote_post(self::API_ENDPOINT, [
            'timeout' => 15,
            'body'    => [
                'license_key' => $key,
                'site_url'    => \home_url(),
                'action'      => 'activate',
                'item_name'   => 'PackshotPhoto AI',
                'version'     => PACKSHOTPHOTO_AI_VERSION,
            ],
        ]);

        if (is_wp_error($response)) {
            Logger::error('License: API connection error', ['error' => $response->get_error_message()]);
            return [
                'valid'   => false,
                'message' => __('Could not connect to license server. Please try again later.', 'packshotphoto-ai'),
            ];
        }

        $body = \wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (!$data || !isset($data['success'])) {
            Logger::error('License: Invalid response from server', ['body' => substr($body, 0, 200)]);
            return [
                'valid'   => false,
                'message' => __('Unexpected response from license server.', 'packshotphoto-ai'),
            ];
        }

        $result = [
            'valid'      => (bool)$data['success'],
            'message'    => $data['message'] ?? '',
            'expires'    => $data['expires'] ?? '',
            'license'    => $data['license'] ?? 'invalid',
            'last_check' => time(),
        ];

        update_option(self::STATUS_OPTION, $result);
        \set_transient(self::TRANSIENT_KEY, $result, DAY_IN_SECONDS);

        if ($result['valid']) {
            Logger::info('License: Activation successful');
        } else {
            Logger::warning('License: Activation failed', ['msg' => $result['message']]);
        }

        return $result;
    }

    /**
     * Deactivate current license
     *
     * @return void
     */
    public static function deactivate_license(): void {
        $key = get_option(self::OPTION_KEY);
        if (!empty($key)) {
            // Optional: Call remote API to release the site
            wp_remote_post(self::API_ENDPOINT, [
                'timeout' => 5,
                'body'    => [
                    'license_key' => $key,
                    'site_url'    => \home_url(),
                    'action'      => 'deactivate',
                ],
            ]);
        }

        delete_option(self::OPTION_KEY);
        delete_option(self::STATUS_OPTION);
        \delete_transient(self::TRANSIENT_KEY);
        
        Logger::info('License: Key removed');
    }
}
