<?php

namespace Mtc\Plugins\SiteMenu\Controller;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Mtc\Plugins\SiteMenu\Classes\SiteMenu;

/**
 * @class SiteMenuController
 * @author Nithika Senaweera <nithika.senaweera@@mtc.co.uk>
 * @date  2025-05-22
 * @description Site Menu Controller
 * @extends Controller
 * @copyright MTC Media
 * @version 2.0
 * */
class SiteMenuController extends Controller
{
    public function index() : string
    {
        return json_encode(['success' => 'Site menu Controller loaded successfully']);
    }

    /**
     * @description get site menu children by parent name
     * @param Request $request
     * @return String
     * @author Nithika Senaweera <nithika.senaweera@@mtc.co.uk>
     * @date  2025-05-22
     * @version 2.0
     * @copyright MTC Media
     */
    public function childrenByName(Request $request) : string {
        // Validate the request to ensure 'name' is provided
        $name = $request->input('name');
        try {
            // Find the parent site menu by name
            $parent = SiteMenu::where('name', $name)->first();

            if (!$parent) {
                http_response_code(404);
                return json_encode(['error' => 'Parent site menu not found']);
            }

            // Get the parent ID
            $parentId = $parent->id;

            // Fetch the children of the parent site menu
            $children = self::children($parentId);

            $children = json_decode($children, true);
            // Recursively fetch children for each child
            foreach ($children as $key => $child) {
                $children[$key]['children'] = $this->getChildrenRecursively($child['id']);
            }

            if ($children) {
                // Set response code and return JSON response
                http_response_code(200);
                return json_encode($children);
            } else {
                // Set response code and return error message
                http_response_code(404);
                return json_encode(['error' => 'No children found for the specified parent site menu']);
            }

        } catch (\Exception $e) {
            // Set response code and return error message
            http_response_code(500);
            return json_encode(['error' => 'An error occurred while fetching the site menu children: ' . $e->getMessage()]);
        }
    }

    /**
     * @method children
     * @description get site menu children by parent id
     * @param $id int
     * @return String
     * @author Nithika Senaweera <nithika.senaweera@mtc.co.uk>
     * @date  2025-05-22
     * @version 2.0
     * @copyright MTC Media
     */
    public function children(int $id) : String
    {

        try {
            $children = SiteMenu::where('parent_id', $id)->orderBy('order')->get();
            if ($children) {
                // set response code and return JSON response
                http_response_code(200);
                return json_encode($children);
            } else {
                // set response code and return error message
                http_response_code(404);
                return json_encode(['error' => 'Site menu not found']);
            }
        }
        catch (\Exception $e) {
            // set response code and return error message
            http_response_code(500);
            return json_encode(
                ['error' => 'An error occurred while fetching the site menu children: ' . $e->getMessage()]
            );
        }
    }

    /**
     * @description Recursively fetch children of a site menu item
     *
     * @param $parentId int
     *
     * @return array
     * */
    private function getChildrenRecursively(int $parentId) : array {
        // Fetch direct children of the current parent ID
        $children = SiteMenu::where('parent_id', $parentId)->get();

        if ($children->isEmpty()) {
            return [];
        }

        // Initialize an array to hold the result
        $result = [];

        foreach ($children as $child) {
            // For each child, recursively get its children and add to the result
            $childData = $child->toArray();
            $childData['children'] = $this->getChildrenRecursively($child->id);
            $result[] = $childData;
        }

        return $result;
    }


    // End of SiteMenuController
}
