<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CertificateTemplate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
// use Intervention\Image\Facades\Image; // Temporarily disabled

class CertificateTemplateController extends Controller
{
    public function index()
    {
        $templates = CertificateTemplate::orderBy('created_at', 'desc')->paginate(10);
        return view('admin.certificates.templates.index', compact('templates'));
    }

    public function create()
    {
        return view('admin.certificates.templates.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'background_image' => 'required|image|mimes:jpg,jpeg,png|max:2048',
            'name_x' => 'required|integer|min:0',
            'name_y' => 'required|integer|min:0',
            'date_x' => 'required|integer|min:0',
            'date_y' => 'required|integer|min:0',
            'serial_x' => 'required|integer|min:0',
            'serial_y' => 'required|integer|min:0',
        ]);

        $path = null;
        if ($request->hasFile('background_image')) {
            $image = $request->file('background_image');
            $filename = time() . '_' . $image->getClientOriginalName();
            $path = $image->storeAs('certificate-templates', $filename, 'graduation-certificates');

            \Log::info('Image uploaded to path: ' . $path);
            \Log::info('Full storage path: ' . storage_path('app/public/' . $path));

            // Temporarily disable image optimization to test basic upload
            \Log::info('Image uploaded successfully to: ' . $path);
            \Log::info('Full path: ' . storage_path('app/public/' . $path));

            // Check if file exists
            $imagePath = storage_path('app/public/' . $path);
            if (file_exists($imagePath)) {
                \Log::info('Image file exists at: ' . $imagePath);
                \Log::info('File size: ' . filesize($imagePath));
            } else {
                \Log::error('Image file does not exist at: ' . $imagePath);
            }
        } else {
            \Log::warning('No background image file found in request');
        }

        try {
            \Log::info('Creating template with image_path: ' . $path);
            $template = CertificateTemplate::create([
                'name' => $request->name,
                'image_path' => $path,
                'name_x' => $request->name_x,
                'name_y' => $request->name_y,
                'date_x' => $request->date_x,
                'date_y' => $request->date_y,
                'serial_x' => $request->serial_x,
                'serial_y' => $request->serial_y,
            ]);
            \Log::info('Template created successfully with ID: ' . $template->id);
        } catch (\Exception $e) {
            \Log::error('Failed to create template: ' . $e->getMessage());
            // If template creation fails, delete the uploaded image and show error
            if ($path) {
                Storage::disk('graduation-certificates')->delete($path);
            }
            throw $e;
        }

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

    public function edit(CertificateTemplate $template)
    {
        return view('admin.certificates.templates.edit', compact('template'));
    }

    public function update(Request $request, CertificateTemplate $template)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'background_image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
            'name_x' => 'required|integer|min:0',
            'name_y' => 'required|integer|min:0',
            'date_x' => 'required|integer|min:0',
            'date_y' => 'required|integer|min:0',
            'serial_x' => 'required|integer|min:0',
            'serial_y' => 'required|integer|min:0',
        ]);

        $data = [
            'name' => $request->name,
            'name_x' => $request->name_x,
            'name_y' => $request->name_y,
            'date_x' => $request->date_x,
            'date_y' => $request->date_y,
            'serial_x' => $request->serial_x,
            'serial_y' => $request->serial_y,
        ];

        if ($request->hasFile('background_image')) {
            // Delete old image
            if ($template->image_path) {
                Storage::disk('graduation-certificates')->delete($template->image_path);
            }

            $image = $request->file('background_image');
            $filename = time() . '_' . $image->getClientOriginalName();
            $path = $image->storeAs('certificate-templates', $filename, 'graduation-certificates');

            // Temporarily disable image optimization to test basic upload
            \Log::info('Image updated successfully to: ' . $path);
            \Log::info('Full path: ' . storage_path('app/public/' . $path));

            // Check if file exists
            $imagePath = storage_path('app/public/' . $path);
            if (file_exists($imagePath)) {
                \Log::info('Image file exists at: ' . $imagePath);
                \Log::info('File size: ' . filesize($imagePath));
            } else {
                \Log::error('Image file does not exist at: ' . $imagePath);
            }

            $data['image_path'] = $path;
        }

        $template->update($data);

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

    public function destroy(CertificateTemplate $template)
    {
        // Check if template is being used
        if ($template->certificates()->count() > 0) {
                    return redirect()->route('admin.graduation-certificates.templates.index')
            ->with('error', 'Cannot delete template that is being used by certificates.');
        }

        // Delete image
        if ($template->image_path) {
            Storage::disk('graduation-certificates')->delete($template->image_path);
        }

        $template->delete();

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