<?php

namespace App\Http\Controllers;

use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

class DraftPreviewController extends Controller
{
    /**
     * Show the page preview using draft data from cache (no save required).
     */
    public function show(Request $request, string $token): View
    {
        $key = 'page_draft_preview_' . $token;
        $data = Cache::store('file')->get($key);

        if (! $data || ! is_array($data)) {
            abort(404, 'معاينة المسودة منتهية أو غير موجودة.');
        }

        $page = $this->makePageFromDraft($data);

        return view('pages.show', compact('page'));
    }

    /**
     * Show draft preview for current user + page.
     * Falls back to the saved page when draft cache is not available yet.
     */
    public function showForPage(Request $request, Page $page): View
    {
        $userId = (int) ($request->user()?->id ?? auth()->id() ?? 1);
        $key = 'page_draft_preview_user_' . $userId . '_page_' . $page->getKey();
        $data = Cache::store('file')->get($key);

        if (is_array($data) && ! empty($data['locale'])) {
            app()->setLocale($data['locale']);
        }

        file_put_contents('/tmp/preview_debug.log', "--- RETRIEVED BY CONTROLLER ---\n" . json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);

        $previewPage = is_array($data) ? $this->makePageFromDraft($data) : $page;

        return view('pages.show', ['page' => $previewPage]);
    }

    private function makePageFromDraft(array $data): Page
    {
        $page = new Page();
        $page->exists = false;
        $locale = $data['locale'] ?? app()->getLocale();

        $page->setTranslation('title', $locale, $data['title'] ?? '');
        $page->slug = $data['slug'] ?? 'preview';
        if (isset($data['meta_title'])) $page->setTranslation('meta_title', $locale, $data['meta_title']);
        if (isset($data['meta_description'])) $page->setTranslation('meta_description', $locale, $data['meta_description']);
        $page->meta_keywords = $data['meta_keywords'] ?? null;
        $page->setTranslation('content', $locale, $data['content'] ?? []);
        if (isset($data['custom_html'])) $page->setTranslation('custom_html', $locale, $data['custom_html']);

        $page->is_published = true; // so the view renders normally

        return $page;
    }
}
