<?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\GalleryAlbum;
use App\Models\Event;
use App\Models\Download;
use App\Models\Media;
use App\Models\User;
use App\Models\Setting;
use App\Services\MaintenanceService;

class DashboardController extends Controller
{
    public function index(Request $request, array $params = []): void
    {
        $basePath    = $this->app->basePath();
        $versionFile = $basePath . '/app/Config/version.php';
        $cmsVersion  = is_file($versionFile) ? require $versionFile : '–';

        $postCount = BlogPost::count();

        // locale-aware date for welcome banner
        $locale = current_locale();
        if ($locale === 'de') {
            $days   = ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'];
            $months = ['','Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
            $todayFormatted = $days[(int) date('w')] . ', ' . date('j') . '. ' . $months[(int) date('n')] . ' ' . date('Y');
        } else {
            $todayFormatted = date('l, F j, Y');
        }

        $data = [
            'pageTitle'          => 'Dashboard',
            'todayFormatted'     => $todayFormatted,

            // primary stats
            'pageCount'          => Page::count(),
            'postCount'          => $postCount,
            'postPublished'      => BlogPost::count(['status' => 'published']),
            'postDraft'          => BlogPost::count(['status' => 'draft']),
            'galleryCount'       => GalleryAlbum::count(),
            'eventCount'         => Event::count(),
            'upcomingEventCount' => Event::countPublishedUpcoming(),

            // secondary stats
            'downloadCount'      => Download::count(),
            'mediaCount'         => Media::count(),
            'userCount'          => User::count(),

            // content widgets
            'recentPosts'        => BlogPost::recent(5),
            'recentPages'        => Page::recentlyUpdated(5),
            'upcomingEvents'     => Event::upcomingCompact(3),

            // system info
            'systemInfo'         => [
                'cms_version'  => $cmsVersion,
                'php_version'  => PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
                'active_theme' => Setting::get('active_theme', 'default'),
                'maintenance'  => MaintenanceService::isActive($basePath),
            ],

            'auth'               => $this->auth(),
            'csrf'               => $this->csrf(),
        ];

        $view = $this->app->service('view');
        $html = $view->renderAdmin('dashboard/index', $data);
        Response::html($html);
    }
}
