<?php

namespace App\Http\Controllers\Pages;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\Datatables\Datatables;
use App\Models\Group;
use App\Models\Detail;
use App\Models\Menu;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use Illuminate\Support\Facades\Validator;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Support\Facades\Auth;

class GroupController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $page_title = 'Data Group';
        $page_description = 'This is Data Group test page';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Group'],
            ['page' => 'users', 'title' => 'Data Group']
        ];
        return view('pages.group.index', compact('page_title', 'page_description', 'page_breadcrumbs'));
    }

    public function privilege(Request $request, $id)
    {
        $page_title = 'Detail Privilege';
        $page_description = 'This is Privilege management';
        $page_breadcrumbs = [
            ['page' => '#', 'title' => 'Group'],
            ['page' => 'users', 'title' => 'Data Group']
        ];
        $data = Group::find($id);
        return view('pages.privilege.index', compact('page_title', 'page_description', 'page_breadcrumbs', 'data'));
    }

    public function getPrivilege(Request $request, $id)
    {
        $data = DB::table('details')
            ->join('menus', 'menus.id', '=', 'details.idmenu')
            ->where('details.idgroup', '=', $id)
            ->select('details.*', 'menus.title')->get();
        $i = 0;
        $array = array();
        foreach ($data as $item) {
            $i++;
            $array[] = array(
                'no' => $i,
                'id' => $item->id,
                'group' => $item->idgroup,
                'menu' => $item->title,
                'create' => $item->hcreate,
                'edit' => $item->hedit,
                'delete' => $item->hdelete,
                'read' => $item->hread
            );
        }
        return Datatables::of($array)->make(true);
    }

    public function editPrivilage($id)
    {
        $data = DB::table('details')
            ->join('menus', 'menus.id', '=', 'details.idmenu')
            ->where('details.id', '=', $id)
            ->select('details.*', 'menus.title')->get();
        return view('pages.privilege.edit', compact('data'));
    }

    public function updatePrivilage(Request $request, $id)
    {
        $data = Detail::find($id);
        $idgroup = $data->idgroup;
        $data->update([
            'hcreate' => $request->hcreate,
            'hedit' => $request->hedit,
            'hdelete' => $request->hdelete,
            'hread' => $request->hread
        ]);
        Alert::success('Success!', 'Data has been update!');
        return redirect("/groups/$idgroup/privilege/");
    }

    public function deletePrivilage($id)
    {
        Detail::find($id)->delete();
    }

    public function getMenu($group)
    {
        $data = $group;
        return view('popup.privilege', compact('data'));
    }

    public function getDataMenu($group)
    {
        $data = DB::table('menus')
            ->whereNotExists(function ($query) use ($group) {
                $query->select(DB::raw(1))
                    ->from('details')
                    // ->whereRaw('groups.idgroup = details.idgroup')
                    ->whereRaw('menus.id = details.idmenu')
                    ->whereNotExists(function ($res) use ($group) {
                        $res->select(DB::raw(1))
                            ->from('groups')
                            ->whereRaw('groups.idgroup = details.idgroup')
                            ->where('groups.idgroup', '!=', $group);
                    });
            })->orderBy('parent', 'asc')
            ->get();
        $array = array();
        $i = 0;
        foreach ($data as $item) {
            $i++;
            $array[] = array(
                'no' => $i,
                'menu' => $item->id,
                'title' => $item->title
            );
        }
        return Datatables::of($array)->make(true);
    }

    public function storeGrpMenu(Request $request)
    {
        Detail::create([
            'idgroup' => $request->group,
            'idmenu' => $request->idmodule,
            'hcreate' => $request->hcreate,
            'hread' => $request->hread,
            'hedit' => $request->hedit,
            'hdelete' => $request->hdelete
        ]);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|max:255',
            'slug' => 'required|max:255',
        ]);
        $id = IdGenerator::generate(['table' => 'groups', 'field' => 'idgroup', 'length' => 7, 'prefix' => 'GROUP']);
        Group::create([
            'idgroup' => $id,
            'title' => ucfirst($request->title),
            'slug' => strtolower(str_replace(' ', '-', $request->slug)),
        ]);
        Helper::Activity('groups', $id, 'CREATE');
        Alert::success('Success!', 'Data has been saved!');
        return redirect('groups');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $group = DB::table('groups')->get();
        $i = 0;
        $array = array();

        foreach ($group as $data) {
            $i++;
            $array[] = array(
                'no' => $i,
                'title' => $data->title,
                'slug' => $data->slug,
                'created_at' => $data->created_at,
                'updated_at' => $data->updated_at,
                'idgroup' => $data->idgroup
            );
        }
        return Datatables::of($array)->make(true);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Group::find($id);
        return view('pages.group.edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $bank = Group::find($id)
            ->update([
                'title' => $request->title,
                'slug' => $request->slug,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        Helper::Activity('groups', $id, 'UPDATE');
        Alert::success('Success!', 'Data has been update!');
        return redirect('groups');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Helper::Activity('groups', $id, 'DELETE');
        Group::find($id)->delete();
    }
}
