<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Frontend extends MY_Controller
{
    protected bool $requireAuth = false;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('kb_model');
    }

    public function index()
    {
        $this->knowledgebase();
    }

    public function knowledgebase()
    {
        $search = trim((string) $this->input->get('q', true));
        $selectedCategory = (int) $this->input->get('category', true);

        $categories = $this->db
            ->where('type', 'kb')
            ->where('status', 1)
            ->order_by('sort', 'ASC')
            ->order_by('kb_category_id', 'ASC')
            ->get('tbl_kb_category')
            ->result();

        $articles = $this->db
            ->select('tbl_knowledgebase.*, tbl_kb_category.category AS category_name, tbl_kb_category.description AS category_description')
            ->from('tbl_knowledgebase')
            ->join('tbl_kb_category', 'tbl_kb_category.kb_category_id = tbl_knowledgebase.kb_category_id', 'left')
            ->where('tbl_kb_category.type', 'kb')
            ->where('tbl_kb_category.status', 1)
            ->where('tbl_knowledgebase.status', 1)
            ->where('tbl_knowledgebase.for_all', 'No')
            ->order_by('tbl_knowledgebase.total_view', 'DESC')
            ->order_by('tbl_knowledgebase.kb_id', 'DESC')
            ->get()
            ->result();

        $categoryCounts = array();
        if (!empty($articles)) {
            foreach ($articles as $article) {
                $cid = (int) $article->kb_category_id;
                if (!isset($categoryCounts[$cid])) {
                    $categoryCounts[$cid] = 0;
                }
                $categoryCounts[$cid]++;
            }
        }

        $filteredArticles = array();
        if (!empty($articles)) {
            foreach ($articles as $article) {
                if (!empty($selectedCategory) && (int) $article->kb_category_id !== $selectedCategory) {
                    continue;
                }

                if ($search !== '') {
                    $haystack = mb_strtolower((string) ($article->title . ' ' . strip_tags((string) $article->description) . ' ' . $article->category_name));
                    if (mb_strpos($haystack, mb_strtolower($search)) === false) {
                        continue;
                    }
                }
                $filteredArticles[] = $article;
            }
        }

        // Keep selected category valid.
        if (!empty($selectedCategory)) {
            $exists = false;
            foreach ($categories as $category) {
                if ((int) $category->kb_category_id === $selectedCategory) {
                    $exists = true;
                    break;
                }
            }
            if (!$exists) {
                $selectedCategory = 0;
            }
        }

        $currentCategory = null;
        if (!empty($selectedCategory)) {
            foreach ($categories as $category) {
                if ((int) $category->kb_category_id === $selectedCategory) {
                    $currentCategory = $category;
                    break;
                }
            }
        }

        // Group filtered articles by category for compact category cards.
        $grouped = array();
        foreach ($filteredArticles as $article) {
            $cid = (int) $article->kb_category_id;
            if (!isset($grouped[$cid])) {
                $grouped[$cid] = array();
            }
            $grouped[$cid][] = $article;
        }

        $data = array(
            'title' => lang('knowledgebase'),
            'categories' => $categories,
            'category_counts' => $categoryCounts,
            'articles' => $filteredArticles,
            'grouped_articles' => $grouped,
            'current_category' => $currentCategory,
            'selected_category' => $selectedCategory,
            'search' => $search,
        );

        $this->load->view('frontend/knowledgebase', $data);
    }

    public function knowledgebase_article($id = null)
    {
        $id = (int) $id;
        if (empty($id)) {
            show_404();
        }

        $article = $this->db
            ->select('tbl_knowledgebase.*, tbl_kb_category.category AS category_name, tbl_kb_category.description AS category_description, tbl_kb_category.kb_category_id')
            ->from('tbl_knowledgebase')
            ->join('tbl_kb_category', 'tbl_kb_category.kb_category_id = tbl_knowledgebase.kb_category_id', 'left')
            ->where('tbl_knowledgebase.kb_id', $id)
            ->where('tbl_knowledgebase.status', 1)
            ->where('tbl_knowledgebase.for_all', 'No')
            ->where('tbl_kb_category.status', 1)
            ->where('tbl_kb_category.type', 'kb')
            ->get()
            ->row();

        if (empty($article)) {
            show_404();
        }

        $this->kb_model->increase_total_view($id);

        $related = $this->db
            ->select('kb_id, title, total_view')
            ->from('tbl_knowledgebase')
            ->where('status', 1)
            ->where('for_all', 'No')
            ->where('kb_category_id', (int) $article->kb_category_id)
            ->where('kb_id !=', $id)
            ->order_by('total_view', 'DESC')
            ->order_by('kb_id', 'DESC')
            ->limit(8)
            ->get()
            ->result();

        $categories = $this->db
            ->where('type', 'kb')
            ->where('status', 1)
            ->order_by('sort', 'ASC')
            ->order_by('kb_category_id', 'ASC')
            ->get('tbl_kb_category')
            ->result();

        $categoryCountsQuery = $this->db
            ->select('kb_category_id, COUNT(*) AS total_articles')
            ->from('tbl_knowledgebase')
            ->where('status', 1)
            ->where('for_all', 'No')
            ->group_by('kb_category_id')
            ->get()
            ->result();

        $categoryCounts = array();
        foreach ($categoryCountsQuery as $row) {
            $categoryCounts[(int) $row->kb_category_id] = (int) $row->total_articles;
        }

        $data = array(
            'title' => $article->title,
            'article' => $article,
            'related' => $related,
            'categories' => $categories,
            'category_counts' => $categoryCounts,
        );

        $this->load->view('frontend/knowledgebase_article', $data);
    }
}
