<?php

namespace App\Http\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\GalleryAlbum;
use App\Models\GalleryImage;
use App\Models\Menu;

class GalleryController extends Controller
{
    public function index(Request $request, array $params = []): void
    {
        $albums = GalleryAlbum::visible();

        $this->renderFrontend('gallery', [
            'page_title'    => 'Gallery',
            'seo_title'     => 'Gallery – ' . setting('site_name'),
            'canonical_url' => base_url('/gallery'),
            'breadcrumbs'   => [
                ['label' => 'Home',    'url' => '/'],
                ['label' => 'Gallery', 'url' => null],
            ],
            'albums'        => $albums,
            'current_uri'   => '/gallery',
        ]);
    }

    public function album(Request $request, array $params = []): void
    {
        $slug  = $params['slug'] ?? '';
        $album = GalleryAlbum::findBySlug($slug);

        if (!$album || !$album['is_visible']) {
            http_response_code(404);
            $this->renderFrontend('404', ['current_uri' => $request->uri()]);
            return;
        }

        $images = GalleryImage::byAlbum($album['id']);

        // OG image: use album cover if available
        $ogImage = '';
        if (!empty($album['cover_image'])) {
            $webpUrl = webp_url($album['cover_image']);
            $ogImage = base_url($webpUrl ?? ('/uploads/' . $album['cover_image']));
        }

        $this->renderFrontend('gallery-album', [
            'album'           => $album,
            'images'          => $images,
            'page_title'      => $album['title'],
            'seo_title'       => $album['title'] . ' – Gallery – ' . setting('site_name'),
            'seo_description' => $album['description'] ?? '',
            'canonical_url'   => base_url('/gallery/' . $slug),
            'og_image'        => $ogImage,
            'breadcrumbs'     => [
                ['label' => 'Home',          'url' => '/'],
                ['label' => 'Gallery',       'url' => '/gallery'],
                ['label' => $album['title'], 'url' => null],
            ],
            'current_uri'     => '/gallery/' . $slug,
        ]);
    }

    private function renderFrontend(string $template, array $data = []): void
    {
        $data['main_menu']   = Menu::getItems('main');
        $data['footer_menu'] = Menu::getItems('footer');

        $view = $this->app->service('view');
        $html = $view->render($template, $data);
        Response::html($html);
    }
}
