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

// Load API client
require_once WP_PLUGIN_DIR . '/blogibot/src/API/Client.php';

class Blog82AI_License_Manager {
    
    private static $option_name = 'blog82ai_license_data';
    
    /**
     * Check if license is valid and set
     */
    public static function is_license_valid() {
        $license_data = get_option(self::$option_name, []);
        
        return !empty($license_data['license_key']) && 
               !empty($license_data['domain']) && 
               isset($license_data['status']) && 
               $license_data['status'] === 'active';
    }
    
    /**
     * Get license data
     */
    public static function get_license_data() {
        return get_option(self::$option_name, [
            'license_key' => '',
            'domain' => '',
            'status' => 'inactive',
            'user_type' => 'free', // free, starter, agency, enterprise
            'activated_at' => '',
            'last_checked' => ''
        ]);
    }
    
    /**
     * Save license data
     */
    public static function save_license_data($license_key, $domain, $user_type = 'free') {
        $license_data = [
            'license_key' => sanitize_text_field($license_key),
            'domain' => sanitize_text_field($domain),
            'status' => 'active',
            'user_type' => sanitize_text_field($user_type),
            'activated_at' => current_time('mysql'),
            'last_checked' => current_time('mysql')
        ];
        
        return update_option(self::$option_name, $license_data);
    }
    
    /**
     * Remove license data
     */
    public static function remove_license() {
        $license_data = self::get_license_data();
        
        // If we have a valid license, try to remove registration first
        if (!empty($license_data['license_key']) && !empty($license_data['domain'])) {
            // Try the new remove endpoint first, fallback to deregister if it fails
            $remove_result = Blog82AI_API_Client::remove_license_registration(
                $license_data['license_key'],
                $license_data['domain']
            );
            
            // If the new endpoint fails (maybe not implemented yet), try the old deregister endpoint
            if (!$remove_result['success'] && isset($remove_result['error']) && 
                (strpos($remove_result['error'], '404') !== false || strpos($remove_result['error'], 'not found') !== false)) {
                
                error_log('Blogibot: Remove endpoint not found, falling back to deregister');
                $remove_result = Blog82AI_API_Client::deregister_license(
                    $license_data['license_key'],
                    $license_data['domain']
                );
            }
            
            // Log removal result for debugging
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('License removal result: ' . json_encode($remove_result));
            }
            
            // Return API result with local cleanup
            if ($remove_result['success']) {
                $local_deleted = delete_option(self::$option_name);
                return [
                    'success' => true,
                    'message' => $remove_result['message'] ?? 'License removed successfully',
                    'local_cleanup' => $local_deleted
                ];
            } else {
                // Even if API fails, still remove local data for better UX
                delete_option(self::$option_name);
                return [
                    'success' => true, // Return success for UX, but note the API failure
                    'message' => 'License removed locally. API removal failed: ' . ($remove_result['error'] ?? 'Unknown error'),
                    'local_cleanup' => true,
                    'api_failed' => true
                ];
            }
        }
        
        // No license data to remove, just clean up local
        $deleted = delete_option(self::$option_name);
        return [
            'success' => true,
            'message' => 'No license data found to remove',
            'local_cleanup' => $deleted
        ];
    }
    
    /**
     * Register license with remote server
     */
    public static function register_license($license_key, $domain) {
        // Basic validation first
        $basic_validation = self::basic_license_validation($license_key, $domain);
        if (!$basic_validation['valid']) {
            return $basic_validation;
        }
        
        // Register with API
        $api_result = Blog82AI_API_Client::register_license($license_key, $domain);
        
        if ($api_result['success']) {
            // Extract plan from API response (default to 'free' if not provided)
            $user_type = 'free';
            if (isset($api_result['data']['plan'])) {
                $user_type = strtolower(sanitize_text_field($api_result['data']['plan']));
            }
            
            // Save license data locally with user_type
            if (self::save_license_data($license_key, $domain, $user_type)) {
                return [
                    'valid' => true,
                    'message' => 'License registered and activated successfully',
                    'data' => $api_result['data'] ?? []
                ];
            } else {
                return [
                    'valid' => false,
                    'message' => 'License registered remotely but failed to save locally'
                ];
            }
        } else {
            return [
                'valid' => false,
                'message' => $api_result['error'] ?? 'Failed to register license'
            ];
        }
    }
    
    /**
     * Validate license with remote server
     */
    public static function validate_license($license_key, $domain) {
        // Basic validation first
        $basic_validation = self::basic_license_validation($license_key, $domain);
        if (!$basic_validation['valid']) {
            return $basic_validation;
        }
        
        // Validate with API
        $api_result = Blog82AI_API_Client::validate_license($license_key, $domain);
        
        if ($api_result['success']) {
            // Update last checked time and plan if provided
            $license_data = self::get_license_data();
            $license_data['last_checked'] = current_time('mysql');
            
            // Update plan/user_type if provided in response
            if (isset($api_result['data']['plan'])) {
                $license_data['user_type'] = strtolower(sanitize_text_field($api_result['data']['plan']));
            }
            
            update_option(self::$option_name, $license_data);
            
            return [
                'valid' => true,
                'message' => 'License is valid and active',
                'data' => $api_result['data'] ?? []
            ];
        } else {
            return [
                'valid' => false,
                'message' => $api_result['error'] ?? 'License validation failed'
            ];
        }
    }
    
    /**
     * Basic license validation (offline)
     */
    private static function basic_license_validation($license_key, $domain) {
        if (empty($license_key) || strlen($license_key) < 10) {
            return [
                'valid' => false,
                'message' => 'License key must be at least 10 characters long'
            ];
        }
        
        if (empty($domain) || !filter_var('http://' . $domain, FILTER_VALIDATE_URL)) {
            return [
                'valid' => false,
                'message' => 'Please enter a valid domain name'
            ];
        }
        
        return [
            'valid' => true,
            'message' => 'Basic validation passed'
        ];
    }
    
    /**
     * Get license status for display
     */
    public static function get_license_status() {
        $license_data = self::get_license_data();
        
        if (self::is_license_valid()) {
            return [
                'status' => 'active',
                'message' => 'License is active and valid',
                'license_key' => $license_data['license_key'],
                'domain' => $license_data['domain'],
                'activated_at' => $license_data['activated_at']
            ];
        }
        
        return [
            'status' => 'inactive',
            'message' => 'No valid license found',
            'license_key' => '',
            'domain' => '',
            'activated_at' => ''
        ];
    }
    
    /**
     * Get API debug information
     */
    public static function get_api_debug_info() {
        if (!defined('WP_DEBUG') || !WP_DEBUG) {
            return null;
        }
        
        return Blog82AI_API_Client::get_debug_info();
    }
    
    /**
     * Get user type (free, starter, agency, enterprise)
     */
    public static function get_user_type() {
        $license_data = self::get_license_data();
        
        // If no valid license, return 'free'
        if (!self::is_license_valid()) {
            return 'free';
        }
        
        return $license_data['user_type'] ?? 'free';
    }
    
    /**
     * Check if user has access to premium features
     */
    public static function has_feature_access($feature) {
        $user_type = self::get_user_type();
        
        // Free users have no premium features
        if ($user_type === 'free') {
            return false;
        }
        
        // Define feature access per user type
        $feature_matrix = [
            'featured_image' => ['starter', 'agency', 'enterprise'],
            'content_images' => ['starter', 'agency', 'enterprise'],
            'image_regeneration' => ['starter', 'agency', 'enterprise'],
            'title_regeneration' => ['starter', 'agency', 'enterprise'],
            'content_regeneration' => ['starter', 'agency', 'enterprise']
        ];
        
        // Check if feature exists and user type has access
        if (isset($feature_matrix[$feature])) {
            return in_array($user_type, $feature_matrix[$feature]);
        }
        
        // Unknown feature defaults to no access
        return false;
    }
    
    /**
     * Check if current user is free tier
     */
    public static function is_free_user() {
        return self::get_user_type() === 'free';
    }
}
