<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Poster;
use Illuminate\Http\Request;

class PosterController extends Controller
{
    public function index()
    {
        $posters = Poster::latest()->paginate(10);
        return view('admin.posters.index', compact('posters'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'file_path' => 'nullable|string',
            'preview_image' => 'nullable|string',
        ]);

        if (!empty($validated['preview_image'])) {
            $originalPreviewInput = $validated['preview_image'];
            $extracted = \App\Helpers\UrlImageExtractor::extract($originalPreviewInput);

            if (empty($validated['file_path']) && filter_var($originalPreviewInput, FILTER_VALIDATE_URL)) {
                if ($extracted !== $originalPreviewInput || empty($extracted)) {
                    $validated['file_path'] = $originalPreviewInput;
                }
            }

            $validated['preview_image'] = $extracted;
        }

        if (empty($validated['preview_image'])) {
            $validated['preview_image'] = \App\Helpers\UrlImageExtractor::getThemeImage($validated['title'], 'poster');
        }
        if (empty($validated['file_path'])) {
            $validated['file_path'] = 'posters/poster_default.pdf';
        }

        Poster::create($validated);

        return redirect()->route('admin.posters.index')->with('success', 'Poster edukasi berhasil ditambahkan!');
    }

    public function destroy(Poster $poster)
    {
        $poster->delete();
        return redirect()->route('admin.posters.index')->with('success', 'Poster berhasil dihapus.');
    }
}
