<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Hash;
use App\Models\Event;                // ✅ modelo correcto
use App\Models\EventImage; 
use Illuminate\Http\Request;

class PreviewController extends Controller
{
    public function form(string $slug)
    {
        $event = Event::where('slug',$slug)->firstOrFail();

        // ya autenticado por sesión
        if ($this->hasPreviewAccess($event)) {
            return redirect()->route('preview.show', $event->slug);
        }

        abort_unless($event->is_preview_enabled, 403);
        return view('preview.form', compact('event'));
    }

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

        abort_unless($event->is_preview_enabled, 403);

        $data = $request->validate([
            'code' => ['required','string','min:4','max:20']
        ]);

        if ($event->preview_code_hash && Hash::check($data['code'], $event->preview_code_hash)) {
            session(['preview_ok_'.$event->id => true]);
            return redirect()->route('preview.show', $event->slug);
        }

        return back()->withErrors(['code' => 'Código incorrecto']);
    }

   public function show(string $slug)
    {
        $event = \App\Models\Event::with(['images' => function ($q) {
            $q->orderBy('order')->orderBy('id');
        }])->where('slug', $slug)->firstOrFail();

        if (!session('preview_ok_' . $event->id)) {
            return redirect()->route('preview.form', $event->slug)
                ->withErrors(['code' => 'Debes ingresar el código para acceder.']);
        }

        return view('preview.show', compact('event'));
    }


    protected function hasPreviewAccess(Event $event): bool
    {
        return session('preview_ok_'.$event->id, false) === true;
    }
}
