<?php
declare(strict_types=1);

namespace App\Controllers;

use App\I18n;
use App\Repositories\Container;

class PublicController
{
    public function home(): void
    {
        $artists = Container::artists()->all(true);
        $gallery = array_slice(Container::gallery()->all(), 0, 8);
        $settings = Container::settings()->get();
        render('public', 'public.home', compact('artists', 'gallery', 'settings'), t('page.home.title'));
    }

    public function about(): void
    {
        $settings = Container::settings()->get();
        render('public', 'public.about', compact('settings'), t('page.about.title'));
    }

    public function artists(): void
    {
        $artists = Container::artists()->all(true);
        render('public', 'public.artists', compact('artists'), t('page.artists.title'));
    }

    public function artistDetail(array $params): void
    {
        $artist = Container::artists()->findBySlug($params['slug'] ?? '');
        if (!$artist) { http_response_code(404); require MAT_ROOT . '/src/Views/errors/404.php'; return; }
        $gallery = Container::gallery()->all(['artist_id' => $artist['id']]);
        render('public', 'public.artist-detail', compact('artist', 'gallery'), $artist['display_name'] ?? '');
    }

    public function portfolio(): void
    {
        $gallery = Container::gallery()->all();
        $artists = Container::artists()->all(true);
        $activeArtist = $_GET['artist'] ?? '';
        if ($activeArtist) {
            $gallery = array_values(array_filter($gallery, fn($g) => ($g['artist_id'] ?? '') === $activeArtist));
        }
        render('public', 'public.portfolio', compact('gallery', 'artists', 'activeArtist'), t('page.portfolio.title'));
    }

    public function aftercare(): void
    {
        render('public', 'public.aftercare', [], t('page.aftercare.title'));
    }

    public function contact(): void
    {
        $settings = Container::settings()->get();
        render('public', 'public.contact', compact('settings'), t('page.contact.title'));
    }

    public function contactSubmit(): void
    {
        \App\Csrf::requireValid();
        // For MVP, just flash and redirect. Could email info@ via Services\Email later.
        $_SESSION['_flash']['success'] = t('page.contact.sent');
        redirect('/contact');
    }

    public function faq(): void
    {
        render('public', 'public.faq', [], t('page.faq.title'));
    }

    public function setLang(array $params): void
    {
        $code = $params['code'] ?? 'en';
        I18n::set($code);
        $back = $_SERVER['HTTP_REFERER'] ?? '/';
        $parts = parse_url($back);
        $path = ($parts['path'] ?? '/') . (isset($parts['query']) ? '?' . $parts['query'] : '');
        redirect($path ?: '/');
    }
}
