<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\View\View;
use Lib\Content\HeaderLib;
use Lib\Content\SavePageLib;
use Lib\Site\MenuLib;
use Lib\Util\RVLog;
use Rvsitebuilder\Core\Models\CoreHeader;
use Rvsitebuilder\Core\Models\CoreMenu;
use Rvsitebuilder\Core\Models\CorePage;
use Rvsitebuilder\Core\Models\CoreSetting;
use Rvsitebuilder\Core\Models\CoreSlug;
use Rvsitebuilder\Core\Traits\BaseRelation;
use Rvsitebuilder\Wysiwyg\Http\Requests\ResetHeaderRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\ResetTemplateRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveFooterStyleRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveHeaderStyleRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveImageRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveMenuStyleRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SavethumbnailRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveTopMenuStyleRequest;

class HeaderController extends Controller
{
    public function saveHeaderStyle(SaveHeaderStyleRequest $request)
    {
        try {
            $header_style = $request->input('header_style');
            $content_view = $request->input('content_view');
            $content_edit = $request->input('content_edit');
            $page_id = $request->input('page_id');

            if ($request->has('topmenu_style')) {
                $topmenu_style = $request->input('topmenu_style');
            }

            if ($request->has('menu_style')) {
                $menu_style = $request->input('menu_style');
            }

            $cdnImg = [];
            if ($request->has('cdn')) {
                $cdnImg = $request->input('cdn');
            }

            $header_id = DB::transaction(function () use ($header_style, $topmenu_style, $menu_style, $content_view, $content_edit, $page_id, $cdnImg) {
                $page = CorePage::find($page_id);
                $header = CoreHeader::find($page->header_id);
                $header->content_view = SavePageLib::downloadImgCdn($cdnImg, $content_view);
                $header->content_edit = SavePageLib::downloadImgCdn($cdnImg, $content_edit);
                $header->created_at = date('Y-m-d H:i:s');
                $header->save();

                SavePageLib::cloneHeaderCSS($header_style, null, null, null);

                $settingBanner = CoreSetting::firstOrNew(['key' => 'banner_style']);
                $settingBanner->value = $header_style.'.css';
                $settingBanner->save();

                if (isset($topmenu_style)) {
                    SavePageLib::cloneHeaderCSS(null, $topmenu_style, null, null);
                    $settingTopMenu = CoreSetting::firstOrNew(['key' => 'topmenu_style']);
                    $settingTopMenu->value = $topmenu_style.'.css';
                    $settingTopMenu->save();
                }

                if (isset($menu_style)) {
                    SavePageLib::cloneHeaderCSS(null, null, $menu_style, null);
                    $settingMenu = CoreSetting::firstOrNew(['key' => 'menu_style']);
                    $settingMenu->value = $menu_style.'-main.css';
                    $settingMenu->save();
                }

                return $header->id;
            });

            DB::commit();
            RVLog::debug(__METHOD__.':: header_id: '.$header_id);

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

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

    public function saveMenuStyle(SaveMenuStyleRequest $request)
    {
        try {
            //$page_id = $request->input ( 'page_id' );
            $menu_style = $request->input('menu_style');
            //$page = CorePage::find ( $page_id );

            SavePageLib::cloneHeaderCSS(null, null, $menu_style, null);

            CoreSetting::updateOrCreate(['key' => 'menu_style'], ['value' => $menu_style.'-main.css']);

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

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

    public function SaveFooterStyle(SaveFooterStyleRequest $request)
    {
        try {
            //$page_id = $request->input ( 'page_id' );
            $footer_style = $request->input('footer_style');
            //$page = CorePage::find ( $page_id );

            SavePageLib::cloneHeaderCSS(null, null, null, $footer_style);
            CoreSetting::updateOrCreate(['key' => 'footer_style'], ['value' => $footer_style.'.css']);

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

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

    public function saveTopMenuStyle(SaveTopMenuStyleRequest $request)
    {
        try {
            // $page_id = $request->input ( 'page_id' );
            $topmenu_style = $request->input('topmenu_style');
            //$page = CorePage::find ( $page_id );
            SavePageLib::cloneHeaderCSS(null, $topmenu_style, null, null);

            CoreSetting::updateOrCreate(['key' => 'topmenu_style'], ['value' => $topmenu_style.'.css']);

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

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

    public function myHeader()
    {
        $useHeader = CoreHeader::with('getPageUseHeader')->get();

        $leftMenu = CoreMenu::with([
                'getSlug',
                'children' => function ($Query) {
                    $Query->with([
                            'getSlug',
                            'children' => function ($subQuery) {
                                $subQuery->with('getSlug');
                            },
                    ]);
                },
        ])->where('location', '=', '1')->where('parent_id', '=', '0')->orderBy('priority', 'ASC')->get();

        $topMenu = CoreMenu::with([
                'getSlug',
                'children',
        ])->where('location', '=', '3')->where('parent_id', '=', '0')->orderBy('priority', 'ASC')->get();

        $rightMenu = CoreMenu::with([
                'getSlug',
                'children' => function ($Query) {
                    $Query->with([
                            'getSlug',
                            'children' => function ($subQuery) {
                                $subQuery->with('getSlug');
                            },
                    ]);
                },
        ])->where('location', '=', '2')->where('parent_id', '=', '0')->orderBy('priority', 'ASC')->get();

        $menu = new MenuLib();

        $headerArr = [];
        $textLeftMenu = $menu->getMenuLeft($leftMenu, []);
        $textRightMenu = $menu->getMenuRight($rightMenu, []);
        $textTopMenu = $menu->getMenuTop($topMenu, []);

        foreach ($useHeader as $key => $value) {
            $usePage = implode(',', $value->getPageUseHeader->pluck('page_name')->toArray());

            $logo = config('core.db.logo');
            $logo_mobile = config('core.db.logo_mobile');

            $header = $value->content_edit;
            $header = str_replace('[[LEFT_NAV]]', $textLeftMenu, $header);
            $header = str_replace('[[RIGHT_NAV]]', $textRightMenu, $header);
            $header = str_replace('[[TOP_NAV]]', $textTopMenu, $header);
            $header = str_replace('[[TEL]]', 'Tel: 02-123-456', $header);
            $header = str_replace('[[LOGO]]', '<img src="'.URL::to(Storage::url('images/'.$logo)).'" alt="">', $header);
            $header = str_replace('[[LOGO_MOBILE]]', '<img src="'.URL::to(Storage::url('images/'.$logo_mobile)).'" alt="">', $header);

            // TODO: revision image
            $header_thumbnail = ''; // default
            $file = public_path('storage').'/myheader/header/thumbnail/header_'.$value->id.'.png';
            if (is_file($file)) {
                $header_thumbnail = Storage::url('myheader/header/thumbnail/header_'.$value->id.'.png').'?v='.microtime();
                RVLog::debug('header_thumbnail = '.$header_thumbnail);
            }

            array_push($headerArr, (object) [
                    'icon' => '',
                    'html' => $header,
                    'use_page' => $usePage,
                    'header_id' => $value->id,
                    'header_thumbnail' => $header_thumbnail,
            ]);
        } // end header

        return View('wysiwyg::backend.header.myheader')->with('headerArr', $headerArr);
    }

    public function canvasHeader($header_id)
    {
        $this->logo = config('core.db.logo');
        $this->logo_mobile = config('core.db.logo_mobile');

        $useHeader = CoreHeader::findOrFail($header_id);

        $leftMenu = CoreMenu::with([
                'getSlug',
                'children' => function ($Query) {
                    $Query->with([
                            'getSlug',
                            'children' => function ($subQuery) {
                                $subQuery->with('getSlug');
                            },
                    ]);
                },
        ])->where('location', '=', '1')->where('parent_id', '=', '0')->orderBy('priority', 'ASC')->get();

        $topMenu = CoreMenu::with([
                'getSlug',
                'children',
        ])->where('location', '=', '3')->where('parent_id', '=', '0')->orderBy('priority', 'ASC')->get();

        $rightMenu = CoreMenu::with([
                'getSlug',
                'children' => function ($Query) {
                    $Query->with([
                            'getSlug',
                            'children' => function ($subQuery) {
                                $subQuery->with('getSlug');
                            },
                    ]);
                },
        ])->where('location', '=', '2')->where('parent_id', '=', '0')->orderBy('priority', 'ASC')->get();

        $menu = new MenuLib();

        $headerArr = [];
        $textLeftMenu = $menu->getMenuLeft($leftMenu, []);
        $textRightMenu = $menu->getMenuRight($rightMenu, []);
        $textTopMenu = $menu->getMenuTop($topMenu, []);

        $header = $useHeader->content_view;
        $header = str_replace('[[LEFT_NAV]]', $textLeftMenu, $header);
        $header = str_replace('[[RIGHT_NAV]]', $textTopMenu, $header);
        $header = str_replace('[[TOP_NAV]]', $textTopMenu, $header);
        $header = str_replace('[[TEL]]', 'Tel: 02-123-456', $header);
        $header = str_replace('[[LOGO]]', '<img src="'.URL::to(Storage::url('images/'.$this->logo->value)).'" alt="">', $header);
        $header = str_replace('[[LOGO_MOBILE]]', '<img src="'.URL::to(Storage::url('images/'.$this->logo_mobile->value)).'" alt="">', $header);

        RVLog::debug(__METHOD__.' Header_id:'.$header_id);

        return View('wysiwyg::backend.header.canvas-myheader')->with('header', $header)->with('header_id', $header_id);
    }

    /**
     * เรียก iframe.
     *
     * @param unknown $header_id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function makethumbnail($header_id)
    {
        return View('wysiwyg::backend.header.makethumbnail')->with('header_id', $header_id);
    }

    // เก็บไว้เผื่อใช้
    public function savethumbnail(SavethumbnailRequest $request)
    {
        RVLog::debug(__METHOD__);

        // $request->input('tagname');
        $imgdata = $request->input('imgdata');
        $header_id = $request->input('header_id');

        $imagedata = base64_decode($imgdata);
        $filename = ($header_id) ? $header_id : 'unknown';
        $filenameType = 'header_'.$header_id.'.png';
        $width = '250';

        $templateFolder = 'thumbnail';
        // path where you want to upload image
        $path = public_path('storage').'/myheader/header/thumbnail';

        if (false == is_dir($path)) {
            File::makeDirectory($path);
        }

        if (false == is_dir($path)) {
            die('no have '.$path);
        }

        $file = $path.'/original_preview.png';
        $dest = $path.'/'.$filenameType;
        $imageurl = Storage::url('/myheader/header/thumbnail'.'/'.$filenameType);

        RVLog::debug('===== '.$imageurl);

        File::put($file, $imagedata);
        // echo $imageurl;

        $desired_width = $width;
        $src = $file;
        // make thumb
        // make_thumb($file, $dest, $width);

        // TODO: อาจจะไม่มีมี gd ให้ระวัง

        // read the source image
        $source_image = imagecreatefrompng($src);
        // $source_image = imagecreatefromjpeg($src);

        $width = imagesx($source_image);
        $height = imagesy($source_image);

        // find the "desired height" of this thumbnail, relative to the desired width
        $desired_height = floor($height * ($desired_width / $width));

        // create a new, "virtual" image
        $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

        // copy source image at a resized size
        imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

        // create the physical thumbnail image to its destination
        // imagejpeg($virtual_image, $dest);
        imagepng($virtual_image, $dest);

        if (File::exists($file)) {
            // unlink original file
            File::delete($file);
        }

        return $imageurl;
    }

    public function saveImage(SaveImageRequest $request)
    {
        $imgdata = $request->input('imgdata');
        $header_id = $request->input('header_id');
        $small = $request->input('small');

        $imagedata = base64_decode($imgdata);
        $filename = $header_id.'.png';

        $filenameType = ('1' == $small) ? 'small_preview.png' : 'large_preview.png';
        $width = ('1' == $small) ? '350' : '400';

        // path where you want to upload image
        $path = public_path('storage').'/myheader/header/thumbnail';

        // make folder
        if (false == is_dir($path)) {
            File::makeDirectory($path);
        }

        // public_path('storage') . '/myheader/header/'
        // /storage/myheader/header/thumbnail
        if (false == is_dir($path)) {
            die('no have '.$path);
        }
        $file = $path.'/original_preview.png';
        $dest = $path.'/'.$filenameType;
        // $imageurl = 'https://cdn.netway.site/service/template/' . $templateFolder . '/' . $filenameType;

        File::put($file, $imagedata);
        // echo $imageurl;

        // make thumb
        self::make_thumb($file, $dest, $width);

        // delete original
        File::delete($file);
    }

    public static function make_thumb($src, $dest, $desired_width)
    {
        // read the source image
        $source_image = imagecreatefrompng($src);
        // $source_image = imagecreatefromjpeg($src);

        $width = imagesx($source_image);
        $height = imagesy($source_image);

        // find the "desired height" of this thumbnail, relative to the desired width
        $desired_height = floor($height * ($desired_width / $width));

        // create a new, "virtual" image
        $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

        // copy source image at a resized size
        imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

        // create the physical thumbnail image to its destination
        // imagejpeg($virtual_image, $dest);
        imagepng($virtual_image, $dest);
    }

    // ไม่ได้ใช้
    public function resetTemplate(ResetTemplateRequest $request)
    {
        try {
            $header_style = $request->input('header_style');
            $topmenu_style = $request->input('topmenu_style');
            $menu_style = $request->input('menu_style');
            $content_view = $request->input('content_view');
            $content_edit = $request->input('content_edit');

            DB::beginTransaction();
            $masterID = BaseRelation::getMasterHeaderId();

            $header = CoreHeader::where('id', $masterID)->update([
                'content_view' => SavePageLib::downloadImgCdn($cdnImg, $content_view),
                'content_edit' => SavePageLib::downloadImgCdn($cdnImg, $content_edit),
        ]);

            SavePageLib::cloneHeaderCSS($header_style, $topmenu_style, $menu_style, $footer_style);

            // Reset header_id all page to 0
            CorePage::where('header_id', '<>', $masterID)->update(['header_id' => 0]);

            $settingTopMenu = CoreSetting::firstOrNew(['key' => 'topmenu_style']);
            $settingTopMenu->value = $topmenu_style.'.css';
            $settingTopMenu->save();

            $settingMenu = CoreSetting::firstOrNew(['key' => 'menu_style']);
            $settingMenu->value = $menu_style.'-main.css';
            $settingMenu->save();

            $settingBanner = CoreSetting::firstOrNew(['key' => 'banner_style']);
            $settingBanner->value = $header_style.'.css';
            $settingBanner->save();
        } catch (\Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage().' at line:'.$e->getLine();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));
            exit;
        }
    }

    public function resetHeader(ResetHeaderRequest $request)
    {
        $slug_id = $request->input('slug_id');
        $slug = CoreSlug::find($slug_id);
        $header_id = $slug->slugble->header_id;

        if (!$slug->isHomepage()) {
            $slug->slugble->update(['header_id' => 0]);
            DB::table('core_header')->delete($header_id);
        }

        //return Header content
        if ($slug->isPost() || $slug->isCategory()) {
            $header = HeaderLib::getMasterHeaderBlog($slug);
        } else {
            $header = HeaderLib::getMasterHeader($slug);
        }

        return $header->content_edit;
    }
}
