<?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 Intervention\Image\Facades\Image;

class NewCertificatesTemplatesController extends Controller
{
    public function index()
    {
        $this->authorize('admin_certificate_template_list');

        $templates = NewCertificateTemplate::orderBy('created_at', 'desc')->paginate(10);

        $data = [
            'pageTitle' => 'New Certificates Templates',
            'templates' => $templates,
        ];

        return view('admin.certificates.new_templates.index', $data);
    }

    public function create()
    {
        $this->authorize('admin_certificate_template_create');

        $data = [
            'pageTitle' => 'Create New Certificate Template',
            'defaultImagePath' => asset('certificates/dummy.png'),
        ];

        return view('admin.certificates.new_templates.create', $data);
    }

    public function store(Request $request)
    {
        $this->authorize('admin_certificate_template_create');

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

        $path = null;
        if ($request->hasFile('background_image')) {
            $file = $request->file('background_image');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $path = $file->storeAs('public/certificate_templates', $fileName);
        }

        NewCertificateTemplate::create([
            'name' => $request->name,
            'description' => $request->description,
            'background_image_path' => $path,
            '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(),
            'is_active' => true
        ]);

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

    public function show($id)
    {
        $this->authorize('admin_certificate_template_list');

        $template = NewCertificateTemplate::findOrFail($id);

        $data = [
            'pageTitle' => 'View Certificate Template',
            'template' => $template,
        ];

        return view('admin.certificates.new_templates.show', $data);
    }

    public function edit($id)
    {
        $this->authorize('admin_certificate_template_create');

        $template = NewCertificateTemplate::findOrFail($id);

        $data = [
            'pageTitle' => 'Edit Certificate Template',
            'template' => $template,
        ];

        return view('admin.certificates.new_templates.edit', $data);
    }

    public function update(Request $request, $id)
    {
        $this->authorize('admin_certificate_template_create');

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

        $template = NewCertificateTemplate::findOrFail($id);

        $path = $template->background_image_path;
        if ($request->hasFile('background_image')) {
            // Delete old image
            if ($template->background_image_path) {
                Storage::delete($template->background_image_path);
            }

            $file = $request->file('background_image');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $path = $file->storeAs('public/certificate_templates', $fileName);
        }

        $template->update([
            'name' => $request->name,
            'description' => $request->description,
            'background_image_path' => $path,
            'background_image_name' => $request->hasFile('background_image') ? $request->file('background_image')->getClientOriginalName() : $template->background_image_name,
            'canvas_width' => $request->canvas_width,
            'canvas_height' => $request->canvas_height,
            'fields_config' => $request->fields_config ?? $template->fields_config
        ]);

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

    public function destroy($id)
    {
        $this->authorize('admin_certificate_template_create');

        $template = NewCertificateTemplate::findOrFail($id);

        // Delete image file
        if ($template->background_image_path) {
            Storage::delete($template->background_image_path);
        }

        $template->delete();

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