<?php

namespace App\Http\Controllers\Webprofile\Backend;

use App\Models\Webprofile\Pages;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Webprofile\Menu;
use Validator;
use Uuid;
use Alert;
use App\Repositories\Webprofile\En\MenuRepository;
use Crypt;
use Auth;
use Statickidz\GoogleTranslate;

class MenuController extends Controller
{
    private $SOURCE = 'id';
    private $TARGET = 'en';

    public function __construct(MenuRepository $repoEn)
    {
        $this->repoEn = $repoEn;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $parent = Menu::where('status', '1')->whereNull('url')->whereIn('level', [1, 2])->pluck('name', 'id');
        $page = Pages::where('post_status', '1')->pluck('title', 'id');
        $data = Menu::with(['rEn'])->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')->get();
        $menu = [];

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

    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)
    {
        $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-1)->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-1)->first();
        }

        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');
    }

    public function menu_down($id)
    {
        $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+1)->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+1)->first();
        }

        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');
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @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);

            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)
    {
        $trans = new GoogleTranslate();
        $name = $trans->translate($this->SOURCE, $this->TARGET, $data['name']);

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

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

    public function newstorepage(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::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);

            $this->createEn($data, $save);

            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.
     *
     * @param  \App\Models\Menu  $menu
     * @return \Illuminate\Http\Response
     */
    public function edit(Menu $menu)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Menu  $menu
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Menu $menu)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Menu  $menu
     * @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');
        }
    }
}
