<?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;
use App\Models\Page;

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

        // Load associated page record for editable intro content, show_title, SEO
        $page = Page::findByType('gallery');
        if (!$page) {
            $page = Page::findBySlug('gallery');
        }
        $pageTitle = ($page['title'] ?? '') ?: __('theme.gallery_title');

        $this->renderFrontend('gallery', [
            'system_page'   => $page ?: ['title' => __('theme.gallery_title'), 'content' => '', 'show_title' => 1],
            'page_title'    => $pageTitle,
            'seo_title'     => ($page['seo_title'] ?? '') ?: $pageTitle . ' – ' . setting('site_name'),
            'seo_description' => $page['seo_description'] ?? '',
            'canonical_url' => base_url('/gallery'),
            'breadcrumbs'   => [
                ['label' => 'Home',      'url' => '/'],
                ['label' => $pageTitle,  'url' => null],
            ],
            'albums'        => $albums,
            'current_uri'   => '/gallery',
        ]);
    }

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

        // Fallback: normalise the URL slug (e.g. "meisterstück" → "meisterstueck")
        // and try again. If found, 301-redirect to the canonical slug URL so that
        // bookmarks and search engines converge on a single URL.
        if (!$album) {
            $normalised = slugify(urldecode($slug));
            if ($normalised !== '' && $normalised !== $slug) {
                $album = GalleryAlbum::findBySlug($normalised);
                if ($album && $album['is_visible']) {
                    Response::redirect('/gallery/' . $normalised, 301);
                    return;
                }
            }
        }

        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['main_menu_tree'] = Menu::getItemsTree('main');
        $data['footer_menu']    = Menu::getItems('footer');

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