<?php

namespace App\Http\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Download;
use App\Models\DownloadCategory;
use App\Models\Menu;
use App\Models\Page;

/**
 * ITSWEBER CMS – Frontend Download Controller (Phase 8)
 */
class DownloadController extends Controller
{
    /**
     * Download archive – published downloads with optional category filter and search.
     */
    public function index(Request $request, array $params = []): void
    {
        $categorySlug = trim($request->input('category', ''));
        $search       = trim($request->input('search', ''));
        $categoryId   = 0;
        $categoryName = '';

        if ($categorySlug !== '') {
            $category = DownloadCategory::findBySlug($categorySlug);
            if ($category) {
                $categoryId   = (int) $category['id'];
                $categoryName = $category['name'];
            }
        }

        $perPage    = 12;
        $page       = max(1, (int) $request->input('page', 1));
        $offset     = ($page - 1) * $perPage;

        $downloads  = Download::published($perPage, $offset, $categoryId, $search);
        $total      = Download::countPublished($categoryId, $search);
        $pages      = (int) ceil($total / $perPage);
        $categories = DownloadCategory::all('name');

        // Load associated page record for editable intro content, show_title, SEO
        $systemPage = Page::findByType('downloads');
        if (!$systemPage) {
            $systemPage = Page::findBySlug('download');
        }
        $defaultTitle = ($systemPage['title'] ?? '') ?: 'Downloads';
        $pageTitle    = $categoryName ? $defaultTitle . ': ' . $categoryName : $defaultTitle;

        $this->renderFrontend('downloads', [
            'system_page'      => $systemPage ?: ['title' => 'Downloads', 'content' => '', 'show_title' => 1],
            'page_title'       => $pageTitle,
            'seo_title'        => ($systemPage['seo_title'] ?? '') ?: $pageTitle . ' – ' . setting('site_name'),
            'seo_description'  => $systemPage['seo_description'] ?? '',
            'canonical_url'    => base_url('/download'),
            'breadcrumbs'      => [
                ['label' => 'Home',         'url' => '/'],
                ['label' => $defaultTitle,  'url' => null],
            ],
            'downloads'        => $downloads,
            'categories'       => $categories,
            'current_category' => $categorySlug,
            'search'           => $search,
            'total'            => $total,
            'page'             => $page,
            'pages'            => $pages,
            'current_uri'      => '/download',
        ]);
    }

    /**
     * Category listing shortcut: /download/category/{slug}
     */
    public function category(Request $request, array $params = []): void
    {
        $slug     = $params['slug'] ?? '';
        $category = DownloadCategory::findBySlug($slug);

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

        $categoryId = (int) $category['id'];
        $search     = trim($request->input('search', ''));
        $perPage    = 12;
        $page       = max(1, (int) $request->input('page', 1));
        $offset     = ($page - 1) * $perPage;

        $downloads  = Download::published($perPage, $offset, $categoryId, $search);
        $total      = Download::countPublished($categoryId, $search);
        $pages      = (int) ceil($total / $perPage);
        $categories = DownloadCategory::all('name');
        $pageTitle  = __('theme.downloads_category_title', ['name' => $category['name']]);

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

        $this->renderFrontend('downloads', [
            'system_page'      => $systemPage ?: ['title' => 'Downloads', 'content' => '', 'show_title' => 1],
            'page_title'       => $pageTitle,
            'seo_title'        => $pageTitle . ' – ' . setting('site_name'),
            'canonical_url'    => base_url('/download/category/' . $slug),
            'breadcrumbs'      => [
                ['label' => 'Home',            'url' => '/'],
                ['label' => 'Downloads',       'url' => '/download'],
                ['label' => $category['name'], 'url' => null],
            ],
            'downloads'        => $downloads,
            'categories'       => $categories,
            'current_category' => $slug,
            'search'           => $search,
            'total'            => $total,
            'page'             => $page,
            'pages'            => $pages,
            'current_uri'      => '/download/category/' . $slug,
        ]);
    }

    /**
     * Download detail page.
     */
    public function show(Request $request, array $params = []): void
    {
        $slug     = $params['slug'] ?? '';
        $download = Download::findPublished($slug);

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

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

        $this->renderFrontend('download-single', [
            'download'        => $download,
            'page_title'      => $download['title'],
            'seo_title'       => (!empty($download['seo_title']) ? $download['seo_title'] : $download['title']) . ' – ' . setting('site_name'),
            'seo_description' => $download['seo_description'] ?? $download['excerpt'] ?? '',
            'canonical_url'   => base_url('/download/' . $slug),
            'og_image'        => $ogImage,
            'breadcrumbs'     => [
                ['label' => 'Home',              'url' => '/'],
                ['label' => 'Downloads',         'url' => '/download'],
                ['label' => $download['title'],  'url' => null],
            ],
            'current_uri'     => '/download/' . $slug,
        ]);
    }

    // -------------------------------------------------------------------------
    // HELPERS
    // -------------------------------------------------------------------------

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

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