<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ProgrammingLanguage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ProgrammingLanguageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $languages = ProgrammingLanguage::orderBy('sort_order')->orderBy('name')->paginate(15);
        $availableTemplates = ProgrammingLanguage::getAvailableTemplateFiles();

        // Some views expect $programmingLanguages, others expect $languages — provide both aliases
        return view('admin.programming-languages.index', [
            'programmingLanguages' => $languages,
            'languages' => $languages,
            'availableTemplates' => $availableTemplates,
        ]);
    }

    /**
     * Get license file content for viewing
     */
    public function getLicenseFileContent(Request $request, $language)
    {
        try {
            $type = $request->get('type', 'default');
            $content = '';
            
            if ($type === 'default') {
                // Get default template file
                $templateDir = resource_path('templates/licenses');
                $files = glob($templateDir . '/' . $language . '.{php,blade.php}', GLOB_BRACE);
                
                if (!empty($files)) {
                    $file = $files[0];
                    if (file_exists($file)) {
                        $content = file_get_contents($file);
                    } else {
                        return response()->json([
                            'success' => false,
                            'message' => 'Default template file not found'
                        ], 404);
                    }
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => 'Default template file not found for language: ' . $language
                    ], 404);
                }
            } else {
                // Get custom template from language
                $programmingLanguage = ProgrammingLanguage::where('slug', $language)->first();
                
                if (!$programmingLanguage) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Programming language not found'
                    ], 404);
                }
                
                $templatePath = $programmingLanguage->getTemplateFilePath();
                
                if (file_exists($templatePath)) {
                    $content = file_get_contents($templatePath);
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => 'Custom template file not found'
                    ], 404);
                }
            }
            
            return response()->json([
                'success' => true,
                'content' => $content,
                'language' => $language,
                'type' => $type
            ]);
            
        } catch (\Exception $e) {
            // License file content error
            return response()->json([
                'success' => false,
                'message' => 'Error reading file: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.programming-languages.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:programming_languages,slug',
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:100',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
            'file_extension' => 'nullable|string|max:10',
            'license_template' => 'nullable|string',
        ]);

        $validated['slug'] = $validated['slug'] ?: Str::slug($validated['name']);

        ProgrammingLanguage::create($validated);

        return redirect()->route('admin.programming-languages.index')
            ->with('success', 'Programming language created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(ProgrammingLanguage $programmingLanguage)
    {
        $availableTemplates = ProgrammingLanguage::getAvailableTemplateFiles();

        return view('admin.programming-languages.show', compact('programmingLanguage', 'availableTemplates'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(ProgrammingLanguage $programmingLanguage)
    {
        return view('admin.programming-languages.edit', compact('programmingLanguage'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, ProgrammingLanguage $programmingLanguage)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:programming_languages,slug,' . $programmingLanguage->id,
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:100',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
            'file_extension' => 'nullable|string|max:10',
            'license_template' => 'nullable|string',
        ]);

        $validated['slug'] = $validated['slug'] ?: Str::slug($validated['name']);

        $programmingLanguage->update($validated);

        return redirect()->route('admin.programming-languages.index')
            ->with('success', 'Programming language updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(ProgrammingLanguage $programmingLanguage)
    {
        // Check if language is being used by products
        if ($programmingLanguage->products()->count() > 0) {
            return redirect()->route('admin.programming-languages.index')
                ->with('error', 'Cannot delete programming language that is being used by products.');
        }

        $programmingLanguage->delete();

        return redirect()->route('admin.programming-languages.index')
            ->with('success', 'Programming language deleted successfully.');
    }

    /**
     * Toggle active status of the programming language
     */
    public function toggle(ProgrammingLanguage $programmingLanguage)
    {
        $programmingLanguage->update([
            'is_active' => !$programmingLanguage->is_active
        ]);

        $status = $programmingLanguage->is_active ? 'activated' : 'deactivated';

        return redirect()->route('admin.programming-languages.index')
            ->with('success', "Programming language {$status} successfully.");
    }

    /**
     * Get license template information for the language
     */
    public function getTemplateInfo(ProgrammingLanguage $programmingLanguage)
    {
        $templatePath = resource_path("templates/licenses/{$programmingLanguage->slug}.blade.php");
        $templateExists = file_exists($templatePath);

        $templateInfo = [
            'exists' => $templateExists,
            'path' => $templatePath,
            'size' => $templateExists ? filesize($templatePath) : 0,
            'last_modified' => $templateExists ? date('Y-m-d H:i:s', filemtime($templatePath)) : null,
        ];

        return response()->json($templateInfo);
    }

    /**
     * Get all available license templates
     */
    public function getAvailableTemplates()
    {
        $templateDir = resource_path('templates/licenses');
        $templates = [];

        if (is_dir($templateDir)) {
            $files = glob($templateDir . '/*.blade.php');
            foreach ($files as $file) {
                $filename = basename($file, '.blade.php');
                $templates[] = [
                    'name' => $filename,
                    'path' => $file,
                    'size' => filesize($file),
                    'last_modified' => date('Y-m-d H:i:s', filemtime($file)),
                ];
            }
        }

        return response()->json($templates);
    }

    /**
     * Validate template files
     */
    public function validateTemplates()
    {
        try {
            $availableTemplates = ProgrammingLanguage::getAvailableTemplateFiles();
            $validationResults = [];

            foreach ($availableTemplates as $templateName => $templateInfo) {
                $templatePath = $templateInfo['file_path'];
                $content = file_get_contents($templatePath);

                $result = [
                    'template' => $templateName,
                    'file_path' => $templatePath,
                    'is_valid' => true,
                    'errors' => [],
                    'warnings' => []
                ];

                // Check for required placeholders
                $requiredPlaceholders = [
                    '{PRODUCT_NAME}',
                    '{DOMAIN}',
                    '{LICENSE_CODE}',
                    '{VALID_UNTIL}',
                    '{PRODUCT_VERSION}'
                ];

                foreach ($requiredPlaceholders as $placeholder) {
                    if (strpos($content, $placeholder) === false) {
                        $result['warnings'][] = "Missing placeholder: {$placeholder}";
                    }
                }

                // Basic syntax validation for PHP templates
                if (pathinfo($templatePath, PATHINFO_EXTENSION) === 'php') {
                    $syntaxCheck = $this->validatePHPSyntax($content);
                    if (!$syntaxCheck['valid']) {
                        $result['is_valid'] = false;
                        $result['errors'][] = $syntaxCheck['error'];
                    }
                }

                // Check file permissions
                if (!is_readable($templatePath)) {
                    $result['warnings'][] = 'File is not readable';
                }

                if (!is_writable($templatePath)) {
                    $result['warnings'][] = 'File is not writable';
                }

                $validationResults[] = $result;
            }

            return response()->json([
                'success' => true,
                'validation_results' => $validationResults,
                'summary' => [
                    'total_templates' => count($validationResults),
                    'valid_templates' => count(array_filter($validationResults, fn($r) => $r['is_valid'])),
                    'templates_with_errors' => count(array_filter($validationResults, fn($r) => !empty($r['errors']))),
                    'templates_with_warnings' => count(array_filter($validationResults, fn($r) => !empty($r['warnings'])))
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Validate PHP syntax
     */
    private function validatePHPSyntax($code)
    {
        // Create a temporary file for syntax checking
        $tempFile = tempnam(sys_get_temp_dir(), 'php_syntax_check');
        file_put_contents($tempFile, $code);

        // Run PHP syntax check
        $output = shell_exec("php -l \"$tempFile\" 2>&1");

        // Clean up
        unlink($tempFile);

        if (strpos($output, 'No syntax errors detected') === false) {
            return [
                'valid' => false,
                'error' => trim($output)
            ];
        }

        return [
            'valid' => true,
            'error' => null
        ];
    }

    /**
     * Upload template file
     */
    public function uploadTemplate(Request $request, ProgrammingLanguage $programmingLanguage)
    {
        $request->validate([
            'template_file' => 'required|file|mimes:php,js,py,java,cs,cpp,html|max:1024', // 1MB max
        ]);

        try {
            $file = $request->file('template_file');
            $templateDir = resource_path('templates/licenses');

            // Create directory if it doesn't exist
            if (!is_dir($templateDir)) {
                mkdir($templateDir, 0755, true);
            }

            $filename = $programmingLanguage->slug . '.php';
            $file->move($templateDir, $filename);

            return response()->json([
                'success' => true,
                'message' => 'Template file uploaded successfully',
                'file_path' => $templateDir . '/' . $filename
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to upload template file: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Create template file from textarea content
     */
    public function createTemplateFile(Request $request, ProgrammingLanguage $programmingLanguage)
    {
        $request->validate([
            'template_content' => 'required|string|max:50000',
        ]);

        try {
            $templateDir = resource_path('templates/licenses');

            // Create directory if it doesn't exist
            if (!is_dir($templateDir)) {
                mkdir($templateDir, 0755, true);
            }

            $filename = $programmingLanguage->slug . '.php';
            $filePath = $templateDir . '/' . $filename;

            file_put_contents($filePath, $request->template_content);

            return response()->json([
                'success' => true,
                'message' => 'Template file created successfully',
                'file_path' => $filePath
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create template file: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Export programming languages to CSV
     */
    public function export()
    {
        $languages = ProgrammingLanguage::orderBy('sort_order')->orderBy('name')->get();
        
        $filename = 'programming_languages_' . date('Y-m-d_H-i-s') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];
        
        $callback = function() use ($languages) {
            $file = fopen('php://output', 'w');
            
            // CSV Headers
            fputcsv($file, [
                'ID',
                'Name',
                'Slug',
                'Description',
                'Icon',
                'File Extension',
                'Is Active',
                'Sort Order',
                'Created At',
                'Updated At'
            ]);
            
            // CSV Data
            foreach ($languages as $language) {
                fputcsv($file, [
                    $language->id,
                    $language->name,
                    $language->slug,
                    $language->description,
                    $language->icon,
                    $language->file_extension,
                    $language->is_active ? 'Yes' : 'No',
                    $language->sort_order,
                    $language->created_at->format('Y-m-d H:i:s'),
                    $language->updated_at->format('Y-m-d H:i:s')
                ]);
            }
            
            fclose($file);
        };
        
        return response()->stream($callback, 200, $headers);
    }

    /**
     * Get template content for a programming language
     */
    public function getTemplateContent(ProgrammingLanguage $programmingLanguage)
    {
        $templatePath = resource_path("templates/licenses/{$programmingLanguage->slug}.blade.php");
        
        if (file_exists($templatePath)) {
            $content = file_get_contents($templatePath);
            
            return response()->json([
                'success' => true,
                'content' => $content,
                'file_path' => $templatePath,
                'file_size' => filesize($templatePath),
                'last_modified' => date('Y-m-d H:i:s', filemtime($templatePath))
            ]);
        }
        
        return response()->json([
            'success' => false,
            'message' => 'Template file not found',
            'file_path' => $templatePath
        ], 404);
    }


}