<?php

namespace App\Http\Controllers;

use App\Models\Event;
use App\Models\EventRegistration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
// Use the v3 Facade
use Intervention\Image\Laravel\Facades\Image; 

class EventPublicController extends Controller
{
    public function show(string $slug)
    {
        $event = Event::where('share_slug', $slug)->with('admin')->firstOrFail();
        if ($event->status == 0) {
            abort('404');  
        }
        return view('events.show', compact('event'));
    }

    public function register(Request $request, string $slug)
    {
        $event = Event::where('share_slug', $slug)->firstOrFail();

        $data = $request->validate([
            'first_name'       => 'required|string|max:255',
            'last_name'        => 'required|string|max:255',
            'institution_name' => 'nullable|string|max:255',
            'email'            => 'required|email',
            'mobile_no'            => 'nullable|string',
            'cropped_image'    => 'required|string', 
        ]);

        // 1. Decode and Save the Base64 Image (Already Circular if selected)
        $image_parts = explode(";base64,", $request->cropped_image);
        $image_base64 = base64_decode($image_parts[1]);
        
        $fileName = uniqid() . '.png';
        $userPhotoRelativePath = 'user_photos/' . $fileName;
        
        // Save raw PNG to storage
        Storage::disk('public')->put($userPhotoRelativePath, $image_base64);

        // 2. Generate Final Image
        $finalPath = $this->generateFinalImage($event, $userPhotoRelativePath, $data['first_name'] . ' ' . $data['last_name'], $data['institution_name'] ?? null);

        // 3. Store Record
        EventRegistration::create([
            'event_id'           => $event->id,
            'first_name'         => $data['first_name'],
            'last_name'          => $data['last_name'],
            'institution_name'   => $data['institution_name'] ?? null,
            'email'              => $data['email'],
            'mobile_no'              => $data['mobile_no'] ?? null,
            'uploaded_photo_path'=> $userPhotoRelativePath,
            'final_image_path'   => $finalPath,
        ]);

        return response()->download(Storage::disk('public')->path($finalPath));
    }

    protected function generateFinalImage(Event $event, string $userPhotoPath, string $fullName, string $institutionName = null): string
    {
        // 1. Read Banner
        $bannerPath = public_path('uploads/banner_image/' . $event->banner_image_path);
        $banner = Image::read($bannerPath);

        // 2. Read User Photo (Already Circular PNG)
        $userImgPath = Storage::disk('public')->path($userPhotoPath);
        $userImg = Image::read($userImgPath);

        // 3. Resize User Photo (Just to be safe on dimensions)
        $userImg->resize(
            $event->photo_width ?? 232,
            $event->photo_height ?? 232
        );

        // 4. Place Photo (No masking needed!)
        $banner->place(
            $userImg,
            'top-left',
            $event->photo_x ?? 0,
            $event->photo_y ?? 0
        );

        // 5. Write Text
        $banner->text(
            $fullName,
            $event->name_x ?? 0,
            $event->name_y ?? 0,
            function ($font) use ($event) {
                $font->file(public_path('fonts/Roboto-Regular.ttf'));
                $font->size(36);
                $font->color($event->name_color ?? '#ffffff');
                $font->align('left');
                $font->valign('top');
            }
        );

        if (!empty($institutionName)) {
            // Offset Y by approx 45 pixels (adjust based on font size)
            $secondLineY = ($event->name_y ?? 0) + 35; 
            
            $banner->text(
                $institutionName,
                $event->name_x ?? 0,
                $secondLineY, 
                function ($font) use ($event) {
                    $font->file(public_path('fonts/Roboto-Regular.ttf'));
                    $font->size(24); // Smaller size for institution
                    $font->color($event->name_color ?? '#ffffff');
                    $font->align('left');
                    $font->valign('top');
                }
            );
        }

        // 6. Save
        $finalName = 'final/' . uniqid('event_pass_') . '.png';
        Storage::disk('public')->put($finalName, $banner->toPng());

        return $finalName;
    }
}
