<?php
declare(strict_types=1);

namespace App\Controller;

use App\Controller\AppController;
use Cake\Http\Exception\NotFoundException;
use Cake\Utility\Text;
use Cake\Http\Response;

/**
 * Contents Controller
 *
 * @property \App\Model\Table\ContentsTable $Contents
 * @method \App\Model\Entity\Content[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class ContentController extends AppController
{
    /**
     * Initialization hook method.
     *
     * This method is called automatically during the controller's initialization process.
     * It sets up the required table associations by fetching the respective table objects
     * using the `fetchTable()` method. This includes tables such as 'Menus', 'PageContents',
     * 'SectionBannerAssoc', 'Banners', 'Contents', and 'Files', which are used for handling
     * various entities within the application.
     *
     * @return void
     */
    public function initialize(): void
    {
        parent::initialize();
        $this->Menus = $this->fetchTable('Menus');
        $this->PageContents = $this->fetchTable('PageContents');
        $this->SectionBannerAssoc = $this->fetchTable('SectionBannerAssoc');
        $this->Banners = $this->fetchTable('Banners');
        $this->Contents = $this->fetchTable('Contents');
        $this->Files = $this->fetchTable('Files');
    }

    /*
     * Main method for home of the main menu clicks
     * Handles loading of contents for rendering on section homes
     */
    public function index()
    {
        /** 
         * Default home for basic section features
         *
         * The selected menu is in the section param of the request
         * Lets retreive the data and load the content for that section
         * 
         */

        $section = $this->request->getParam('section');

        // Find the menu details based on the provided 'slug' parameter
        $menuDetails = $this->PageContents->Menus->getMenuDetail($section);

        /**
         * Only load the content if the menu is active, else log the issue and throw a not found exception
         * And ofcourse, if no menu is found with the section slug, then there is no need to continue as well
         */
        if ($menuDetails == null) {
            $this->log('No menu found with the selected slug: ' . $this->request->getParam('section'), 'debug');
            throw new NotFoundException();
        } else if ($menuDetails->status != 1) {
            $this->log('Menu found with slug: ' . $this->request->getParam('section') . ' but not active', 'debug');
            throw new NotFoundException();
        }

        // Initialize the content array and populate the contents of each section
        $pageContents = $this->PageContents->Contents->getContents($menuDetails);

        $viewContents = [];

        if (!empty($pageContents)) {
            foreach ($pageContents as $pageContent) {
                $slug = $pageContent->slug ?? $menuDetails->slug;

                // Ensure that the key exists and is an array
                if (!isset($viewContents[$slug])) {
                    $viewContents[$slug] = [
                        'content' => []
                    ];
                }
                // Append the current content to the 'list' array
                $viewContents[$slug]['content'][] = $pageContent;
            }
        }

        // Load the banners. Banners are normally loaded at the top of the page.
        // So lets add it to the sections.
        // Append to any section if you want to show as well, could be carousel, etc....
        $banners = $this->Banners->getSectionTopBanners();

        /**
         * Load banners append to specific sections
         */
        $sectionBannerAssoc = $this->SectionBannerAssoc->Banners->getSectionBannerAssoc($menuDetails);

        // Load details on sub menus list
        $subMenuLists = $this->PageContents->Menus->getSubMenu($menuDetails);

        $this->set(compact('menuDetails', 'viewContents', 'banners', 'sectionBannerAssoc', 'subMenuLists'));
    }

    /*
     * Handles the event of clicking a sub menu
     * Performs generic actions to retrieve required content of that sub menu
     */
    public function subsection(): void
    {
        /** 
         * Default sub section for basic section features with sub menus
         *
         * The selected sub menu is in the subsection param of the request
         * The selected main menu is in the section param of the request
         * 
         * Lets retreive the data and load the content for that sub section
         * 
         */

        $subsection = $this->request->getParam('subsection');

        // Retrieve the sub menu using the section (Should be the same as the menu slug)
        $menuDetails = $this->PageContents->Menus->getMenuDetail($subsection);

        /**
         * Only load the content if the menu is active, else log the issue and throw a not found exception
         * And ofcourse, if no menu is found with the section slug, then there is no need to continue as well
         */
        if ($menuDetails == null) {
            $this->log('No menu found with the selected slug: ' . $this->request->getParam('section'), 'debug');
            throw new NotFoundException();
        } else if ($menuDetails->status != 1) {
            $this->log('Menu found with slug: ' . $this->request->getParam('section') . ' but not active', 'debug');
            throw new NotFoundException();
        }

        // Load details on sub menus list
        $subMenus = $this->PageContents->Menus->getSubSecSubMenu($menuDetails);

        // Initialize the content array and populate the contents of each sub section
        $pageContents = $this->PageContents->Contents->getSubSecContent($menuDetails, $subMenus);

        $viewContents = [];

        if (!empty($pageContents)) {
            foreach ($pageContents as $pageContent) {
                $slug = $pageContent->slug ?? $menuDetails->slug;

                // Ensure that the key exists and is an array
                if (!isset($viewContents[$slug])) {
                    $viewContents[$slug] = [
                        'content' => []
                    ];
                }
                // Append the current content to the 'list' array
                $viewContents[$slug]['content'][] = $pageContent;
            }
        }

        // Retrieve the submenus of this menu
        // We will use this to display sub menus in the form of category page / view
        $categoryContents = $this->PageContents->Menus->getCategory($menuDetails);

        $annualReports = $this->Files->getAnualReports();

        // Load details on sub menus list
        $subMenuLists = $this->PageContents->Menus->find('all', [
            'conditions' => [
                'status' => '1',
                'parent_menu_id' => $menuDetails->id
            ]
        ])->toArray();

        // Load the banners. Banners are normally loaded at the top of the page.
        // So lets add it to the sections.
        // Append to any section if you want to show as well, could be carousel, etc....
        $banners = $this->Banners->getSectionTopBanners();

        /**
         * Load banners append to specific sections
         */
        $sectionBannerAssoc = $this->SectionBannerAssoc->Banners->getSectionBannerAssoc($menuDetails);

        $this->set(compact('menuDetails', 'viewContents', 'categoryContents', 'annualReports', 'subMenuLists', 'banners', 'sectionBannerAssoc'));
        // Render the same view for the main menu
        // Most views are similar accross the site
        $this->render('sub_section');
    }

    /**
     * Handles the details of content
     * Retrive the content details 
     * and match the menu to compare if it is the right link
     */
    public function details($id = null)
    {

        /** 
         * The selected menu is in the section param of the request
         * 
         * Lets retreive the data and load the content for that sub section
         * 
         */
        $section = $this->request->getParam('section');

        if (!empty($section)) {
            // Find the menu details based on the provided 'slug' parameter
            $menuDetails = $this->PageContents->Menus->getMenuDetail($section);
        } else {
            $menuDetails = $this->PageContents->Menus->getMenuDetailById($id);
        }

        /**
         * Only load the content if the menu is active, else log the issue and throw a not found exception
         * And ofcourse, if no menu is found with the section slug, then there is no need to continue as well
         */
        if ($menuDetails == null) {
            $this->log('No menu found with the selected slug: ' . $this->request->getParam('section'), 'debug');
            throw new NotFoundException();
        } else if ($menuDetails->status != 1) {
            $this->log('Menu found with slug: ' . $this->request->getParam('section') . ' but not active', 'debug');
            throw new NotFoundException();
        }

        // Initialize the content array and populate the contents of each detail section
        $viewDetails = $this->PageContents->Contents->getDetailContent($id);

        //to used to change element 
        $detailSlug = strtolower(Text::slug($viewDetails->name));

        // Load the banners. Banners are normally loaded at the top of the page.
        // So lets add it to the sections.
        // Append to any section if you want to show as well, could be carousel, etc....
        $banners = $this->Banners->getSectionTopBanners();

        /**
         * Load banners append to specific sections
         */
        $sectionBannerAssoc = $this->SectionBannerAssoc->Banners->getSectionBannerAssoc($menuDetails);

        if ($viewDetails == null) {
            $this->log('No details found for content with ID: ' . $id, 'debug');
            throw new NotFoundException();
        }

        /**
         * Set the final values to the view
         */
        $this->set(compact('viewDetails', 'menuDetails', 'banners', 'sectionBannerAssoc','detailSlug'));
    }

}