<?php

namespace App\Http\Controllers;

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

class BlogController extends Controller
{
    private const POSTS_PER_PAGE = 12;

    public function index(Request $request, array $params = []): void
    {
        $currentPage = max(1, (int) ($request->query('page') ?? 1));
        $perPage     = self::POSTS_PER_PAGE;
        $offset      = ($currentPage - 1) * $perPage;

        $total      = BlogPost::publishedCount();
        $totalPages = max(1, (int) ceil($total / $perPage));
        $currentPage = min($currentPage, $totalPages);
        $offset     = ($currentPage - 1) * $perPage;

        $posts      = BlogPost::published($perPage, $offset);
        $categories = BlogCategory::allWithPostCount();

        // Load associated page record for editable intro content, show_title, SEO
        $page = Page::findByType('blog');
        if (!$page) {
            $page = Page::findBySlug('blog');
        }
        $pageTitle = ($page['title'] ?? '') ?: 'Blog';

        $this->renderFrontend('blog-list', [
            'system_page'     => $page ?: ['title' => 'Blog', 'content' => '', 'show_title' => 1],
            'page_title'      => $pageTitle,
            'seo_title'       => ($page['seo_title'] ?? '') ?: $pageTitle . ' – ' . setting('site_name'),
            'seo_description' => $page['seo_description'] ?? '',
            'canonical_url'   => base_url('/blog'),
            'breadcrumbs'     => [
                ['label' => 'Home',     'url' => '/'],
                ['label' => $pageTitle, 'url' => null],
            ],
            'posts'           => $posts,
            'categories'      => $categories,
            'pagination'      => [
                'current_page' => $currentPage,
                'total_pages'  => $totalPages,
                'total_posts'  => $total,
                'base_url'     => '/blog',
            ],
            'current_uri'     => '/blog',
        ]);
    }

    public function show(Request $request, array $params = []): void
    {
        $slug = $params['slug'] ?? '';
        $post = BlogPost::findWithDetails($slug);

        if (!$post) {
            http_response_code(404);
            $this->renderFrontend('404', ['current_uri' => $request->uri()]);
            return;
        }

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

        $this->renderFrontend('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'   => base_url('/blog/' . $slug),
            'og_type'         => 'article',
            'og_image'        => $ogImage,
            'breadcrumbs'     => [
                ['label' => 'Home',         'url' => '/'],
                ['label' => 'Blog',         'url' => '/blog'],
                ['label' => $post['title'], 'url' => null],
            ],
            'current_uri'     => '/blog/' . $slug,
        ]);
    }

    public function category(Request $request, array $params = []): void
    {
        $slug = $params['slug'] ?? '';
        $category = BlogCategory::findBySlug($slug);

        if (!$category) {
            http_response_code(404);
            $this->renderFrontend('404', ['current_uri' => $request->uri()]);
            return;
        }

        $page    = max(1, (int) ($request->query('page') ?? 1));
        $perPage = self::POSTS_PER_PAGE;

        $total      = BlogPost::publishedCountByCategory((int) $category['id']);
        $totalPages = max(1, (int) ceil($total / $perPage));
        $page       = min($page, $totalPages);
        $offset     = ($page - 1) * $perPage;

        $posts      = BlogPost::publishedByCategory((int) $category['id'], $perPage, $offset);
        $categories = BlogCategory::allWithPostCount();

        // Load system page for show_title / intro content
        $systemPage = Page::findByType('blog') ?: Page::findBySlug('blog');

        $this->renderFrontend('blog-list', [
            'system_page'     => $systemPage ?: ['title' => 'Blog', 'content' => '', 'show_title' => 1],
            'page_title'      => $category['name'],
            'seo_title'       => $category['name'] . ' – Blog – ' . setting('site_name'),
            'canonical_url'   => base_url('/blog/category/' . $slug),
            'breadcrumbs'     => [
                ['label' => 'Home',            'url' => '/'],
                ['label' => 'Blog',            'url' => '/blog'],
                ['label' => $category['name'], 'url' => null],
            ],
            'posts'           => $posts,
            'categories'      => $categories,
            'active_category' => $slug,
            'pagination'      => [
                'current_page' => $page,
                'total_pages'  => $totalPages,
                'total_posts'  => $total,
                'base_url'     => '/blog/category/' . $slug,
            ],
            'current_uri'     => '/blog/category/' . $slug,
        ]);
    }

    public function tag(Request $request, array $params = []): void
    {
        $slug = $params['slug'] ?? '';

        $posts = $this->db()->fetchAll(
            "SELECT p.*, u.username as author_name FROM iw_blog_posts p
             LEFT JOIN iw_blog_post_tags pt ON p.id = pt.post_id
             LEFT JOIN iw_blog_tags t ON pt.tag_id = t.id
             LEFT JOIN iw_users u ON p.author_id = u.id
             WHERE p.status = 'published' AND t.slug = :tag_slug
             ORDER BY p.published_at DESC",
            ['tag_slug' => $slug]
        );

        $tagLabel = 'Tag: ' . $slug;

        // Load system page for show_title / intro content
        $systemPage = Page::findByType('blog') ?: Page::findBySlug('blog');

        $this->renderFrontend('blog-list', [
            'system_page'     => $systemPage ?: ['title' => 'Blog', 'content' => '', 'show_title' => 1],
            'page_title'      => $tagLabel,
            'seo_title'       => $tagLabel . ' – Blog – ' . setting('site_name'),
            'seo_description' => '',
            'canonical_url'   => base_url('/blog/tag/' . $slug),
            'breadcrumbs'     => [
                ['label' => 'Home',     'url' => '/'],
                ['label' => 'Blog',     'url' => '/blog'],
                ['label' => $tagLabel,  'url' => null],
            ],
            'posts'           => $posts,
            'current_uri'     => '/blog/tag/' . $slug,
        ]);
    }

    private function renderFrontend(string $template, array $data = []): void
    {
        $data['main_menu']   = Menu::getItems('main');
        $data['footer_menu'] = Menu::getItems('footer');

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