<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Lib\Site\SlugLib;
use Lib\Util\RVLog;
// Model
use Rvsitebuilder\Blog\Models\BlogCategory;
use Rvsitebuilder\Blog\Models\BlogPostCategory;
// Request
use Rvsitebuilder\Core\Models\CoreMenu;
use Rvsitebuilder\Core\Models\CoreOldSlug;
use Rvsitebuilder\Core\Models\CoreSetting;
use Rvsitebuilder\Core\Models\CoreSlug;
use Rvsitebuilder\Core\Traits\BaseRelation;
use Rvsitebuilder\Wysiwyg\Http\Requests\SetDraft;
use Rvsitebuilder\Wysiwyg\Http\Requests\SetHomepage;

class PageOptionController extends Controller
{
    public function setDraft(SetDraft $request)
    {
        $slug_id = $request->input('slug_id');

        try {
            DB::beginTransaction();
            $updateOption = CoreSlug::find($slug_id);

            // toggle draft / undraft
            $is_published = (1 == $updateOption->slugble->is_published ? 0 : 1);

            $updateOption->slugble->update([
                    'is_published' => $is_published,
            ]);

            DB::commit();

            return response()->json([
                    'status' => true,
                    'data' => [
                            'is_published' => $is_published,
                        'slug_id' => $slug_id,
                        'msg' => 'Success.',
                    ],
            ], 200);
        } catch (Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));

            return response()->json([
                    'status' => false,
                    'data' => [
                            'message' => 'Set draft fail.',
                    ],
            ], 500);
        }
    }

    public static function delete(Request $request)
    {
        $slug_id = $request->input('slug_id');

        try {
            $updateOption = CoreSlug::with('slugble')->where('id', $slug_id)->first();

            if (count($updateOption->slugble->getBookmark)) {
                $allSlugId = $updateOption->slugble->getBookmark->pluck('id')->toArray();
            } else {
                $allSlugId = [];
            }

            // del old slug
            if (count($updateOption->getOldSlug)) {
                $updateOption->getOldSlug()->delete();
            }

            // del menu

            CoreMenu::whereIn('slug_id', $allSlugId)->delete();

            // del seo
            if (!empty($updateOption->slugble->getSeo)) {
                $updateOption->slugble->getSeo()->delete();
            }

            // del facebook
            if (!empty($updateOption->slugble->getFacebook)) {
                $updateOption->slugble->getFacebook()->delete();
            }

            // del twiter
            if (!empty($updateOption->slugble->geTwitter)) {
                $updateOption->slugble->geTwitter()->delete();
            }

            // if is post delete post category
            if ($updateOption->isPost()) {
                $updateOption->slugble->getCategoryInPost()->delete();
            }

            if ($updateOption->isCategory()) {
                $updateOption->slugble->getPostInCategory()->delete();
            }

            // del slug
            $updateOption->slugble->getBookmark()->delete();

            $updateOption->slugble->delete();

            DB::commit();

            return response()->json([
                    'status' => true,
                    'data' => [
                        'slug_id' => $slug_id,
                        'msg' => 'Delete Success.',
                    ],
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));

            return response()->json([
                    'status' => false,
                    'data' => [],
                    'error' => 'Delete fail.',
            ], 500);
        }
    }

    public function setHomepage(SetHomepage $request)
    {  
        $slug_id = $request->input('slug_id');

        try {
            DB::beginTransaction();

            $updateOption = CoreSlug::find($slug_id); 
            // ถ้า sidebar_id ของ page ที่กำลังจะเปลี่ยนเป็น homepage = 0 จะ update sidebar_id ของ home page เก่า
            
            // sidebar blog จะไม่เหมือนของ page ต้องใช้ master sidebar แยกกัน 
            if( $updateOption->isPost() ){ 
                if (0 == $updateOption->slugble->sidebar_id) { 
                    $sidebar_id = BaseRelation::getBlogMasterSidebarId();
                        $updateOption->slugble->update([
                                'sidebar_id' => $sidebar_id,
                        ]);
                }
            } else { 

                if (0 == $updateOption->slugble->sidebar_id) {
                    $sidebar_id = BaseRelation::getMasterSidebarId();
                    $updateOption->slugble->update([
                            'sidebar_id' => $sidebar_id,
                    ]);
                }
            }

            if (0 == $updateOption->slugble->header_id) {
                $header_id = BaseRelation::getMasterHeaderId();
                $updateOption->slugble->update([
                        'header_id' => $header_id,
                ]);
            }

            if (0 == $updateOption->slugble->footer_id) { 
                $footer_id = BaseRelation::getMasterFooterId();
                $updateOption->slugble->update([
                        'footer_id' => $footer_id,
                ]);
            }

            CoreSetting::updateOrCreate([
                    'key' => 'home_page',
            ], [
                    'value' => $updateOption->slug_name,
            ]);

            DB::commit();

            return response()->json([
                    'status' => true,
                'data' => [
                    'slug_id' => $slug_id,
                    'msg' => 'Set as home Success.',
                ],
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));

            return response()->json([
                    'status' => false,
                    'data' => [],
                    'error' => 'Delete fail.',
            ], 500);
        }
    }

    public function rename(Request $request)
    {
        $slug_id = $request->input('slug_id');
        $category = $request->input('category_name');
        $page_name = SlugLib::genPagename($request->input('page_name'));
        $newSlug = SlugLib::genSlug($request->input('page_name'));
        try {
            DB::beginTransaction();

            //if menu title == page name / post name then change menu title
            $slug = CoreSlug::findOrFail($request->input('slug_id'));
            $old_page_name = htmlentities($slug->slugble->getPagename());
            $menu = CoreMenu::where('slug_id', '=', $slug_id)->get(['menu_title', 'id']);
            $changed_menutitle = false;
            foreach ($menu as $k => $v) {
                if (strtolower($v->menu_title) == strtolower($old_page_name)) {
                    $coremenu = CoreMenu::find($v->id);
                    $coremenu->menu_title = $page_name;
                    $coremenu->save();
                    $changed_menutitle = true;
                }
            }
            // if is post
            if ($slug->isPost()) {
                $slug->slugble->update(['post_name' => $page_name]);
                $redirect_url = url('/admin/wysiwyg/uikit/show/'.$slug->slug_prefix.'/'.$newSlug);
            }
            if ($slug->isPage() || $slug->isSystem()) {
                $slug->slugble->update(['page_name' => $page_name]);

                //TODO:: ถ้า systemPage สามารถแก้ไข ได้ ต้องแยกออกจาก page เพราะ systemPage แยก password/reset เป็น slug_prefix,slug_name แล้ว
                $redirect_url = url('/admin/wysiwyg/uikit/show/'.$newSlug);
            }
            if ($slug->isCategory()) {
                $slug->slugble->update(['category_name' => $page_name]);
                $redirect_url = url('/admin/wysiwyg/uikit/show/'.$slug->slug_prefix.'/'.$newSlug);
            }

            if ($slug->slug_name != $newSlug) {
                $findSlug = CoreSlug::where('slug_name', '=', $slug)->distinct()->count();
                $newSlug = SlugLib::checkSlugExist($newSlug);
            }

            $this->updateOldSlug($slug, $newSlug);

            // if page is homepage update homepage
            if ($slug->slug_name == config('core.db.home_page')) {
                CoreSetting::updateOrCreate(['key' => 'home_page'], ['value' => $newSlug]);
            }

            //   blog_index
            if ($slug->slug_name == config('core.db.blog_index')) {
                CoreSetting::updateOrCreate(['key' => 'blog_index'], ['value' => $newSlug]);

                // update blog_index
                CoreSlug::where('slugble_type', '=', config('core.db.blog_index'))->update(['slug_name' => $newSlug]);

                // update prefix category
                CoreSlug::where('slugble_type', '=', config('core.model.category'))->update(['slug_prefix' => $newSlug]);

                $findPrefixPost = CoreSlug::where('slugble_type', '=', config('core.model.post'));

                //find category
                $cat = BlogPostCategory::all();

                foreach ($cat as $key => $val) {
                    $post_id = $val['post_id'];
                    $category_id = $val['category_id'];

                    $catName = BlogCategory::findOrfail($category_id);

                    $slug_prefix = $newSlug.'/'.strtolower($catName->category_name);

                    $slugPrefixOld = $slug->slug_name.'/'.$catName->category_name;

                    // update prefix post
                    CoreSlug::where('slugble_type', '=', config('core.model.post'))
                    ->where('slug_prefix', '=', $slugPrefixOld)
                    ->update(['slug_prefix' => $slug_prefix]);
                }
            }

            // use "$slug->isCategory()" เพราะ ไม่มีใน config
            if ($slug->isCategory()) {
                $oldSlugName = CoreOldSlug::where('slug_id', '=', $slug->id)->orderBy('id', 'desc')->first();

                $blogCat = $slug->slug_prefix.'/'.$slug->slug_name;

                $catName = CoreSlug::where('slugble_type', '=', config('core.model.category'))->first();

                $slugPrefixOld = $catName->slug_prefix.'/'.$slug->slug_name;

                //find category
                $allSlugPrefix = CoreSlug::where('slug_prefix', '=', $slugPrefixOld)->first();

                if (!empty($allSlugPrefix)) {
                    foreach ($allSlugPrefix as $key => $val) {
                        // update prefix post
                        CoreSlug::where('slugble_type', '=', config('core.model.post'))
                                    ->where('slug_prefix', '=', $slugPrefixOld)
                                    ->update(['slug_prefix' => $catName->slug_prefix.'/'.$newSlug]);
                    }
                }
            }

            $slug->slugble->getBookmark()->update([
                    'slug_name' => $newSlug,
            ]);

            DB::commit();

            return response()->json([
                    'status' => true,
                    'data' => [
                            'url' => $redirect_url,
                            'slug_name' => $newSlug,
                            'page_name' => $page_name,
                            'slug_id' => $slug_id,
                            'changed_menutitle' => $changed_menutitle,
                    ],
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));

            return response()->json([
                    'status' => false,
                    'data' => [],
            ], 500);
        }
    }

    public function duplicate(Request $request)
    {
        $slug_id = $request->input('slug_id');
        try {
            $updateOption = CoreSlug::find($slug_id);

            $slug_name = $updateOption->slug_name;
            $slug_prefix = $updateOption->slug_prefix;

            if ($updateOption->isPost()) {
                // if is post use field post_name
                $pageName = $updateOption->slugble->post_name;
            } else {
                // if is page or system page use field page_name
                $pageName = $updateOption->slugble->page_name;
            }

            $slugAllArray = CoreSlug::distinct('slug_name')->pluck('slug_name')->toArray();
            $checkSlug = true;
            $countCopy = 2;
            $newSlug = '';

            // Loop make new page_name and slug_name
            while ($checkSlug) {
                $newSlug = $slug_name.'-'.$countCopy; // ex: home-1
                $newPageName = $pageName.'-'.$countCopy;

                if (!\in_array($newSlug, $slugAllArray)) {
                    // if new slug donts exist
                    $checkSlug = false;
                }
                ++$countCopy;
            }

            $replicatePage = $updateOption->slugble->replicate();

            if ($updateOption->isPost()) {
                // if is post use field post_name
                $replicatePage->post_name = $newPageName;
            } else {
                // if is page or system page use field page_name
                $replicatePage->page_name = $newPageName;
            }

            $replicatePage->save();

            // Loop replicate slug and bookmark
            foreach ($updateOption->slugble->getBookmark as $bookmark) {
                $replicateSlug = $bookmark->replicate();
                $replicateSlug->slugble_id = $replicatePage->id;
                $replicateSlug->slug_name = $newSlug;
                $replicateSlug->slug_prefix = $slug_prefix;
                $replicateSlug->save();
            }

            // echo json_encode($updateOption->slugble->getSeo);
            // replicate seo
            $replicateSeo = $updateOption->slugble->getSeo->replicate();
            $replicateSeo->seoble_id = $replicatePage->id;
            $replicateSeo->save();

            if ($updateOption->slugble->getTwitter) {
                // replicate twitter
                $replicateTwit = $updateOption->slugble->getTwitter->replicate();
                $replicateTwit->twitble_id = $replicatePage->id;
                $replicateTwit->save();
            }

            if ($updateOption->slugble->getFacebook) {
                // replicate facebook
                $replicateFacebook = $updateOption->slugble->getFacebook->replicate();
                $replicateFacebook->fbble_id = $replicatePage->id;
                $replicateFacebook->save();
            }

            if ($updateOption->isPost()) {
                foreach ($updateOption->slugble->getCategoryInPost as $category) {
                    $replicateCatPost = $category->replicate();
                    $replicateCatPost->post_id = $replicatePage->id;
                    $replicateCatPost->save();
                }
            }

            DB::commit();
            $newPage = CoreSlug::where('slug_name', '=', $newSlug)->first();
//             dd($updateOption->slugble->getPrimaryCategory->getCategory->id);

            //retrun redirect url
            if ('Page' == $updateOption->slugble->getType()) {
                return response()->json([
                    'status' => true,
                    'data' => [
                        'url' => url('/admin/wysiwyg/uikit/show/'.$newSlug),
                        'msg' => 'Duplicate Success.',
                        // JSTREE update
                        'id' => $newPage->slugble->id,
                        'is_homepage' => 0,
                        'is_published' => $newPage->slugble->is_published,
                        'menu' => null,
                        'page_id' => ($newPage->isPage()) ? $newPage->slugble->id : null,
                        'post_id' => ($newPage->isPost()) ? $newPage->slugble->id : null,
                        'page_name' => $newPage->slugble->getPagename(),
                        'parent' => '#',
                        'slug_id' => $newPage->id,
                        'slug_name' => $newPage->slug_name,
                        'text' => $newPage->slugble->getPagename(),
                        'type' => 'internalpage',
                    ],
                ], 200);
            }

            return response()->json([
                    'status' => true,
                    'data' => [
                        'category_name' => $updateOption->slugble->getPrimaryCategory->getCategory->category_name,
                        'url' => url('/admin/wysiwyg/uikit/show/'.$updateOption->slug_prefix.'/'.$newSlug),
                        'msg' => 'Duplicate Success.',
                        // JSTREE update
                    'id' => $newPage->slugble->id,
                    'is_homepage' => 0,
                    'is_published' => $newPage->slugble->is_published,
                    'menu' => null,
                    'post_id' => $newPage->slugble->id,
                    'post_name' => $newPage->slugble->getPagename(),
                    'parent' => 'category'.$updateOption->slugble->getPrimaryCategory->getCategory->id,
                    'slug_id' => $newPage->id,
                    'slug_name' => $newPage->slug_name,
                    'slug_prefix' => $updateOption->slug_prefix,
                    'text' => $newPage->slugble->getPagename(),
                    'type' => 'default',
                        ],
                        ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage().':'.$e->getLine();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));

            return response()->json([
                    'status' => false,
                    'data' => [],
            ], 500);
        }
    }

    protected function updateOldSlug($slug, $newSlug)
    {
        try {
            DB::beginTransaction();

            if ($slug->slug_name == config('core.db.blog_index')) { // /blog > category > post
                $slug_prefix = $slug->slug_prefix.'/'.$slug->slug_name;
                $index = $slug->slug_prefix;
                $slugNmae = $slug->slug_name;

                //find post and category
                $allslug = CoreSlug::where(function ($query) use ($slug_prefix,$slugNmae) {
                    $query->where('slug_prefix', '=', $slug_prefix)
                    ->orwhere('slugble_type', '=', config('core.model.post'))
                    ->orwhere('slugble_type', '=', config('core.model.category'))
                    ->orwhere('slug_name', '=', $slugNmae);
                })->get();

                foreach ($allslug as $key => $val) {
                    //insert old_slug => change cate
                    $oldSlug = new CoreOldSlug();
                    $oldSlug->slug_id = $val['id'];
                    $oldSlug->slug_Name = $val['slug_name'];
                    $oldSlug->slug_prefix = $val['slug_prefix'];
                    $oldSlug->created_at = date('Y-m-d H:i:s');
                    $oldSlug->save();
                }
            }

            if ($slug->isCategory()) { // category > post
                $slug_prefix = $slug->slug_prefix.'/'.$slug->slug_name;
                $index = $slug->slug_prefix;
                $slugNmae = $slug->slug_name;

                //find post and category
                $CatPost = CoreSlug::where(function ($query) use ($slug_prefix,$slugNmae) {
                    $query->where('slug_prefix', '=', $slug_prefix)
                    ->where('slugble_type', '=', config('core.model.post'))
                    ->orwhere('slug_name', '=', $slugNmae);
                })->get();

                foreach ($CatPost as $key => $val) {
                    //insert old_slug => change cate
                    $oldSlug = new CoreOldSlug();
                    $oldSlug->slug_id = $val['id'];
                    $oldSlug->slug_Name = $val['slug_name'];
                    $oldSlug->slug_prefix = $val['slug_prefix'];
                    $oldSlug->created_at = date('Y-m-d H:i:s');
                    $oldSlug->save();
                }
            }

            if ($slug->isPost()) { // post
                $allPost = CoreSlug::where('slug_name', '=', $slug->slug_name)->get();

                foreach ($allPost as $key => $val) {
                    $oldSlug = new CoreOldSlug();
                    $oldSlug->slug_id = $val['id'];
                    $oldSlug->slug_name = $val['slug_name'];
                    $oldSlug->slug_prefix = $val['slug_prefix'];
                    $oldSlug->created_at = date('Y-m-d H:i:s');
                    $oldSlug->save();
                }
            }
            if ($slug->isPage()) { // post
                $oldSlug = new CoreOldSlug();
                $oldSlug->slug_id = $slug->id;
                $oldSlug->slug_Name = $slug->slug_name;
                $oldSlug->slug_prefix = $slug->slug_prefix;
                $oldSlug->save();
            }

            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));

            return response()->json([
                    'status' => false,
                    'data' => [
                        'msg' => $errorMsg,
                    ],
            ], 500);
        }
    }
}
