<?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 : '–';

        // Consolidate dashboard counts into a single query (replaces 10 separate COUNT queries)
        $db = $this->app->db();
        $counts = $db->fetch("
            SELECT
                (SELECT COUNT(*) FROM iw_pages) AS pages,
                (SELECT COUNT(*) FROM iw_blog_posts) AS posts,
                (SELECT COUNT(*) FROM iw_blog_posts WHERE status = 'published') AS posts_published,
                (SELECT COUNT(*) FROM iw_blog_posts WHERE status = 'draft') AS posts_draft,
                (SELECT COUNT(*) FROM iw_gallery_albums) AS albums,
                (SELECT COUNT(*) FROM iw_events) AS events,
                (SELECT COUNT(*) FROM iw_events WHERE publish_status = 'published' AND start_date >= CURDATE()) AS events_upcoming,
                (SELECT COUNT(*) FROM iw_downloads) AS downloads,
                (SELECT COUNT(*) FROM iw_media) AS media,
                (SELECT COUNT(*) FROM iw_users) AS users
        ") ?: [];

        // 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 (single query)
            'pageCount'          => (int) ($counts['pages'] ?? 0),
            'postCount'          => (int) ($counts['posts'] ?? 0),
            'postPublished'      => (int) ($counts['posts_published'] ?? 0),
            'postDraft'          => (int) ($counts['posts_draft'] ?? 0),
            'galleryCount'       => (int) ($counts['albums'] ?? 0),
            'eventCount'         => (int) ($counts['events'] ?? 0),
            'upcomingEventCount' => (int) ($counts['events_upcoming'] ?? 0),

            // secondary stats (single query)
            'downloadCount'      => (int) ($counts['downloads'] ?? 0),
            'mediaCount'         => (int) ($counts['media'] ?? 0),
            'userCount'          => (int) ($counts['users'] ?? 0),

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