<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Lib\Content\SidebarLib;
use Rvsitebuilder\Core\Models\CoreSlug;

class SidebarController extends Controller
{
    public function resetSidebar(Request $request)
    {
        $slug_id = $request->input('slug_id');

        $slug = CoreSlug::findOrFail($slug_id);

        $sidebar_id = $slug->slugble->sidebar_id;

        // delete side bar all page
        if (!$slug->isHomepage()) {
            //TODO:: slug_name blog rename ได้
            if ($slug->isSystem() && $slug->slug_name == config('core.db.blog_index')) {
                $slug->slugble->update(['sidebar_id' => 2]);
                DB::table('core_sidebar')->where('id', '<>', '2')->delete($sidebar_id);
            } else {  // page
                $slug->slugble->update(['sidebar_id' => 0]);
                DB::table('core_sidebar')->delete($sidebar_id);
            }
        } else {
            // home
            $slug->slugble->getSidebar->update(['use_sidebar' => 0]);
        }

        //return side bar content
        if ($slug->isPost() || $slug->isCategory()) {
            $sidebar = SidebarLib::getSidebarBlog($slug);

            // ไม่สามารถ return เป็น json and array ได้ เพราะ จะเอาไป render widget ไม่ได้
            //::TODO พี่ต้น ของหาวิธีทำให้เป็น json and array ได้
            // จูล เพื่อน element ไว้เพื่อเอาไปทำ use_sidebar
            if ('left_content' == $request->input('type')) {
                return response()->json([
                    'left_content_edit' => $sidebar->left_content_edit,
                    'right_content_edit' => $sidebar->right_content_edit,
                    'use_sidebar' => $sidebar->use_sidebar,
                ]);

                return   $sidebar->left_content_edit.'<div id="use_reset" use_reset="'.$sidebar->use_sidebar.'">';
            }

            return   $sidebar->right_content_edit;
        }    // page and system
        $sidebar = SidebarLib::getSidebar($slug);

        return response()->json([
                    'left_content_edit' => $sidebar->left_content_edit,
                    'right_content_edit' => $sidebar->right_content_edit,
                    'use_sidebar' => $sidebar->use_sidebar,
            ]);
    }
}
