<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;

use DataTables;
use App\Models\Admin\Menu;
use Illuminate\Http\Request;
use App\Traits\Permissions_trait;
use Illuminate\Support\Facades\Auth;
use Spatie\Activitylog\Contracts\Activity;
class MenuController extends Controller
{
    var $url,$Model;
    use Permissions_trait;

    public function __construct()
    {
        $this->middleware('auth');
        $this->url = request()->path();
    }
    public function index(Request $request)
    {
        if (!$this->Permissions_trait('view', $this->url)) :
            abort(403, 'Permission denied..');
        endif;
        if ($request->ajax()) {
            $data = Menu::all()->sortByDesc("id");
            // dd($data);
            return Datatables::of($data)
                ->addIndexColumn()
                ->setRowId(function ($row) {
                    return $row->id;
                })
                ->addColumn('label', function ($row) {
                    if (Auth::user()->locale == "en") {
                        $name = $row->value_en;
                    } else {
                        $name = $row->value_ar;
                    }
                    return $name;
                })
                ->addColumn('Parent',function($row){
                    if(!$row->parent_id == 0):
                        $parent = Menu::find($row->parent_id)->menu_name;
                        return "<span class='badge bg-primary'>".$parent.'</span>';
                    else:
                    return "<span class='badge bg-secondary'>Parent</span>";
                    endif;
                })
                ->addColumn('Type',function($row){
                    switch ($row->type) {
                        case '1':
                            return '<span class="badge bg-primary">Main</span>';
                            break;
                        case '2':
                            return '<span class="badge bg-info">Side</span>';
                            break;
                        case '3':
                            return '<span class="badge bg-warning">Footer</span>';
                            break;


                        default:
                            return '<span class="badge bg-danger">Setting</span>';
                            break;
                    }
                })
                ->addColumn('status', function ($row) {
                    $checked = "";
                    if ($row->status == '1') {
                        $checked = "checked";
                    }
                    $swtich = "";
                    if ($this->Permissions_trait('update', 'menu')) :
                        $swtich .= '<label class="switch" for="checkbox' . $row->id . '">
                                <input class="state_switch" type="checkbox" id="checkbox' . $row->id . '" value="' . $row->id . '" ' . $checked . ' />
                                <div class="slider round"></div>
                            </label> ';
                        return $swtich;
                    endif;
                })
                ->addColumn('action', function ($row) {
                    $btn = "";
                    if($this->Permissions_trait('update','menu')):
                        $btn .= '<button onclick="edit_menu(' . $row->id . ');" id="edit_sub_cat" class="btn btn-warning btn-xs">' . trans('admin.Edit') . '</button>';
                    endif;
                    if ($this->Permissions_trait('delete', 'menu')) :
                        $btn .= ' <button class="btn btn-xs btn-danger btn-delete" value="' . $row->id . '">' . trans('admin.Delete') . '</button>';
                    endif;
                    return $btn;
                })
                ->rawColumns(['action', 'status','Type','Parent'])
                ->make(true);
        }
        // dd($data);
        activity('Menus index')->causedBy(Auth::user())
            ->performedOn(new Menu())
            // ->withProperties(['old'  => [], 'modified' => $data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log(Auth::user()->name.' Visited Menu index page');
        return view('admin/menu.index');
    }

    public function status_change(Request $request)
    {
        $id = $request->id;
        $menu = Menu::find($id);
        $status  = ($menu->status == '1') ? '0' : '1';
        $record = Menu::where('id',$id)->update(['status' => $status]);
        if ($record) :
            // Add activity logs
                activity('Menu status changed')
                    ->performedOn(new Menu)
                    ->causedBy(Auth::user()->id)
                    ->withProperties(['old'  => ['status' => $menu->status], 'modified' => ['status' => $status]])
                    ->log('Menu Status changed to '.$status.' by ' . Auth::user()->name);
            return ['text' => trans('admin.Updated_successfully'), 'cls' => 'success'];
        endif;
    }

    public function addMenu()
    {
        $parentMenu = Menu::where('parent_id',0)->get();
         return view('admin.menu.add')->with(['parent_menu' => $parentMenu]);
    }


    public function store(Request $request)
    {
        $data = [
            'menu_name' => $request->name,
            'menu_ar' => $request->name_ar,
            'route' => $request->route,
            'type' => $request->type,
			'icon' => $request->icon,
			'order_by' => $request->order_by,
            'parent_id' => $request->parent_id ? $request->parent_id : 0,
            'created_at' => date('Y-m-d H:i:s')
        ];
        // dd($data);
        $add = Menu::insert($data);
        if($add):
           activity('Menu Data Added')
           ->causedBy(Auth::user())
            ->performedOn(new Menu())
            ->withProperties(['old'  => [], 'modified'=>$data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Menu Created by ' . Auth::user()->name);
            return ['text' => trans('admin.Updated_successfully'), 'cls' => 'success'];
        else:
            return ['text' => trans('admin.Not_updated_successfully'), 'cls' => 'error'];
        endif;
    }

    public function edit($id)
    {
       $data = Menu::find($id);
       $parentMenu = Menu::where('parent_id', 0)->get();
       $types =[
            '1' => 'Main',
            '2' => 'Side',
            '3' => 'Footer',
            '4' => 'Setting',
       ];
        activity('Menu Edit page visited')
        ->causedBy(Auth::user())
        ->performedOn($data)
        // ->withProperties(['old'  => [], 'modified'=>$data])
        ->tap(function (Activity $activity) {
            $activity->route_link = $this->url;
        })->log( Auth::user()->name.'user visit Edit menu  Page of Menu id = '.$id);
       return view('admin.menu.edit')->with(['data' => $data,'types' => $types,'parent_menu' => $parentMenu]);
    }

    public function update(request $request)
    {
        $data = [
            'menu_name' => $request->name,
            'menu_ar' => $request->name_ar,
            'route' => $request->route,
            'type' => $request->type,
			'icon' => $request->icon,
			'order_by' => $request->order_by,
            'parent_id' => $request->parent_id ? $request->parent_id : 0,
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        $oldData = Menu::find($request->id);
        $update =  Menu::where('id',$request->id)->update($data);
        if ($update) :
            activity('Menu Data Updated Page visited')
            ->causedBy(Auth::user())
                ->performedOn(new Menu())
                ->withProperties(['old'  => $oldData, 'modified' => $data])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Menu Data Updated by ' . Auth::user()->name);
            return ['text' => trans('admin.Updated_successfully'), 'cls' => 'success'];
        else :
            return ['text' => trans('admin.Not_updated_successfully'), 'cls' => 'error'];
        endif;
    }

    public function destroy($id)
    {
        Menu::where('id',$id)->delete();
        return ['text' => trans('admin.Updated_successfully'), 'cls' => 'success'];

    }
}
