<?php

namespace Modules\ClinicSite\Http\Controllers\Site;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\View;
use Modules\ClinicSite\Entities\CsPage;
use Modules\ClinicSite\Entities\CsSite;
use Modules\ClinicSite\Entities\CsMessage;
use Modules\ClinicSite\Support\ThemeRegistry;

class SiteRenderController extends Controller
{
    /** Mini front-controller invoked by ResolveTenantSite for tenant hosts. */
    public function dispatch(Request $request, CsSite $site)
    {
        $path = trim($request->path(), '/'); // '' for home

        if ($request->isMethod('post') && $path === 'contact') {
            return $this->submitContact($request, $site);
        }

        if ($path === 'sitemap.xml') {
            return $this->sitemap($site);
        }

        if ($path === '' || $path === '/') {
            $page = $site->homePage();
        } else {
            $page = $site->pages()->where('slug', $path)->where('status', 'published')->first();
        }

        if (! $page) {
            return response()->view('clinicSite::site.not_found', ['site' => $site], 404);
        }

        return $this->renderPage($request, $site, $page);
    }

    /** Render a page through the active theme (used by tenant + admin preview). */
    public function renderPage(Request $request, CsSite $site, CsPage $page)
    {
        $theme = ThemeRegistry::exists($site->theme) ? $site->theme : 'aurora';
        $view  = 'clinicSite::themes.' . $theme . '.layout';

        // Defensive: a half-built theme falls back to aurora so a clinic is
        // never left with a blank page after switching themes.
        if (! View::exists($view)) {
            $theme = 'aurora';
            $view  = 'clinicSite::themes.aurora.layout';
        }

        return response()->view($view, [
            'site'     => $site,
            'page'     => $page,
            'theme'    => $theme,
            'blocks'   => $page->orderedBlocks(),
            'palette'  => $site->palette(),
            'fonts'    => $site->fonts(),
            'navPages' => $site->navPages(),
            'preview'  => $request->boolean('preview'),
            'sent'     => $request->boolean('sent'),
        ]);
    }

    protected function submitContact(Request $request, CsSite $site)
    {
        // Honeypot: bots fill hidden fields humans never see.
        if ($request->filled('company')) {
            return redirect('/' . ltrim($request->input('return', 'contact'), '/'));
        }

        $data = $request->validate([
            'name'    => 'required|string|max:150',
            'email'   => 'nullable|email|max:180',
            'phone'   => 'nullable|string|max:40',
            'subject' => 'nullable|string|max:200',
            'message' => 'nullable|string|max:5000',
        ]);

        CsMessage::create([
            'business_id' => $site->business_id,
            'site_id'     => $site->id,
            'name'        => $data['name'],
            'email'       => $data['email'] ?? null,
            'phone'       => $data['phone'] ?? null,
            'subject'     => $data['subject'] ?? null,
            'message'     => $data['message'] ?? null,
            'source'      => 'contact_form',
            'ip'          => $request->ip(),
        ]);

        $return = ltrim((string) $request->input('return', ''), '/');
        return redirect('/' . $return . ($return ? '?' : '?') . 'sent=1#contact');
    }

    protected function sitemap(CsSite $site)
    {
        $base = request()->getSchemeAndHttpHost();
        $urls = [$base . '/'];
        foreach ($site->navPages() as $p) {
            if (! $p->is_home) {
                $urls[] = $base . '/' . $p->slug;
            }
        }

        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        foreach ($urls as $u) {
            $xml .= '  <url><loc>' . htmlspecialchars($u) . '</loc></url>' . "\n";
        }
        $xml .= '</urlset>';

        return response($xml, 200, ['Content-Type' => 'application/xml']);
    }
}
