<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Routing\Controller;
use Rvsitebuilder\Core\Models\CoreSlug;
use Rvsitebuilder\Wysiwyg\Http\Requests\ReturnContentSeoRequest;

class SeoController extends Controller
{
    public function returnContentSeo(ReturnContentSeoRequest $request)
    {
        $slug = CoreSlug::find($request->input('slug_id'));

        if (!$slug->slugble->isCustomHeader()) {
            $getHeader = false;
            // $slug->Menu->first();
            $menu = $slug->getMenu;

            // if has menu

            if (count($menu)) {
                $menu = $menu->first();
                while (false == $getHeader) {
                    if (!empty($menu->getParent)) {
                        // if has parent menu and
                        $menu = $menu->getParent;
                        if ($menu->getSlug->slugble->isCustomHeader()) {
                            $getHeader = true;
                            $header = $menu->getSlug->slugble->getHeader;
                        }
                    } elseif (empty($menu->getParent)) {    // if not has parent menu
                        if ($menu->getSlug->slugble->isCustomHeader()) {
                            // if is custom banner use it

                            $getHeader = true;
                            $header = $menu->getSlug->slugble->getHeader;
                        } else {
                            // if root menu is not custom banner
                            $getHeader = true;
                            $homepage = config('core.db.home_page');
                            $header = CoreSlug::where('slug_name', '=', $homepage)->first();
                            $header = $header->slugble->getHeader;
                        }
                    }
                }
            } else {
                // if is not has menu use master banner
                $homepage = config('core.db.home_page');
                $header = CoreSlug::where('slug_name', '=', $homepage)->first();
                $header = $header->slugble->getHeader;
            }
        } else {
            $header = $slug->slugble->getHeader;
        }

        $pageContent = $slug->slugble->content_view;
        $headerContent = $header->content_view;
        $pageName = $slug->slugble->getPagename();

        $content = (object) [
                 'headerContent' => $headerContent,
                 'pageContent' => $pageContent,
                 'pageName' => $pageName,
         ];

        return response()->json($content);
    }
}
