<?php

namespace App\Http\Controllers\Webprofile\Backend;

use Alert;
use App\Http\Controllers\Controller;
use App\Models\Webprofile\Menu;
use App\Models\Webprofile\Pages;
use App\Repositories\Webprofile\De\MenuRepository as DeMenuRepository;
use App\Repositories\Webprofile\En\MenuRepository;
use App\Repositories\Webprofile\MenuRepository as WebprofileMenuRepository;
use App\Repositories\Webprofile\Sa\MenuRepository as SaMenuRepository;
use App\Repositories\Webprofile\Zh\MenuRepository as ZhMenuRepository;
use Auth;
use Crypt;
use Illuminate\Http\Request;
use Statickidz\GoogleTranslate;
use Validator;

class MenuController extends Controller
{
    private $SOURCE = 'id';
    private $TARGET = 'en';
    private $TARGETDE = 'de';
    private $TARGETSA = 'ar';
    private $TARGETZH = 'zh';

    public function __construct(
        MenuRepository $repoEn,
        WebprofileMenuRepository $repo,
        DeMenuRepository $repoDe,
        SaMenuRepository $repoSa,
        ZhMenuRepository $repoZh
    ) {
        $this->repoEn = $repoEn;
        $this->repoDe = $repoDe;
        $this->repoSa = $repoSa;
        $this->repoZh = $repoZh;
        $this->repo = $repo;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $parent = Menu::where('status', '1')->whereNull('url')->whereIn('level', [1, 2, 3])->pluck('name', 'id');
        $page = Pages::orderBy('title', 'asc')->pluck('title', 'id');
        $data = Menu::with(['rEn', 'rDe', 'rSa', 'rZh'])->select('id', 'parent', 'name', 'url', 'level', 'urutan')->orderby('level', 'asc')->orderby('urutan', 'asc')->get();

        $arr = $this->build_menu();

        return view('webprofile.backend.menu.index', compact('parent', 'page', 'data', 'arr'))->withTitle('Menu');
    }

    public function build_menu()
    {
        $data = Menu::select('id', 'parent', 'name', 'url', 'level', 'urutan')->where('level', '1')->orderby('urutan', 'asc')->with('rEn', 'rChild')->get()->toArray();

        return $data;
    }

    public function menu_has_child($parentid)
    {
        $data = Menu::where('parent', $parentid)->count();

        if ($data > 0) {
            return true;
        } else {
            return false;
        }
    }

    public function menu_get_child($parentid)
    {
        $cdata = Menu::select('id', 'parent', 'name', 'url', 'level', 'urutan')->where('parent', $parentid)->orderby('urutan', 'asc')->get();

        $i = 0;
        $cmenu = [];
        foreach ($cdata as $citem) {
            $cmenu[$i]['id'] = $citem->id;
            $cmenu[$i]['parent'] = $citem->parent;
            $cmenu[$i]['name'] = $citem->name;
            $cmenu[$i]['url'] = $citem->url;
            $cmenu[$i]['level'] = $citem->level;
            $cmenu[$i]['urutan'] = $citem->urutan;
            if ($this->menu_has_child($citem->parent)) {
                $cmenu[$i]['child'] = $this->menu_get_child($citem->id);
            }
            ++$i;
        }

        return $cmenu;
    }

    public function menu_up($id, $urut = 1)
    {
        $cur_menu = Menu::where('id', Crypt::decrypt($id))->first();
        if ($cur_menu->parentlevel == null) {
            $up_menu = Menu::where('level', $cur_menu->level)->where('urutan', (int) $cur_menu->urutan - $urut)->first();
        }
        if ($cur_menu->parentlevel != null) {
            $up_menu = Menu::where('parent', $cur_menu->parent)->where('level', $cur_menu->level)->where('urutan', (int) $cur_menu->urutan - $urut)->first();
        }

        if ($up_menu) {
            Menu::where('id', Crypt::decrypt($id))->update([
                'urutan' => $up_menu->urutan,
                'userid_created' => Auth::user()->name,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            Menu::where('id', $up_menu->id)->update([
                'urutan' => $up_menu->urutan + 1,
                'userid_created' => Auth::user()->name,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            return redirect()->route('menu.index');
        }

        return $this->menu_up($id, $urut + 1);
    }

    public function menu_down($id, $urut = 1)
    {
        $cur_menu = Menu::where('id', Crypt::decrypt($id))->first();
        if ($cur_menu->parentlevel == null) {
            $up_menu = Menu::where('level', $cur_menu->level)->where('urutan', (int) $cur_menu->urutan + $urut)->first();
        }
        if ($cur_menu->parentlevel != null) {
            $up_menu = Menu::where('parent', $cur_menu->parent)->where('level', $cur_menu->level)->where('urutan', (int) $cur_menu->urutan + $urut)->first();
        }

        if ($up_menu) {
            Menu::where('id', Crypt::decrypt($id))->update([
                'urutan' => $up_menu->urutan,
                'userid_created' => Auth::user()->name,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            Menu::where('id', $up_menu->id)->update([
                'urutan' => $up_menu->urutan - 1,
                'userid_created' => Auth::user()->name,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            return redirect()->route('menu.index');
        }

        return $this->menu_down($id, $urut + 1);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->except('_token');
        $validator = Validator::make($data, Menu::$rules, Menu::$errormessage);

        if ($validator->fails()) {
            $errormessage = $validator->messages();

            return redirect()->route('menu.index')
            ->withErrors($validator)
            ->withInput();
        } else {
            if ($request->input('parent') == null || $request->input('parent') == '') {
                $parentlevel = null;
                $level = 1;
            } else {
                $getlevelparent = Menu::where('id', $request->input('parent'))->first()->level;
                $parentlevel = $getlevelparent;
                $level = (int) $getlevelparent + 1;
            }

            $urutan = Menu::where('level', $level)->where('parent', $request->input('parent'))->max('urutan');

            $data['status'] = 1;
            $data['level'] = $level;
            $data['parentlevel'] = $parentlevel;
            $data['urutan'] = $urutan + 1;
            $data['userid_created'] = Auth::user()->name;
            $data['userid_updated'] = Auth::user()->name;

            $save = Menu::create($data);

            $this->createEn($data, $save);
            $this->createDe($data, $save);
            $this->createSa($data, $save);
            $this->createZh($data, $save);

            Alert::success('Data berhasil disimpan')->persistent('Ok');

            $successmessage = 'Proses Tambah Menu Berhasil !!';

            return redirect()->route('menu.index')->with('successMessage', $successmessage);
        }
    }

    private function createEn($data, $menu, $translate = 1)
    {
        if ($translate == 1) {
            $trans = new GoogleTranslate();
            $name = $trans->translate($this->SOURCE, $this->TARGET, $data['name']);
        } else {
            $name = $data['name'];
        }

        $dataEn['menu_id'] = $menu->id;
        $dataEn['name'] = $name;

        $this->repoEn->store($dataEn);
    }

    private function createDe($data, $menu, $translate = 1)
    {
        if ($translate == 1) {
            $trans = new GoogleTranslate();
            $name = $trans->translate($this->SOURCE, $this->TARGETDE, $data['name']);
        } else {
            $name = $data['name'];
        }

        $dataDe['menu_id'] = $menu->id;
        $dataDe['name'] = $name;

        $this->repoDe->store($dataDe);
    }

    private function createSa($data, $menu, $translate = 1)
    {
        if ($translate == 1) {
            $trans = new GoogleTranslate();
            $name = $trans->translate($this->SOURCE, $this->TARGETSA, $data['name']);
        } else {
            $name = $data['name'];
        }

        $dataSa['menu_id'] = $menu->id;
        $dataSa['name'] = $name;

        $this->repoSa->store($dataSa);
    }

    private function createZh($data, $menu, $translate = 1)
    {
        if ($translate == 1) {
            $trans = new GoogleTranslate();
            $name = $trans->translate($this->SOURCE, $this->TARGETZH, $data['name']);
        } else {
            $name = $data['name'];
        }

        $dataZh['menu_id'] = $menu->id;
        $dataZh['name'] = $name;

        $this->repoZh->store($dataZh);
    }

    public function storepage(Request $request)
    {
        $data = $request->except('_token');
        $validator = Validator::make($data, Menu::$rules, Menu::$errormessage);

        if ($validator->fails()) {
            $errormessage = $validator->messages();

            return redirect()->route('menu.index')
            ->withErrors($validator)
            ->withInput();
        } else {
            if ($request->input('parentpage') == null || $request->input('parentpage') == '') {
                $parentlevel = null;
                $level = 1;
            } else {
                $getlevelparent = Menu::where('id', $request->input('parentpage'))->first()->level;
                $parentlevel = $getlevelparent;
                $level = (int) $getlevelparent + 1;
            }

            $urutan = Menu::where('level', $level)->where('parent', $request->input('parentpage'))->max('urutan');

            $page = Pages::with(['rEn'])->where('id', $request->input('page'))->first();

            $data['name'] = $page->title;
            $data['level'] = $level;
            $data['parentlevel'] = $parentlevel;
            $data['urutan'] = $urutan + 1;
            $data['parent'] = $request->input('parentpage');
            $data['url'] = '/page/'.$page->slug;
            $data['status'] = 1;
            $data['userid_created'] = Auth::user()->name;
            $data['userid_updated'] = Auth::user()->name;

            $save = Menu::create($data);

            $data['name'] = $page->rEn ? $page->rEn->title : null;
            $this->createEn($data, $save, 'notTranslate');

            $data['name'] = $page->rDe ? $page->rDe->title : null;
            $this->createDe($data, $save, 'notTranslate');

            $data['name'] = $page->rSa ? $page->rSa->title : null;
            $this->createSa($data, $save, 'notTranslate');

            $data['name'] = $page->rZh ? $page->rZh->title : null;
            $this->createZh($data, $save, 'notTranslate');

            Alert::success('Data berhasil disimpan')->persistent('Ok');

            $successmessage = 'Proses Tambah Menu Berhasil !!';

            return redirect()->route('menu.index')->with('successMessage', $successmessage);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param \App\Models\Menu $menu
     *
     * @return \Illuminate\Http\Response
     */
    public function show(Menu $menu)
    {
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $id = Crypt::decrypt($id);
        $setting = webprofilesetting();
        $data = $this->repo->findId($id, ['rEn', 'rDe', 'rSa', 'rZh']);

        $data = [
            'data' => $data,
            'setting' => $setting,
        ];

        return view('webprofile.backend.menu.edit', $data)->withTitle(trans('feature.edit_menu'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->except(['_token', 'id']);

        $data['name'] = $data['titleiid'];
        $menu = $this->repo->findId($id, ['rEn', 'rDe', 'rSa', 'rZh']);
        $this->repo->update($data, $menu);

        if ($menu->rEn) {
            $dataEn['name'] = $data['titleien'];
            $menuEn = $this->repoEn->findId($menu->rEn->id);
            $this->repoEn->update($dataEn, $menuEn);
        } else {
            $dataEn['menu_id'] = $menu->id;
            $dataEn['name'] = $data['titleien'];

            $this->repoEn->store($dataEn);
        }

        if ($menu->rDe) {
            $dataDe['name'] = $data['titleide'];
            $menuDe = $this->repoDe->findId($menu->rDe->id);
            $this->repoDe->update($dataDe, $menuDe);
        } else {
            $dataDe['menu_id'] = $menu->id;
            $dataDe['name'] = $data['titleide'];

            $this->repoDe->store($dataDe);
        }

        if ($menu->rSa) {
            $dataSa['name'] = $data['titleisa'];
            $menuSa = $this->repoSa->findId($menu->rSa->id);
            $this->repoSa->update($dataSa, $menuSa);
        } else {
            $dataSa['menu_id'] = $menu->id;
            $dataSa['name'] = $data['titleisa'];

            $this->repoSa->store($dataSa);
        }

        if ($menu->rZh) {
            $dataZh['name'] = $data['titleizh'];
            $menuZh = $this->repoZh->findId($menu->rZh->id);
            $this->repoZh->update($dataZh, $menuZh);
        } else {
            $dataZh['menu_id'] = $menu->id;
            $dataZh['name'] = $data['titleizh'];

            $this->repoZh->store($dataZh);
        }

        return redirect()->route('menu.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            $ceklevel = Menu::where('id', Crypt::decrypt($id))->first();
            $level = $ceklevel->level;

            Menu::where('id', Crypt::decrypt($id))->delete(Crypt::decrypt($id));
            $tataurut = Menu::where('level', $level)->orderBy('urutan', 'asc')->get();
            $urut = 1;

            foreach ($tataurut as $value) {
                Menu::where('id', $value->id)->update([
                    'urutan' => $urut++,
                    'userid_created' => Auth::user()->name,
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }

            return redirect()->route('menu.index');
        } catch (\Exception $id) {
            return redirect()->route('menu.index');
        }
    }
}
