<?php

namespace App\Http\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Event;
use App\Models\EventCategory;
use App\Models\Menu;
use App\Models\Page;

/**
 * ITSWEBER CMS – Frontend Event Controller (Phase 4b)
 */
class EventController extends Controller
{
    /**
     * Event listing – upcoming published events, with optional category filter.
     */
    public function index(Request $request, array $params = []): void
    {
        $categorySlug = trim($request->input('category', ''));
        $categoryId   = 0;
        $categoryName = '';

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

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

        $events     = Event::publishedUpcoming($perPage, $offset, $categoryId);
        $total      = Event::countPublishedUpcoming($categoryId);
        $pages      = (int) ceil($total / $perPage);
        $categories = EventCategory::all('name');
        $featured   = Event::featuredUpcoming(4);

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

        $this->renderFrontend('events', [
            'system_page'      => $page ?: ['title' => 'Events', '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('/events'),
            'breadcrumbs'      => [
                ['label' => 'Home',         'url' => '/'],
                ['label' => $defaultTitle,  'url' => null],
            ],
            'events'           => $events,
            'featured'         => $featured,
            'categories'       => $categories,
            'current_category' => $categorySlug,
            'total'            => $total,
            'page'             => $currentPage,
            'pages'            => $pages,
            'current_uri'      => '/events',
        ]);
    }

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

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

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

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

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

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

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

        $events     = Event::publishedUpcoming($perPage, $offset, $categoryId);
        $total      = Event::countPublishedUpcoming($categoryId);
        $pages      = (int) ceil($total / $perPage);
        $categories = EventCategory::all('name');
        $featured   = Event::featuredUpcoming(4);
        $pageTitle  = 'Events: ' . $category['name'];

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

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

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

    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);
    }
}
