<?php

// BACKEND CONTROLLER WITH EVENT-LISTENER

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use App\Helpers\Auth\RoleAndPermissionHelper;
use function GuzzleHttp\json_encode;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\File;
use Lib\Content\SidebarLib;
use Lib\Util\RVLog;
use Rvsitebuilder\Core\Http\Composers\Backend\ViewBackendComposer;
use Rvsitebuilder\Core\Http\Composers\Backend\WexViewComposer;
use Rvsitebuilder\Core\Models\CorePage;
use Rvsitebuilder\Core\Models\CoreSetting;
use Rvsitebuilder\Core\Models\CoreSlug;
use Rvsitebuilder\Email\Database\Seeds\EmailDatabaseSeeder;
use Rvsitebuilder\Email\Models\Email;
use Rvsitebuilder\Email\Models\EmailCategory;
use Rvsitebuilder\Email\Models\EmailForm;
use Rvsitebuilder\Email\Models\EmailHeader;

// amarin
class UikitController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $view = view('wysiwyg::backend.uikit.index')->renderSections()->with('editmode', true);

            return response()->json([
                'content' => $view['content'],
                'leftmenu' => $view['leftmenu'],
            ]);
        }

        return view('wysiwyg::backend.uikit.index')->with('editmode', true);
    }

    //TODO: รวม show กับ showBlog
    public function show(Request $request)
    {
        $template_id = CoreSetting::get('template_id', '');

        if ('' == $template_id) {
            return redirect('/admin/core/template');
        }
        $slug_prefix = null === $request->route()->slug_prefix ? '' : $request->route()->slug_prefix;
        $slug_name = $request->route()->slug_name;

        RVLog::debug('slug_prefix: '.$slug_prefix);
        RVLog::debug('slug_name: '.$slug_name);

        // display last edited page if not specific page
        if ('' == $slug_name) {
            $slug_name = self::lastPageModifier();
        }

        $editModeUri = empty($slug_prefix) ? $slug_name : $slug_prefix.'/'.$slug_name;
        $slug = CoreSlug::where('slug_prefix', '=', $slug_prefix)->where('slug_name', '=', $slug_name)->firstOrFail();

        $globalSetting = WexViewComposer::getGlobalSetting();

        // detect json folder
        if (true == self::notFoundJsonFolder()) {
            RVLog::debug('redirect(/admin/wysiwyg/uikit/show)');

            return redirect('/admin/wysiwyg/uikit/show');
        }

        $firstSave = CorePage::whereNotNull('updated_at')->limit(1)->count();

        //TODO: มาปรับ wex, mex ทีหลัง
        $currentData = self::_getCurrentData($slug);

        return view('wysiwyg::backend.uikit.show')
        ->with('editmode', true)
        ->with('viewmode', false)
        ->with('lastpagemodifier', $editModeUri)
        ->with('currentPageData', $currentData)
        ->with('globalSetting', json_encode($globalSetting))
        ->with('firstSave', $firstSave)
        ->with('site_brand', optional($globalSetting)->site_brand)
        ->with('clientdashboard', ViewBackendComposer::registerMyDashboard())
        ->with('supportWidgetSetting', ViewBackendComposer::registerSupportWidgetSetting())
        ->with('title', (!empty($slug->slugble->getSeo) ? $slug->slugble->getSeo->getMetaTag()->title : ''))->with('slugData', $slug)
        ->with('restrictedMember', RoleAndPermissionHelper::getFrontendRole());

        // if ไว้ไม่ให้ เครื่องอื่นพัง เพราะ System page ไม่มี Data SEO
    }

    public function showblog($category, $itemid, Request $request)
    {
        // display last edited page if not specific page
        if ('' == $itemid) {
            $itemid = self::lastPageModifier();
        }

        $slug = CoreSlug::where('slug_name', '=', $itemid)->first();

        $firstSave = CorePage::whereNotNull('updated_at')->limit(1)->count();

        // if page not found
        if (empty($slug)) {
            return abort(404);
        }

        $slug_name = $slug->slug_name;
        if ($slug->isPost()) {
            $slug_name = config('core.db.blog_index').'/'.$slug->slugble->getCategoryInPost[0]->getCategory->category_name.'/'.$slug->slug_name;
        }
        // echo $slug_name_post;

        $globalSetting = WexViewComposer::getGlobalSetting();

        // detect json folder
        if (true == self::notFoundJsonFolder()) {
            RVLog::debug('redirect(/admin/wysiwyg/uikit/show)');

            return redirect('/admin/wysiwyg/uikit/show');
        }

        $currentData = (object) [
            'page_name' => htmlentities($slug->slugble->getPagename()),
            'is_published' => $slug->slugble->is_published,
            'id' => $slug->slugble->id,
            'slug_id' => $slug->id,
            'slug_type' => $slug->slugble->getType(),
            'slug' => (object) [
                'slug_name' => $slug->slug_name,
                'slug_prefix' => $slug->slug_prefix,
            ],
            'is_homepage' => $slug->isHomepage(),
        ];

        // getPostData
        return view('wysiwyg::backend.uikit.show')
        ->with('editmode', true)->with('lastpagemodifier', $slug_name)
        ->with('currentPageData', $currentData)
        ->with('globalSetting', json_encode($globalSetting))
        ->with('firstSave', $firstSave)
        ->with('site_brand', optional($globalSetting)->site_brand)
        ->with('clientdashboard', ViewBackendComposer::registerMyDashboard())
        ->with('supportWidgetSetting', ViewBackendComposer::registerSupportWidgetSetting())
        // if ไว้ไม่ให้ เครื่องอื่นพัง เพราะ System page ไม่มี Data SEO
        ->with('title', (!empty($slug->slugble->getSeo) ? $slug->slugble->getSeo->getMetaTag()->title : ''))
        ->with('slugData', $slug);
    }

    //TODO: รวม show กับ showMail
    public function showemail(Request $request)
    {
        $email_id = $request->email_id;
        $email_type = $request->email_type;

        RVLog::debug('email_id: '.$email_id);
        RVLog::debug('email_type: '.$email_type);

        // display last edited page if not specific page
        if ('' == $email_id) {
            $email = self::lastEmailModifier();
        } else {
            ('emailcategory' == $email_type) ?
            $email = EmailCategory::find($email_id) : $email = Email::find($email_id);
        }

        $editModeUri = 'email/'.$email->id.'/'.$email->getType();
        $globalSetting = WexViewComposer::getGlobalSetting();

        $currentData = (object) [
            'page_name' => htmlentities($email->getEmailName()),
            'email_name' => htmlentities($email->getEmailName()),
            'email_subject' => isset($email->email_subject) ? htmlentities($email->email_subject) : '',
            'is_published' => $email->is_published,
            'id' => $email->id,
            'email_type' => $email->getType(),
            'email' => (object) [
                'email_path' => $editModeUri,
            ],
            'isForm' => ('emailcategory' == $email_type) ? false : EmailForm::where('email_id', $email->id)->exists(),
        ];

        $alleheader = EmailHeader::get();
        $emptyMaster = $alleheader->isEmpty();
        $emptyMasterView = (isset($alleheader[0]) && $alleheader[0]->content_view) ? 0 : 1;

        return view('email::backend.show')
        ->with('editmode', true)
        ->with('viewmode', false)
        ->with('lastemailmodifier', $editModeUri)
        ->with('currentPageData', $currentData)
        ->with('globalSetting', json_encode($globalSetting))
        ->with('emptyMaster', $emptyMaster)
        ->with('emptyMasterView', $emptyMasterView)
        ->with('site_brand', optional($globalSetting)->site_brand)
        ->with('clientdashboard', ViewBackendComposer::registerMyDashboard())
        ->with('supportWidgetSetting', ViewBackendComposer::registerSupportWidgetSetting())
        ->with('title', '')
        ->with('email', $email);
    }

    public function imageeditor(Request $request)
    {
        return view('wysiwyg::backend.uikit.imageeditor')
        ->with('wex', config('wysiwyg.wex'));
    }

    public static function _getCurrentData($slug = '')
    {
        $typeVal = '';
        $statusIcon = '';
        if ($slug->isPost()) {
            $customSidebar = $slug->slugble->isCustomSidebar();

            if (0 == $customSidebar) {
                $ParentSidebar = SidebarLib::getSidebarBlog($slug);

                $use_sidebar = $ParentSidebar->use_sidebar;
            } else {
                $use_sidebar = $slug->slugble->getSidebar->use_sidebar;
            }
        } else {
            $custom = $slug->slugble->getSidebar->use_sidebar;
            (0 != $custom ? $customSidebar = 1 : $customSidebar = 0);
            $use_sidebar = SidebarLib::getSidebar($slug)->use_sidebar;
        }

        $visWithParent = $slug->slugble->getVisibilityWithParent();
        $draft = $slug->slugble->is_published;

        //dd($slug);

        if( $slug->isPage() ){
             
                $pageName = $slug->slugble->getPagename ();

                if( $visWithParent['visibility'] == 0 ){
                    if( $slug->isHomepage() ){ 
                        $statusIcon =  "home-normal"; 
                        $typeVal = 'home';
                    } else {  
                        $statusIcon = "parent-normal";
                        $typeVal = 'default';
                        if($draft == 0){
                            $statusIcon = "parent-normal-draft";
                            $typeVal = 'draft';
                        }
                    }
                }
                if( $visWithParent['visibility'] == 1 ){
                    if( $slug->isHomepage() ){ 
                        $statusIcon =  "home-member"; 
                        $typeVal = 'home';
                    } else {  
                        $statusIcon = "parent-member";
                        $typeVal = 'default';
                        if($draft == 0){
                            $statusIcon = "parent-member-draft";
                            $typeVal = 'draft';
                        }
                    }
                }
                if( $visWithParent['visibility'] == 2 ){
                    if( $slug->isHomepage() ){ 
                        $statusIcon =  "home-specific"; 
                        $typeVal = 'home';
                    } else {  
                        $statusIcon = "parent-specific";
                        $typeVal = 'default';
                        if($draft == 0){
                            $statusIcon = "parent-specific-draft";
                            $typeVal = 'draft';
                        }
                    }
                }
        }
        if ($slug->isPost()) {
            $pageName = $slug->slugble->post_name;

            if( $visWithParent['visibility'] == 0 ){
                if( $slug->isHomepage() ){ 
                    $statusIcon =  "home-normal"; 
                    $typeVal = 'home';
                } else {
                    $statusIcon = "bpost-normal";
                    $typeVal = 'default';
                    if($draft == 0){
                        $statusIcon = "bpost-normal-draft";
                        $typeVal = 'draft';
                    }
                }
            }
            if( $visWithParent['visibility'] == 1 ){
                if( $slug->isHomepage() ){ 
                    $statusIcon =  "home-member"; 
                    $typeVal = 'home';
                } else {
                    $statusIcon = "bpost-member";
                    $typeVal = 'default';
                    if($draft == 0){
                        $statusIcon = "bpost-member-draft";
                        $typeVal = 'draft';
                    }
                }
            }
            if( $visWithParent['visibility'] == 2 ){
                if( $slug->isHomepage() ){ 
                    $statusIcon =  "home-specific"; 
                    $typeVal = 'home';
                } else {
                    $statusIcon = "bpost-specific";
                    $typeVal = 'default';
                    if($draft == 0){
                        $statusIcon = "bpost-specific-draft";
                        $typeVal = 'draft';
                    }
                }
            }
        }
        if ($slug->isCategory()) {
            $pageName = $slug->slugble->category_name;

            if (0 == $visWithParent['visibility']) {
                $statusIcon = 'bcate-normal';
                $typeVal = 'default';
                if (0 == $draft) {
                    $statusIcon = 'bcate-normal-draft';
                    $typeVal = 'draft';
                }
            }
            if (1 == $visWithParent['visibility']) {
                $statusIcon = 'bcate-member';
                $typeVal = 'default';
                if (0 == $draft) {
                    $statusIcon = 'bcate-member-draft';
                    $typeVal = 'draft';
                }
            }
            if (2 == $visWithParent['visibility']) {
                $statusIcon = 'bcate-specific';
                $typeVal = 'default';
                if (0 == $draft) {
                    $statusIcon = 'bcate-specific-draft';
                    $typeVal = 'draft';
                }
            }
        }
        if ($slug->isSystem()) {
            $pageName = $slug->slugble->getPagename();

            if (0 == $visWithParent['visibility']) {
                $statusIcon = 'system-normal';
                $typeVal = 'default';
                if (0 == $draft) {
                    $statusIcon = 'system-normal-draft';
                    $typeVal = 'draft';
                }
            }
            if (1 == $visWithParent['visibility']) {
                $statusIcon = 'system-member';
                $typeVal = 'default';
                if (0 == $draft) {
                    $statusIcon = 'system-member-draft';
                    $typeVal = 'draft';
                }
            }
            if (2 == $visWithParent['visibility']) {
                $statusIcon = 'system-specific';
                $typeVal = 'default';
                if (0 == $draft) {
                    $statusIcon = 'system-specific-draft';
                    $typeVal = 'draft';
                }
            }
        }

        $currentData = [];
        if (!empty($slug)) {
            $currentData = (object) [
                'page_name' => htmlentities($pageName),
                'is_published' => $slug->slugble->is_published,
                'id' => $slug->slugble->id,
                'page_id' => $slug->slugble->id,
                'slug_id' => $slug->id,
                'slug_type' => $slug->slugble->getType(),
                'slug' => (object) [
                    'slug_name' => $slug->slug_name,
                    'slug_prefix' => $slug->slug_prefix,
                ],
                'type' => $typeVal,
                'statusIcon' => $statusIcon,
                'is_homepage' => $slug->isHomepage(),
                'sidebar' => (object) [
                    'use_sidebar' => $use_sidebar,
                    'isCustom_sidebar' => $customSidebar,
                ],
            ];
        }
//         dd($currentData);
        return $currentData;
    }

    /**
     * detect public/storage/json.
     *
     * @param unknown $request
     */
    public static function notFoundJsonFolder()
    {
        $pathJson = public_path('storage/json');
        $freeImage = $pathJson.'/freeImages.json';
        $freebg = $pathJson.'/freeBackground.json';
        $myImages = $pathJson.'/myimages.json';
        $storeImages = $pathJson.'/storeimages.json';
        $tagFolder = $pathJson.'/tagfolder.json';
        $isFileMissing = false;

        $cdn_freeimgurl = config('rvsitebuildercms.cdn').'/templates/rvs_library/freeBackground.json';
        if(file_exists($freebg) && (md5_file($freebg) != md5_file($cdn_freeimgurl)) ){
            File::delete($freebg);
        }

        if (false == is_file($freeImage) || false == is_file($myImages) || false == is_file($storeImages) || false == is_file($tagFolder) || false == is_file($freebg)) {
            $isFileMissing = true;
        }

        if (false == is_dir($pathJson)) {
            RVLog::debug('make:: '.$pathJson);
            // make:: json
            File::makeDirectory($pathJson);
        }

        if (true == $isFileMissing) {
            RVLog::debug('isFileMissing:: ');
            // buildImagesJson file
            $obj = new CommonController();
            $obj->_buildImagesJson();
            $obj->_buildFreeImagesJson();
            $obj->defacementimage();

            return true;
        }

        return false;
    }

    public static function lastPageModifier()
    {
        $page = CorePage::limit(1)->orderBy('created_at', 'DESC')->orderBy('updated_at', 'DESC')->first();

        return $page->getSlug->slug_name;
    }

    public static function lastEmailModifier()
    {
        $email = Email::limit(1)->orderBy('created_at', 'DESC')->orderBy('updated_at', 'DESC')->first();
        if (empty($email)) {
            $email = EmailCategory::limit(1)->orderBy('created_at', 'DESC')->orderBy('updated_at', 'DESC')->first();
        }

        if (empty($email)) {
            $seeder = new EmailDatabaseSeeder();
            $seeder->run();
        }

        return $email;
    }
}
