<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Models\Site;
use App\Models\Article;
use App\Models\Topic;
use App\Models\SiteSeoMetric;

class DashboardController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();

        $sites = Site::findAll('name ASC');
        $articleStats = Article::getStats();
        $totalSites = Site::count();
        $activeSites = Site::count('is_active = 1');
        $totalTopics = Topic::count();
        $recentArticles = Article::findAllWithRelations(10);

        $this->view('dashboard/index', [
            'sites' => $sites,
            'articleStats' => $articleStats,
            'totalSites' => $totalSites,
            'activeSites' => $activeSites,
            'totalTopics' => $totalTopics,
            'recentArticles' => $recentArticles,
        ]);
    }

    public function seoStats(): void
    {
        Auth::requireLogin();

        $sort = (string) $this->input('sort', 'traffic');
        $dir = strtolower((string) $this->input('dir', 'desc')) === 'asc' ? 'asc' : 'desc';
        $rows = SiteSeoMetric::latestForAllSites($sort, $dir);

        $this->view('dashboard/seo-stats', [
            'rows' => $rows,
            'currentSort' => $sort,
            'currentDir' => $dir,
        ]);
    }
}
