<?php
namespace App\Controllers;

use App\Core\{Lang, Session};
use App\Models\Page;
use App\Services\Translate\ZaloroxTranslateBot;
use Throwable;

class PageController extends BaseController
{
    public function show(string $slug): string
    {
        return $this->showForLanguage($slug, Lang::current());
    }

    public function showLocalized(string $lang, string $slug): string
    {
        return $this->showForLanguage($slug, $lang);
    }

    private function showForLanguage(string $slug, string $language): string
    {
        if (in_array($language, $this->config['supported_languages'] ?? ['tr', 'en', 'de', 'fr'], true)) {
            Session::put('lang', $language);
        }

        try {
            $page = (new Page())->findPublishedBySlug($slug, $language);
            if (!$page) {
                http_response_code(404);

                return $this->view('main', 'pages/show', [
                    'title' => 'Sayfa bulunamadi',
                    'page' => [
                        'title' => 'Sayfa bulunamadi',
                        'content' => 'Aradiginiz sayfa yayinda degil veya kaldirilmis.',
                    ],
                ]);
            }
            $translationNote = null;
            if ($language !== 'tr' && (string) ($page['language'] ?? 'tr') !== $language) {
                $translation = (new ZaloroxTranslateBot($this->config))->translationFor('page', (int) ($page['id'] ?? 0), $language);
                if ($translation) {
                    $page['title'] = $translation['title'] ?: $page['title'];
                    $page['content'] = $translation['body'] ?: ($translation['description'] ?: $page['content']);
                    $page['language'] = $language;
                } else {
                    $translationNote = 'Ceviri hazirlaniyor; simdilik Turkce orijinal icerik gosteriliyor.';
                }
            }

            return $this->view('main', 'pages/show', [
                'title' => $page['seo_title'] ?: $page['title'],
                'page' => $page,
                'translationNote' => $translationNote,
                'contentLanguage' => $language,
            ]);
        } catch (Throwable $exception) {
            $this->logException($exception, 'page.show');
            http_response_code(500);

            return $this->view('main', 'pages/show', [
                'title' => 'Sayfa yuklenemedi',
                'page' => [
                    'title' => 'Sayfa yuklenemedi',
                    'content' => 'Sayfa su anda goruntulenemiyor.',
                ],
            ]);
        }
    }
}
