<?php

namespace Modules\VetSite\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetSite\Entities\VsSite;
use Modules\VetSite\Entities\VsPage;
use Modules\VetSite\Entities\VsMessage;
use Modules\VetSite\Http\Controllers\Concerns\HandlesUploads;
use Modules\VetSite\Http\Controllers\Site\SiteRenderController;
use Modules\VetSite\Support\ThemeRegistry;

class SiteController extends Controller
{
    use HandlesUploads;

    private function biz()
    {
        return request()->session()->get('user.business_id');
    }

    private function gate(string $perm = 'vet_site.access_module')
    {
        if (! auth()->user()->can($perm)) {
            abort(403, 'Unauthorized action.');
        }
    }

    private function site(): VsSite
    {
        return VsSite::forBusiness($this->biz());
    }

    public function dashboard()
    {
        $this->gate();
        $site = $this->site();
        $stats = [
            'pages'    => $site->pages()->count(),
            'messages' => VsMessage::where('site_id', $site->id)->count(),
            'unread'   => VsMessage::where('site_id', $site->id)->where('is_read', false)->count(),
        ];
        return view('vetSite::admin.dashboard', compact('site', 'stats'));
    }

    public function settings()
    {
        $this->gate('vet_site.manage_settings');
        $site = $this->site();
        return view('vetSite::admin.settings', compact('site'));
    }

    public function saveSettings(Request $request)
    {
        $this->gate('vet_site.manage_settings');
        $request->validate([
            'name'    => 'nullable|string|max:150',
            'tagline' => 'nullable|string|max:200',
        ]);

        $site = $this->site();
        $biz  = $this->biz();

        $data = [
            'enabled'         => $request->boolean('enabled'),
            'status'          => $request->input('status') === 'published' ? 'published' : 'draft',
            'name'            => $request->name,
            'tagline'         => $request->tagline,
            'seo_title'       => $request->seo_title,
            'seo_description' => $request->seo_description,
            'analytics_id'    => $request->analytics_id,
            'contact'         => [
                'phone'    => $request->input('contact.phone'),
                'whatsapp' => $request->input('contact.whatsapp'),
                'email'    => $request->input('contact.email'),
                'address'  => $request->input('contact.address'),
            ],
            'social'          => array_filter([
                'facebook'  => $request->input('social.facebook'),
                'instagram' => $request->input('social.instagram'),
                'twitter'   => $request->input('social.twitter'),
                'tiktok'    => $request->input('social.tiktok'),
                'youtube'   => $request->input('social.youtube'),
                'linkedin'  => $request->input('social.linkedin'),
            ]),
            'options'         => array_merge((array) $site->options, [
                'cta_label'        => $request->input('cta_label') ?: 'Book appointment',
                'cta_url'          => $request->input('cta_url') ?: '#contact',
                'show_portal_link' => $request->boolean('show_portal_link') ? '1' : '0',
            ]),
        ];

        // Opening hours rows
        $hours = [];
        foreach ((array) $request->input('hours_day', []) as $i => $day) {
            $time = $request->input('hours_time.' . $i);
            if ($day || $time) {
                $hours[] = ['day' => $day, 'time' => $time];
            }
        }
        $data['hours'] = $hours;

        foreach (['logo' => 'logo_path', 'favicon' => 'favicon_path', 'og_image' => 'og_image_path'] as $field => $col) {
            if ($request->hasFile($field) && ($path = $this->storeUpload($request->file($field), $biz, $field))) {
                $data[$col] = $path;
            }
        }

        $site->update($data);

        return redirect()->route('vs.settings')->with('status', ['success' => 1, 'msg' => __('vetSite::lang.saved')]);
    }

    public function navigation()
    {
        $this->gate('vet_site.manage_content');
        $site  = $this->site();
        $pages = $site->pages()->orderBy('sort')->get();
        return view('vetSite::admin.navigation', compact('site', 'pages'));
    }

    public function saveNavigation(Request $request)
    {
        $this->gate('vet_site.manage_content');
        $site = $this->site();

        foreach ((array) $request->input('order', []) as $sort => $pageId) {
            VsPage::where('id', $pageId)->where('site_id', $site->id)->update([
                'sort'        => $sort,
                'show_in_nav' => in_array($pageId, (array) $request->input('show_in_nav', [])),
            ]);
        }

        return redirect()->route('vs.navigation')->with('status', ['success' => 1, 'msg' => __('vetSite::lang.saved')]);
    }

    /** Host-independent live preview (also used by the CMS "Preview" buttons). */
    public function preview(Request $request, $pageId = null)
    {
        $this->gate();
        $site = $this->site();

        $page = $pageId
            ? $site->pages()->findOrFail($pageId)
            : $site->homePage();

        if (! $page) {
            return redirect()->route('vs.pages')->with('status', ['success' => 0, 'msg' => 'Create a page first.']);
        }

        // Allow previewing another theme without applying it.
        $tp = $request->input('theme_preview');
        if ($tp && ThemeRegistry::exists($tp)) {
            $site->setAttribute('theme', $tp);
        }

        $request->merge(['preview' => 1]);
        return app(SiteRenderController::class)->renderPage($request, $site, $page);
    }
}
