<?php

namespace App\Http\Controllers\Admin;

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

class NewCertificateTemplateController extends Controller
{
    /**
     * Display a listing of templates
     */
    public function index()
    {
        $templates = NewCertificateTemplate::with('creator')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('admin.certificates.new_templates.index', compact('templates'));
    }

    /**
     * Show the form for creating a new template
     */
    public function create()
    {
        return view('admin.certificates.new_templates.create');
    }

    /**
     * Store a newly created template
     */
    public function store(Request $request)
    {
        // Debug: Log the request data
        \Log::info('Certificate Template Store Request', [
            'all_data' => $request->all(),
            'files' => $request->allFiles(),
            'name' => $request->name,
            'description' => $request->description,
            'background_image' => $request->hasFile('background_image') ? 'File present' : 'No file',
            'canvas_width' => $request->canvas_width,
            'canvas_height' => $request->canvas_height,
            'fields_config' => $request->fields_config
        ]);

        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'background_image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
            'canvas_width' => 'required|integer|min:100|max:2000',
            'canvas_height' => 'required|integer|min:100|max:2000',
            'fields_config' => 'nullable|array'
        ]);

        try {
            // Handle background image upload
            $imagePath = $this->uploadBackgroundImage($request->file('background_image'));
            \Log::info('Image uploaded successfully', ['path' => $imagePath]);

            // Create template
            $templateData = [
                'name' => $request->name,
                'description' => $request->description,
                'background_image_path' => $imagePath,
                'background_image_name' => $request->file('background_image')->getClientOriginalName(),
                'canvas_width' => $request->canvas_width,
                'canvas_height' => $request->canvas_height,
                'fields_config' => $request->fields_config ?? [],
                'created_by' => Auth::id()
            ];

            \Log::info('Creating template with data', $templateData);

            $template = NewCertificateTemplate::create($templateData);
            \Log::info('Template created successfully', ['id' => $template->id]);

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

        } catch (\Exception $e) {
            \Log::error('Error creating template', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return back()->withInput()
                ->with('error', 'Error creating template: ' . $e->getMessage());
        }
    }

    /**
     * Display the specified template
     */
    public function show(NewCertificateTemplate $template)
    {
        return view('admin.certificates.new_templates.show', compact('template'));
    }

    /**
     * Show the form for editing the specified template
     */
    public function edit(NewCertificateTemplate $template)
    {
        return view('admin.certificates.new_templates.edit', compact('template'));
    }

    /**
     * Update the specified template
     */
    public function update(Request $request, NewCertificateTemplate $template)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'background_image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'canvas_width' => 'required|integer|min:100|max:2000',
            'canvas_height' => 'required|integer|min:100|max:2000',
            'fields_config' => 'nullable|array'
        ]);

        try {
            $data = [
                'name' => $request->name,
                'description' => $request->description,
                'canvas_width' => $request->canvas_width,
                'canvas_height' => $request->canvas_height,
                'fields_config' => $request->fields_config ?? []
            ];

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

                $imagePath = $this->uploadBackgroundImage($request->file('background_image'));
                $data['background_image_path'] = $imagePath;
                $data['background_image_name'] = $request->file('background_image')->getClientOriginalName();
            }

            $template->update($data);

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

        } catch (\Exception $e) {
            return back()->withInput()
                ->with('error', 'Error updating template: ' . $e->getMessage());
        }
    }

    /**
     * Remove the specified template
     */
    public function destroy(NewCertificateTemplate $template)
    {
        try {
            // Delete background image
            if ($template->background_image_path) {
                Storage::disk('public')->delete($template->background_image_path);
            }

            $template->delete();

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

        } catch (\Exception $e) {
            return back()->with('error', 'Error deleting template: ' . $e->getMessage());
        }
    }

    /**
     * Save template configuration via AJAX
     */
    public function saveConfiguration(Request $request, NewCertificateTemplate $template)
    {
        $request->validate([
            'fields_config' => 'required|array',
            'canvas_width' => 'required|integer|min:100|max:2000',
            'canvas_height' => 'required|integer|min:100|max:2000'
        ]);

        try {
            $template->update([
                'fields_config' => $request->fields_config,
                'canvas_width' => $request->canvas_width,
                'canvas_height' => $request->canvas_height
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Configuration saved successfully!'
            ]);

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

    /**
     * Upload background image
     */
    private function uploadBackgroundImage($image)
    {
        $filename = 'certificate_templates/' . time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();

        $image->storeAs('public/' . dirname($filename), basename($filename));

        return $filename;
    }
}
