<?php

declare(strict_types=1);

namespace App\Frontend\Controller;

use App\Frontend\Db\AboutDb;
use App\Frontend\Db\CompanyDb; // 🟢 Import de CompanyDb
use App\Frontend\Model\AboutPresenter;
use App\Component\Routing\UrlTool;
use Magepattern\Component\HTTP\Request;
use App\Frontend\Model\SeoHelper;

class AboutController extends BaseController
{
    public function run(): void
    {
        $id = Request::isGet('id') ? (int)$_GET['id'] : 0;
        $idLang = (int)($this->currentLang['id_lang'] ?? 1);
        $siteUrl = $this->view->getTemplateVars('site_url');

        $db = new AboutDb();
        $rawPage = $db->getAboutPage($id, $idLang);

        if (!$rawPage) {
            $this->render404();
            return;
        }

        // 🟢 Récupération des infos de l'entreprise
        $companyDb = new CompanyDb();
        $companyInfo = $companyDb->getCompanyInfo();

        $skinFolder = $this->siteSettings['theme']['value'] ?? 'default';

        // 1. Formatage de la page principale avec $companyInfo
        $about = AboutPresenter::format($rawPage, $this->currentLang, $siteUrl, $companyInfo, $skinFolder);

        // 2. Galerie d'images
        $about['gallery'] = [];
        $images = $db->getAboutImages($id, $idLang);
        foreach ($images as $imgRow) {
            $about['gallery'][] = AboutPresenter::format(array_merge($rawPage, $imgRow), $this->currentLang, $siteUrl, $companyInfo, $skinFolder)['img'];
        }

        // 3. Gestion de l'arborescence (Subdata & Root)
        $about['subdata'] = [];
        $about['root'] = [];

        $rawChildren = $db->getAboutChildren($id, $idLang);

        if (!empty($rawChildren)) {
            foreach ($rawChildren as $childRow) {
                $formattedChild = AboutPresenter::format($childRow, $this->currentLang, $siteUrl, $companyInfo, $skinFolder);

                if ((int)$formattedChild['id_parent'] === $id) {
                    $about['subdata'][] = $formattedChild;
                } else {
                    $about['root'][] = $formattedChild;
                }
            }
        }

        $jsonLdList = SeoHelper::generateItemListJsonLd($about['subdata']);

        // 🟢 GÉNÉRATION DU TABLEAU HREFLANG (About)
        $allLangs = $this->view->getTemplateVars('langs');
        $hreflangUrls = [];
        $urlTool = new UrlTool();

        if ($allLangs && is_array($allLangs)) {
            foreach ($allLangs as $l) {
                $lId = (int)$l['id_lang'];
                $lIso = strtolower($l['iso_lang']);

                // Requête spécifique à About
                $translatedAbout = $db->getAboutPage($id, $lId);

                if ($translatedAbout && !empty($translatedAbout['url_about'])) {
                    $hreflangUrls[$lId] = $urlTool->buildUrl([
                        'type' => 'about',
                        'id'   => $id,
                        'url'  => $translatedAbout['url_about'],
                        'iso'  => $lIso
                    ]);

                    if (isset($l['is_default']) && $l['is_default'] == 1) {
                        $this->view->assign('x_default_url', $hreflangUrls[$lId]);
                    }
                }
            }
        }

        // 4. Assignation Smarty
        $this->view->assign([
            'about'     => $about,
            'json_ld'   => $jsonLdList,
            'hreflang' => $hreflangUrls,
            'seo_title' => $about['seo']['title'],
            'seo_desc'  => $about['seo']['description']
        ]);

        $this->view->display('about/index.tpl');
    }

    private function render404(): void
    {
        header("HTTP/1.0 404 Not Found");
        $tpl404 = 'errors/404.tpl';
        if ($this->view->templateExists($tpl404)) {
            $this->view->display($tpl404);
        } else {
            die("Erreur 404 : Template de secours manquant.");
        }
    }
}