<?php

namespace App\Services;

use App\Models\Product;
use App\Models\ProgrammingLanguage;
use App\Models\Setting;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class LicenseGeneratorService
{
    /**
     * Get API token from database settings
     */
    private function getApiToken(): string
    {
        return \App\Helpers\ConfigHelper::getSetting('license_api_token', '', 'LICENSE_API_TOKEN');
    }

    /**
     * Get Envato token from database settings
     */
    private function getEnvatoToken(): string
    {
        return \App\Helpers\ConfigHelper::getSetting('envato_personal_token', '', 'ENVATO_PERSONAL_TOKEN');
    }

    /**
     * Generate license verification file for a product
     * Only generates new file if significant changes occurred or no file exists
     */
    public function generateLicenseFile(Product $product): string
    {
        // Refresh the product to get the latest data including programming language
        $product->refresh();
        $language = $product->programmingLanguage;

        if (!$language) {
            throw new \Exception('Programming language not found for product');
        }

        // Delete old files for this product first
        $this->deleteOldLicenseFiles($product);

        // Check if we need to generate a new file
        $existingPath = $product->integration_file_path;
        $shouldGenerateNew = $this->shouldGenerateNewFile($product, $existingPath);

        if (!$shouldGenerateNew && $existingPath && Storage::disk('public')->exists($existingPath)) {
            // Return existing file path without regenerating
            return $existingPath;
        }

        // Generate new file
        $template = $this->getLicenseTemplate($language);
        $fileContent = $this->compileTemplate($template, $product);
        $fileName = $this->generateFileName($product, $language);
        $filePath = $this->saveLicenseFile($fileContent, $fileName, $product);

        // Update product with new integration file path
        $product->update(['integration_file_path' => $filePath]);

        return $filePath;
    }

    /**
     * Delete old license files for a specific product
     */
    private function deleteOldLicenseFiles(Product $product): void
    {
        $productDir = "licenses/{$product->id}";
        
        if (!Storage::disk('public')->exists($productDir)) {
            return;
        }

        // Get all files in the product directory
        $files = Storage::disk('public')->files($productDir);
        
        foreach ($files as $file) {
            // Delete all old files for this product
            Storage::disk('public')->delete($file);
        }
    }

    /**
     * Check if we should generate a new license file
     * Only generate new file if no file exists or significant changes occurred
     */
    private function shouldGenerateNewFile(Product $product, ?string $existingPath): bool
    {
        // Always generate new file to ensure we have the latest template and correct extension
        // The deleteOldLicenseFiles method will handle cleaning up old files
        return true;
    }

    /**
     * Get license template for programming language
     */
    private function getLicenseTemplate(ProgrammingLanguage $language): string
    {
        $templatePath = resource_path("templates/licenses/{$language->slug}.blade.php");

        if (!file_exists($templatePath)) {
            // Create default template if not exists
            $this->createDefaultTemplate($language);
        }

        return file_get_contents($templatePath);
    }

    /**
     * Compile template with product data
     */
    private function compileTemplate(string $template, Product $product): string
    {
        // Build the license API URL from environment/app url and the configured verification endpoint
        $apiDomain = rtrim(env('APP_URL', config('app.url')), '/');
        $verificationEndpoint = config('license.verification_endpoint', '/api/license/verify');
        $licenseApiUrl = $apiDomain . '/' . ltrim($verificationEndpoint, '/');

        $data = [
            'product' => $product->name,
            'product_slug' => $product->slug,
            'license_api_url' => $licenseApiUrl,
            'verification_key' => $this->generateVerificationKey($product),
            // Get tokens from database settings
            'api_token' => $this->getApiToken(),
            'envato_token' => $this->getEnvatoToken(),
            'envato_client_id' => '',
            // envato_api_base is safe to include (no secret) if needed by templates
            'envato_api_base' => config('envato.api_base'),
            'date' => now()->format('Y-m-d H:i:s'),
        ];

        // Simple template compilation
        foreach ($data as $key => $value) {
            $template = str_replace("{{{$key}}}", $value, $template);
            $template = str_replace("{{$key}}", $value, $template);
        }
        
        // Debug: Log the data being used
        \Log::info('License generation data:', $data);
        \Log::info('Template after compilation (first 500 chars):', ['template' => substr($template, 0, 500)]);

        return $template;
    }

    /**
     * Generate unique verification key for product
     */
    private function generateVerificationKey(Product $product): string
    {
        return hash('sha256', $product->id . $product->slug . config('app.key'));
    }

    /**
     * Generate file name based on product and language
     * Creates unique filename to avoid overwriting existing working license files
     */
    private function generateFileName(Product $product, ProgrammingLanguage $language): string
    {
        $extension = $this->getFileExtensionForLanguage($language->slug);
        $timestamp = now()->format('Y-m-d_H-i-s');
        return "license-{$product->slug}-{$timestamp}.{$extension}";
    }

    /**
     * Get file extension for programming language
     */
    private function getFileExtensionForLanguage(string $languageSlug): string
    {
        $extensions = [
            'php' => 'php',
            'laravel' => 'php',
            'javascript' => 'js',
            'python' => 'py',
            'java' => 'java',
            'csharp' => 'cs',
            'cpp' => 'cpp',
            'wordpress' => 'php',
            'react' => 'js',
            'angular' => 'ts',
            'nodejs' => 'js',
            'vuejs' => 'js',
            'go' => 'go',
            'swift' => 'swift',
            'typescript' => 'ts',
            'kotlin' => 'kt',
            'c' => 'c',
            'html-css' => 'html',
            'flask' => 'py',
            'django' => 'py',
            'expressjs' => 'js',
            'ruby-on-rails' => 'rb',
            'spring-boot' => 'java',
            'symfony' => 'php',
            'aspnet' => 'cs',
            'html' => 'html',
            'ruby' => 'rb',
        ];

        return $extensions[$languageSlug] ?? 'php';
    }

    /**
     * Save license file to storage
     */
    private function saveLicenseFile(string $content, string $fileName, Product $product): string
    {
        $path = "licenses/{$product->id}/{$fileName}";

        Storage::disk('public')->put($path, $content);

        return $path;
    }

    /**
     * Create default template for programming language
     */
    private function createDefaultTemplate(ProgrammingLanguage $language): void
    {
        $templateDir = resource_path('templates/licenses');
        if (!is_dir($templateDir)) {
            mkdir($templateDir, 0755, true);
        }

        $templatePath = "{$templateDir}/{$language->slug}.blade.php";

        if ($language->slug === 'php') {
            $template = $this->getPHPTemplate();
        } elseif ($language->slug === 'javascript') {
            $template = $this->getJavaScriptTemplate();
        } elseif ($language->slug === 'python') {
            $template = $this->getPythonTemplate();
        } else {
            $template = $this->getGenericTemplate($language);
        }

        file_put_contents($templatePath, $template);
    }

    /**
     * Get PHP license template
     */
    private function getPHPTemplate(): string
    {
        return <<<'PHP'
/**
     * Get PHP license template
     */
    private function getPHPTemplate(): string
    {
        return <<<'PHP'
<?php
/**
 * License Verification System
 * Product: {{product}}
 * Generated: {{date}}
 */

class LicenseVerifier {
    private $apiUrl = '{{license_api_url}}';
    private $productSlug = '{{product_slug}}';
    private $verificationKey = '{{verification_key}}';
    private $apiToken = '{{api_token}}';
    private $envatoToken = '{{envato_token}}';
    private $envatoApiBase = '{{envato_api_base}}';

    /**
     * Verify license with purchase code
     * This method uses the new dual verification system:
     * 1. If Envato valid but not in database -> auto-create license and allow
     * 2. If database valid but Envato invalid -> allow (offline scenarios)
     * 3. If both valid -> allow
     * 4. If both invalid -> reject
     */
    public function verifyLicense($purchaseCode, $domain = null) {
        try {
            // Send request to our license server for dual verification
            $result = $this->verifyWithOurSystem($purchaseCode, $domain);
            
            if ($result['valid']) {
                $verificationMethod = $result['data']['verification_method'] ?? 'unknown';
                $message = 'License verified successfully';
                
                return $this->createLicenseResponse(true, $message, [
                    'verification_method' => $verificationMethod,
                    'envato_valid' => $result['data']['envato_valid'] ?? false,
                    'database_valid' => $result['data']['database_valid'] ?? false,
                    'license_data' => $result['data']
                ]);
            }

            // Verification failed
            return $this->createLicenseResponse(false, $result['message'] ?? 'License verification failed');

        } catch (Exception $e) {
            return $this->createLicenseResponse(false, 'Verification failed: ' . $e->getMessage());
        }
    }

    /**
     * Verify with Envato API
     */
    private function verifyWithEnvato($purchaseCode) {
        if (empty($this->envatoToken)) {
            return ['valid' => false, 'error' => 'Envato token not configured'];
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->envatoApiBase . "/v3/market/author/sale?code=" . urlencode($purchaseCode));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->envatoToken,
            'User-Agent: LicenseVerifier/1.0'
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200) {
            $data = json_decode($response, true);
            return [
                'valid' => true,
                'data' => $data,
                'source' => 'envato'
            ];
        }

        return ['valid' => false, 'error' => 'Envato API returned HTTP ' . $httpCode];
    }

    /**
     * Verify with our license system
     */
    private function verifyWithOurSystem($purchaseCode, $domain = null) {
        $postData = [
            'purchase_code' => $purchaseCode,
            'product_slug' => $this->productSlug,
            'domain' => $domain,
            'verification_key' => $this->verificationKey
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded',
            'User-Agent: LicenseVerifier/1.0',
            'Authorization: Bearer ' . $this->apiToken
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200) {
            $data = json_decode($response, true);
            return [
                'valid' => $data['valid'] ?? false,
                'message' => $data['message'] ?? 'Verification completed',
                'data' => $data,
                'source' => 'our_system'
            ];
        }

        return [
            'valid' => false,
            'error' => 'Unable to verify license with our system',
            'http_code' => $httpCode
        ];
    }

    /**
     * Create standardized response
     */
    private function createLicenseResponse($valid, $message, $data = null) {
        return [
            'valid' => $valid,
            'message' => $message,
            'data' => $data,
            'verified_at' => date('Y-m-d H:i:s'),
            'product' => $this->productSlug
        ];
    }
}

// Usage example:
/*
$verifier = new LicenseVerifier();
$result = $verifier->verifyLicense('YOUR_PURCHASE_CODE', 'yourdomain.com');

if ($result['valid']) {
    echo "License is valid!";
} else {
    echo "License verification failed: " . $result['message'];
}
*/
PHP;
    }

    /**
     * Get JavaScript license template
     */
    private function getJavaScriptTemplate(): string
    {
        return <<<'JS'
/**
 * License Verification System
 * Product: {{product_slug}}
 * Generated: {{date}}
 */

class LicenseVerifier {
    constructor() {
        this.apiUrl = '{{license_api_url}}';
        this.productSlug = '{{product_slug}}';
        this.verificationKey = '{{verification_key}}';
    }

    /**
     * Verify license with purchase code
     * Uses the new dual verification system
     */
    async verifyLicense(purchaseCode, domain = null) {
        try {
            // Send request to our license server for dual verification
            const result = await this.verifyWithOurSystem(purchaseCode, domain);
            
            if (result.valid) {
                const verificationMethod = result.data.verification_method || 'unknown';
                const message = 'License verified successfully';
                
                return this.createLicenseResponse(true, message, {
                    verification_method: verificationMethod,
                    envato_valid: result.data.envato_valid || false,
                    database_valid: result.data.database_valid || false,
                    license_data: result.data
                });
            }

            // Verification failed
            return this.createLicenseResponse(false, result.message || 'License verification failed');

        } catch (error) {
            return this.createLicenseResponse(false, 'Verification failed: ' + error.message);
        }
    }

    /**
     * Verify with Envato API
     */
    async verifyWithEnvato(purchaseCode) {
        try {
            const response = await fetch(`https://api.envato.com/v3/market/author/sale?code=${encodeURIComponent(purchaseCode)}`, {
                headers: {
                    'Authorization': 'Bearer YOUR_ENVATO_TOKEN',
                    'User-Agent': 'LicenseVerifier/1.0'
                }
            });

            if (response.ok) {
                const data = await response.json();
                return {
                    valid: true,
                    data: data
                };
            }

            return { valid: false };
        } catch (error) {
            return { valid: false };
        }
    }

    /**
     * Verify with our license system
     */
    async verifyWithOurSystem(purchaseCode, domain = null) {
        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'User-Agent': 'LicenseVerifier/1.0'
                },
                body: new URLSearchParams({
                    purchase_code: purchaseCode,
                    product_slug: this.productSlug,
                    domain: domain,
                    verification_key: this.verificationKey
                })
            });

            if (response.ok) {
                const data = await response.json();
                return this.createLicenseResponse(
                    data.valid || false,
                    data.message || 'Verification completed',
                    data
                );
            }

            return this.createLicenseResponse(false, 'Unable to verify license');
        } catch (error) {
            return this.createLicenseResponse(false, 'Network error: ' + error.message);
        }
    }

    /**
     * Create standardized response
     */
    createLicenseResponse(valid, message, data = null) {
        return {
            valid: valid,
            message: message,
            data: data,
            verified_at: new Date().toISOString(),
            product: this.productSlug
        };
    }
}

// Usage example:
/*
const verifier = new LicenseVerifier();
verifier.verifyLicense('YOUR_PURCHASE_CODE', 'yourdomain.com')
    .then(result => {
        if (result.valid) {
            // License is valid
        } else {
            // License verification failed
        }
    });
*/
JS;
    }

    /**
     * Get Python license template
     */
    private function getPythonTemplate(): string
    {
        return <<<'PYTHON'
"""
License Verification System
Product: {{product_slug}}
Generated: {{date}}
"""

import requests
import json
from datetime import datetime

class LicenseVerifier:
    def __init__(self):
        self.api_url = '{{license_api_url}}'
        self.product_slug = '{{product_slug}}'
        self.verification_key = '{{verification_key}}'

    def verify_license(self, purchase_code, domain=None):
        """
        Verify license with purchase code
        Uses the new dual verification system
        """
        try:
            # Send request to our license server for dual verification
            result = self._verify_with_our_system(purchase_code, domain)
            
            if result['valid']:
                verification_method = result['data'].get('verification_method', 'unknown')
                message = 'License verified successfully'
                
                return self._create_license_response(True, message, {
                    'verification_method': verification_method,
                    'envato_valid': result['data'].get('envato_valid', False),
                    'database_valid': result['data'].get('database_valid', False),
                    'license_data': result['data']
                })

            # Verification failed
            return self._create_license_response(False, result.get('message', 'License verification failed'))

        except Exception as e:
            return self._create_license_response(False, f'Verification failed: {str(e)}')

    def _verify_with_envato(self, purchase_code):
        """
        Verify with Envato API
        """
        try:
            headers = {
                'Authorization': 'Bearer YOUR_ENVATO_TOKEN',
                'User-Agent': 'LicenseVerifier/1.0'
            }

            response = requests.get(
                f'https://api.envato.com/v3/market/author/sale?code={purchase_code}',
                headers=headers,
                timeout=10
            )

            if response.status_code == 200:
                data = response.json()
                return {
                    'valid': True,
                    'data': data
                }

            return {'valid': False}
        except:
            return {'valid': False}

    def _verify_with_our_system(self, purchase_code, domain=None):
        """
        Verify with our license system
        """
        try:
            data = {
                'purchase_code': purchase_code,
                'product_slug': self.product_slug,
                'domain': domain,
                'verification_key': self.verification_key
            }

            response = requests.post(
                self.api_url,
                data=data,
                headers={
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'User-Agent': 'LicenseVerifier/1.0'
                },
                timeout=10
            )

            if response.status_code == 200:
                result = response.json()
                return self._create_license_response(
                    result.get('valid', False),
                    result.get('message', 'Verification completed'),
                    result
                )

            return self._create_license_response(False, 'Unable to verify license')
        except Exception as e:
            return self._create_license_response(False, f'Network error: {str(e)}')

    def _create_license_response(self, valid, message, data=None):
        """
        Create standardized response
        """
        return {
            'valid': valid,
            'message': message,
            'data': data,
            'verified_at': datetime.now().isoformat(),
            'product': self.product_slug
        }

# Usage example:
"""
verifier = LicenseVerifier()
result = verifier.verify_license('YOUR_PURCHASE_CODE', 'yourdomain.com')

if result['valid']:
    print('License is valid!')
else:
    print(f'License verification failed: {result["message"]}')
"""
PYTHON;
    }

    /**
     * Get generic template for other languages
     */
    private function getGenericTemplate(ProgrammingLanguage $language): string
    {
        return <<<GENERIC
/**
 * License Verification System
 * Product: {{product}}
 * Language: {$language->name}
 * Generated: {{date}}
 *
 * This is a generic template. Please customize according to {$language->name} best practices.
 */

// License verification for {$language->name}
// API URL: {{license_api_url}}
// Product Slug: {{product_slug}}
// Verification Key: {{verification_key}}
// API Token: {{api_token}}
// Envato Token: {{envato_token}}

// IMPORTANT: This is a generic template. You need to implement the actual license verification
// logic according to {$language->name} best practices. The system will provide:
// - API URL: {{license_api_url}}
// - Product Slug: {{product_slug}}
// - Verification Key: {{verification_key}}
// - API Token: {{api_token}}
// - Envato Token: {{envato_token}}

// Example implementation structure:
// 1. Create a license verification class/function
// 2. Use the provided API URL and tokens
// 3. Implement dual verification (Envato + our system)
// 4. Return standardized response format

GENERIC;
    }
}