<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Page;
use App\Models\BlogPost;
use App\Models\BlogTag;
use App\Models\Menu;

/**
 * ITSWEBER CMS – Draft Preview Controller
 *
 * Renders pages and blog posts using the frontend theme templates,
 * regardless of their publish status. Access is restricted to
 * authenticated admin/editor users via AuthMiddleware.
 *
 * No public routes, no tokens, no DB changes required.
 */
class PreviewController extends Controller
{
    // -------------------------------------------------------------------------
    // PAGE PREVIEW
    // -------------------------------------------------------------------------

    public function previewPage(Request $request, array $params = []): void
    {
        $id   = (int) ($params['id'] ?? 0);
        $page = Page::find($id);

        if (!$page) {
            set_flash('error', __('messages.not_found', ['item' => 'Page']));
            Response::redirect('/admin/pages');
            return;
        }

        // Normalize legacy template name 'default' → 'page'
        $template = $page['template'] ?: 'page';
        if ($template === 'default') {
            $template = 'page';
        }

        $slug = $page['slug'] ?: 'preview';

        $this->renderPreview($template, [
            'page'            => $page,
            'page_title'      => $page['title'],
            'seo_title'       => $page['seo_title'] ?: $page['title'] . ' – ' . setting('site_name'),
            'seo_description' => $page['seo_description'] ?? '',
            'canonical_url'   => '',  // No canonical for preview
            'breadcrumbs'     => [
                ['label' => 'Home', 'url' => '/'],
                ['label' => $page['title'], 'url' => null],
            ],
            'current_uri'     => '/' . $slug,
            '_preview_mode'   => true,
            '_preview_type'   => 'page',
            '_preview_status' => $page['status'],
            '_preview_edit_url' => '/admin/pages/edit/' . $id,
        ]);
    }

    // -------------------------------------------------------------------------
    // BLOG POST PREVIEW
    // -------------------------------------------------------------------------

    public function previewBlog(Request $request, array $params = []): void
    {
        $id   = (int) ($params['id'] ?? 0);
        $post = BlogPost::findByIdWithDetails($id);

        if (!$post) {
            set_flash('error', __('messages.not_found', ['item' => 'Post']));
            Response::redirect('/admin/blog');
            return;
        }

        // Load tags for display (same pattern as frontend)
        $tags = BlogTag::findByPost($id);
        $post['tags'] = $tags;

        // OG image: use featured image if available
        $ogImage = '';
        if (!empty($post['featured_image'])) {
            $webpUrl = function_exists('webp_url') ? webp_url($post['featured_image']) : null;
            $ogImage = base_url($webpUrl ?? ('/uploads/' . $post['featured_image']));
        }

        $slug = $post['slug'] ?: 'preview';

        $this->renderPreview('blog-single', [
            'post'            => $post,
            'page_title'      => $post['title'],
            'seo_title'       => $post['seo_title'] ?: $post['title'] . ' – ' . setting('site_name'),
            'seo_description' => $post['seo_description'] ?? $post['excerpt'] ?? '',
            'canonical_url'   => '',  // No canonical for preview
            'og_type'         => 'article',
            'og_image'        => $ogImage,
            'breadcrumbs'     => [
                ['label' => 'Home',          'url' => '/'],
                ['label' => 'Blog',          'url' => '/blog'],
                ['label' => $post['title'],  'url' => null],
            ],
            'current_uri'     => '/blog/' . $slug,
            '_preview_mode'   => true,
            '_preview_type'   => 'blog',
            '_preview_status' => $post['status'],
            '_preview_edit_url' => '/admin/blog/edit/' . $id,
        ]);
    }

    // -------------------------------------------------------------------------
    // RENDER HELPER
    // -------------------------------------------------------------------------

    /**
     * Render a frontend template with shared layout data and a preview banner.
     *
     * Uses the same View::render() path as the public frontend controllers,
     * ensuring the preview looks identical to the live page.
     */
    private function renderPreview(string $template, array $data = []): void
    {
        // Load menu data (same as frontend controllers)
        $data['main_menu']   = Menu::getItems('main');
        $data['footer_menu'] = Menu::getItems('footer');

        $view = $this->app->service('view');
        $html = $view->render($template, $data);

        // Inject preview banner right after <body> tag
        $banner = $this->buildPreviewBanner(
            $data['_preview_type'] ?? 'page',
            $data['_preview_status'] ?? 'draft',
            $data['_preview_edit_url'] ?? '/admin'
        );

        // Insert banner after <body...>
        $html = preg_replace(
            '/(<body[^>]*>)/i',
            '$1' . $banner,
            $html,
            1
        );

        Response::html($html);
    }

    /**
     * Build the HTML for the preview banner.
     */
    private function buildPreviewBanner(string $type, string $status, string $editUrl): string
    {
        $typeLabel   = $type === 'blog' ? __('admin.preview.type_blog') : __('admin.preview.type_page');
        $statusLabel = $status === 'published' ? __('admin.common.published') : __('admin.common.draft');
        $statusClass = $status === 'published' ? 'iw-preview-status--published' : 'iw-preview-status--draft';
        $bannerText  = __('admin.preview.banner_text', [':type' => $typeLabel, ':status' => $statusLabel]);
        $editText    = __('admin.preview.back_to_editor');
        $closeText   = __('admin.preview.close');

        return <<<HTML

<!-- ITSWEBER CMS Preview Banner -->
<div id="iwPreviewBanner" style="
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 999999;
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    color: #fff;
    padding: 10px 20px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    flex-wrap: wrap;
">
    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
        <span style="
            display: inline-block;
            background: #e74c3c;
            color: #fff;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        ">{$typeLabel}</span>
        <span style="opacity:0.9;">{$bannerText}</span>
        <span class="{$statusClass}" style="
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            background: {$this->statusBg($status)};
            color: #fff;
        ">{$statusLabel}</span>
    </div>
    <div style="display:flex;align-items:center;gap:8px;flex-shrink:0;">
        <a href="{$editUrl}" style="
            color: #fff;
            background: rgba(255,255,255,0.15);
            padding: 5px 14px;
            border-radius: 4px;
            text-decoration: none;
            font-size: 13px;
            transition: background 0.2s;
        " onmouseover="this.style.background='rgba(255,255,255,0.25)'"
           onmouseout="this.style.background='rgba(255,255,255,0.15)'"
        >{$editText}</a>
        <button onclick="document.getElementById('iwPreviewBanner').style.display='none';document.body.style.paddingTop='0';" style="
            background: none;
            border: 1px solid rgba(255,255,255,0.3);
            color: rgba(255,255,255,0.7);
            padding: 4px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        ">{$closeText}</button>
    </div>
</div>
<script>
(function(){
    // Push page content down so banner doesn't overlap
    var b = document.getElementById('iwPreviewBanner');
    if (b) {
        var h = b.offsetHeight;
        document.body.style.paddingTop = h + 'px';
        // Recalculate on resize
        window.addEventListener('resize', function() {
            document.body.style.paddingTop = b.offsetHeight + 'px';
        });
    }
})();
</script>
<!-- /ITSWEBER CMS Preview Banner -->

HTML;
    }

    /**
     * Get status badge background color.
     */
    private function statusBg(string $status): string
    {
        return $status === 'published' ? '#27ae60' : '#e67e22';
    }
}
