<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CertificateTemplate;
use App\Services\CertificateGenerationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class TemplateBuilderController extends Controller
{
    protected $certificateService;

    public function __construct(CertificateGenerationService $certificateService)
    {
        $this->certificateService = $certificateService;
    }

    public function index()
    {
        $templates = CertificateTemplate::with('creator')
            ->orderBy('created_at', 'desc')
            ->paginate(12);

        return view('admin.template-builder.index', compact('templates'));
    }

    public function create()
    {
        $fonts = CertificateTemplate::first()->available_fonts ?? [];
        $dataSources = CertificateTemplate::first()->available_data_sources ?? [];

        return view('admin.template-builder.create', compact('fonts', 'dataSources'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'background_image' => 'required|image|mimes:jpeg,png,jpg,gif|max:5120',
            'width' => 'required|integer|min:100|max:3000',
            'height' => 'required|integer|min:100|max:3000',
            'template_data' => 'required|json',
            'category' => 'nullable|string|max:100',
        ]);

        try {
            // Handle background image upload
            $imagePath = $request->file('background_image')->store('certificate-templates', 'public');

            // Get image dimensions
            $imageInfo = getimagesize(storage_path('app/public/' . $imagePath));
            $width = $imageInfo[0];
            $height = $imageInfo[1];

            $template = CertificateTemplate::create([
                'name' => $request->name,
                'description' => $request->description,
                'background_image' => $imagePath,
                'width' => $width,
                'height' => $height,
                'template_data' => json_decode($request->template_data, true),
                'category' => $request->category ?? 'general',
                'created_by' => Auth::id(),
            ]);

            return redirect()->route('admin.template-builder.index')
                ->with('success', 'Template created successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to create template: ' . $e->getMessage()]);
        }
    }

    public function show(CertificateTemplate $template)
    {
        $template->load('creator');
        return view('admin.template-builder.show', compact('template'));
    }

    public function edit(CertificateTemplate $template)
    {
        $fonts = $template->available_fonts;
        $dataSources = $template->available_data_sources;

        return view('admin.template-builder.edit', compact('template', 'fonts', 'dataSources'));
    }

    public function update(Request $request, CertificateTemplate $template)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'background_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5120',
            'template_data' => 'required|json',
            'category' => 'nullable|string|max:100',
            'is_active' => 'boolean',
        ]);

        try {
            $data = [
                'name' => $request->name,
                'description' => $request->description,
                'template_data' => json_decode($request->template_data, true),
                'category' => $request->category ?? 'general',
                'is_active' => $request->has('is_active'),
            ];

            // Handle new background image if provided
            if ($request->hasFile('background_image')) {
                // Delete old image
                if ($template->background_image) {
                    Storage::disk('public')->delete($template->background_image);
                }

                $imagePath = $request->file('background_image')->store('certificate-templates', 'public');
                $data['background_image'] = $imagePath;

                // Update dimensions
                $imageInfo = getimagesize(storage_path('app/public/' . $imagePath));
                $data['width'] = $imageInfo[0];
                $data['height'] = $imageInfo[1];
            }

            $template->update($data);

            return redirect()->route('admin.template-builder.index')
                ->with('success', 'Template updated successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to update template: ' . $e->getMessage()]);
        }
    }

    public function destroy(CertificateTemplate $template)
    {
        try {
            // Delete background image
            if ($template->background_image) {
                Storage::disk('public')->delete($template->background_image);
            }

            $template->delete();

            return redirect()->route('admin.template-builder.index')
                ->with('success', 'Template deleted successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to delete template: ' . $e->getMessage()]);
        }
    }

    public function duplicate(CertificateTemplate $template)
    {
        try {
            $newTemplate = $template->duplicate();

            // Copy background image
            if ($template->background_image) {
                $extension = pathinfo($template->background_image, PATHINFO_EXTENSION);
                $newImagePath = 'certificate-templates/' . Str::random(40) . '.' . $extension;

                Storage::disk('public')->copy($template->background_image, $newImagePath);
                $newTemplate->background_image = $newImagePath;
                $newTemplate->save();
            }

            return redirect()->route('admin.template-builder.index')
                ->with('success', 'Template duplicated successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to duplicate template: ' . $e->getMessage()]);
        }
    }

    public function preview(Request $request, CertificateTemplate $template)
    {
        $request->validate([
            'student_name' => 'required|string',
            'course_name' => 'nullable|string',
            'graduation_date' => 'nullable|date',
            'instructor_name' => 'nullable|string',
            'organization_name' => 'nullable|string',
        ]);

        try {
            $studentData = [
                'student_name' => $request->student_name,
                'course_name' => $request->course_name,
                'graduation_date' => $request->graduation_date ? date('F j, Y', strtotime($request->graduation_date)) : '',
                'instructor_name' => $request->instructor_name,
                'organization_name' => $request->organization_name,
                'serial_number' => 'CERT-' . Str::random(8),
                'current_date' => now()->format('F j, Y'),
                'current_time' => now()->format('g:i A'),
            ];

            $previewPath = $this->certificateService->generateCertificateFromTemplate($template, $studentData, true);

            return response()->json([
                'success' => true,
                'preview_url' => asset('storage/' . $previewPath),
                'download_url' => route('admin.template-builder.download-preview', ['path' => $previewPath])
            ]);

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

    public function downloadPreview($path)
    {
        $fullPath = storage_path('app/public/' . $path);

        if (!file_exists($fullPath)) {
            abort(404);
        }

        return response()->download($fullPath);
    }

    public function export(CertificateTemplate $template)
    {
        try {
            $data = [
                'template' => $template->toArray(),
                'exported_at' => now()->toISOString(),
                'version' => '1.0',
            ];

            $filename = Str::slug($template->name) . '_template.json';

            return response()->json($data)
                ->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
                ->header('Content-Type', 'application/json');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to export template: ' . $e->getMessage()]);
        }
    }

    public function import(Request $request)
    {
        $request->validate([
            'template_file' => 'required|file|mimes:json|max:2048',
        ]);

        try {
            $content = file_get_contents($request->file('template_file')->getPathname());
            $data = json_decode($content, true);

            if (!$data || !isset($data['template'])) {
                throw new \Exception('Invalid template file format');
            }

            $templateData = $data['template'];

            // Create new template from imported data
            $template = CertificateTemplate::create([
                'name' => $templateData['name'] . ' (Imported)',
                'description' => $templateData['description'] ?? null,
                'width' => $templateData['width'] ?? 800,
                'height' => $templateData['height'] ?? 600,
                'template_data' => $templateData['template_data'] ?? [],
                'category' => $templateData['category'] ?? 'imported',
                'created_by' => Auth::id(),
            ]);

            return redirect()->route('admin.template-builder.index')
                ->with('success', 'Template imported successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to import template: ' . $e->getMessage()]);
        }
    }
}
