<?php

namespace App\Controllers;

use App\Models\SettingModel;
use App\Models\PageModel;
use App\Models\NewsModel;

class Pages extends BaseController
{
    public function view($slug)
    {
        $page = (new PageModel())->where('slug', $slug)->where('status', 'published')->first();

        if (!$page) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $settingModel = new SettingModel();

        $settings = $settingModel->getMany([
            'site_name', 'site_tagline', 'site_description',
            'site_logo_text', 'site_logo_icon',
            'contact_phone', 'contact_email', 'contact_address', 'contact_hours',
            'social_facebook', 'social_instagram', 'social_youtube', 'social_tiktok',
            'footer_description', 'footer_copyright', 'footer_services', 'footer_links',
            'theme_color',
            'spmb_url',
            'page_banners',
        ]);

        $allPages = (new PageModel())->where('status', 'published')
            ->orderBy('created_at', 'DESC')
            ->findAll();

        $newsModel = new NewsModel();

        // Categories
        $catRows = $newsModel->select('category, COUNT(*) as count')
            ->where('status', 'published')
            ->groupBy('category')
            ->orderBy('category', 'ASC')
            ->findAll();
        $categories = [];
        foreach ($catRows as $cr) {
            $categories[] = [
                'name'  => $cr['category'],
                'slug'  => $cr['category'],
                'count' => $cr['count'],
            ];
        }

        // Recent news
        $recentNews = $newsModel->where('status', 'published')
            ->orderBy('published_at', 'DESC')
            ->findAll(5);

        // Tags
        $tagRows = $newsModel->select('tags')
            ->where('status', 'published')
            ->findAll();
        $tagCounts = [];
        foreach ($tagRows as $tr) {
            $t = json_decode($tr['tags'], true);
            if (is_array($t)) {
                foreach ($t as $tag) {
                    $tag = trim($tag);
                    if ($tag !== '') {
                        $tagCounts[$tag] = ($tagCounts[$tag] ?? 0) + 1;
                    }
                }
            }
        }
        $tags = [];
        foreach ($tagCounts as $name => $count) {
            $tags[] = ['name' => $name, 'slug' => $name, 'count' => $count];
        }

        // Archive
        $db = \Config\Database::connect();
        $archiveRows = $db->query("SELECT DATE_FORMAT(published_at, '%Y-%m') as month, DATE_FORMAT(published_at, '%M %Y') as label, COUNT(*) as count FROM news WHERE status='published' GROUP BY month ORDER BY month DESC")->getResultArray();

        $data = [
            'page_title'       => $page['meta_title'] ?: $page['title'],
            'site_name'         => $settings['site_name'] ?? 'SekolahKu',
            'site_tagline'      => $settings['site_tagline'] ?? '',
            'site_description'  => $settings['site_description'] ?? '',
            'site_logo_text'    => $settings['site_logo_text'] ?? 'SekolahKu',
            'site_logo_icon'    => $settings['site_logo_icon'] ?? 'graduation-cap',
            'contact_phone'     => $settings['contact_phone'] ?? '',
            'contact_email'     => $settings['contact_email'] ?? '',
            'contact_address'   => $settings['contact_address'] ?? '',
            'contact_hours'     => $settings['contact_hours'] ?? '',
            'social_facebook'   => $settings['social_facebook'] ?? '',
            'social_instagram'  => $settings['social_instagram'] ?? '',
            'social_youtube'    => $settings['social_youtube'] ?? '',
            'social_tiktok'     => $settings['social_tiktok'] ?? '',
            'footer_description' => $settings['footer_description'] ?? '',
            'footer_copyright'  => $settings['footer_copyright'] ?? '',
            'footer_services'   => $settings['footer_services'] ?? '',
            'footer_links'      => $settings['footer_links'] ?? '',
            'theme_color'       => $settings['theme_color'] ?? 'blue',
            'spmb_url'          => $settings['spmb_url'] ?? '#',
            'page_banners'      => $settings['page_banners'] ?? null,
            'page'              => $page,
            'all_pages'         => $allPages,
            'categories'        => $categories,
            'recent_news'       => $recentNews,
            'archive'           => $archiveRows,
            'tags'              => $tags,
        ];

        return view('pages/page', $data);
    }
}
