<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\User;
use App\Menus;
use App\UserMenus;
//use App\UserMenus;
use App\Helpers\PasswordEncryptHelper;
use Auth;

class AdministratorsController extends AdminController
{

    public function __construct()
    {
        $this->middleware('auth');

        $this->breadcrumbs = $this->getBreadcrumbs();
        $this->breadcrumbs[1]['link'] = "admin/administrators";
        $this->breadcrumbs[1]['name'] = "Administrators";
    }

    public function index()
    {

        $model = User::whereIn("role", ["Administrator",'Manager'])->get();

        $data["pageHeader"] = false;
        $data["model"] = $model;
        $data["title"] = "Administrator";
        $data["SubTitle"] = "List";
        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/administrators/index', $data);
    }

    public function show($id)
    {

        $q = new User();

        $data['model'] = $q->find($id);
        //$data['userMenus'] = $data['model']->menus->where("parents_id", 0);
        $data["title"] = "Administrators";
        /* $menus = Menus::orderBy('name', 'asc')->get();
        $data["menus"] = $menus;
        $selectedMenus = array();
        if (count($data['userMenus']) > 0) {
        $i = 0;
        foreach ($data['userMenus'] as $val) {
        $menuModel = Menus::find($val->users_id);
        $childrenModel = $data['model']->menus->where("parents_id", $val->id)->where("users_id", $id);
        $childArray = array();
        $selectedMenus[$i]["id"] = $val->users_id;
        $selectedMenus[$i]["Name"] = $menuModel->name;
        if (count($childrenModel) > 0) {
        $j = 0;
        foreach ($childrenModel as $childModel) {
        $menuModel = Menus::find($childModel->users_id);
        $selectedMenus[$i]["children"][$j]["id"] = $menuModel->id;
        $selectedMenus[$i]["children"][$j]["Name"] = $menuModel->name;
        $childArray[$j]["id"] = $childModel->menus_id;
        $j++;
        }
        }
        $i++;
        }
        }
        */
        //$data["selectedMenus"] = $selectedMenus;

        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = $data['model']->first_name . " " . $data['model']->last_name;

        $data['breadcrumbs'] = $this->breadcrumbs;

        return view('admin/administrators/show', $data);
    }

    public function create()
    {
        $data["pageHeader"] = false;
        $data["model"] = new User();
        $data["title"] = "Administrators";
        $data["subTitle"] = "Create";
        $menus = Menus::orderBy('id', 'asc')->get();
        $data["menus"] = $menus;
        $data["assignMenus"] = "";
        $data["selectedMenus"] = array();

        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Create";

        $data['breadcrumbs'] = $this->breadcrumbs;
        return view('admin/administrators/create', $data);
    }

    public function save(Request $request)
    {

        $rules = [
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string'
        ];
        $input = $request->all();

        $message = [];
        $validator = Validator::make($input, $rules, $message);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {

            $input["password"] = PasswordEncryptHelper::encrypt_decrypt('encrypt', $request->password);
            $assignedOutput = $input["assigned_output"];
            $input["created_at"] = date("Y-m-d H:i:s");
            if (!isset($input["status"])) {
                $input["status"] = "0";
            }

            unset($input["_token"]);
            unset($input["assigned_output"]);
            $userId = User::insertGetId($input);

            $this->assignMenus($userId, $assignedOutput);

            \Session::flash('success', 'Administrators added successfully!');
            return redirect('admin/administrators');
        }
    }

    public function assignMenus($userId, $assignedOutput)
    {

        $menus = json_decode($assignedOutput, true);
        $parentPosition = 0;
        if (sizeof($menus) > 0) {
            foreach ($menus as $menu) {
                $parentMenu = array(
                    'parents_id' => 0,
                    'users_id' => $userId,
                    'menus_id' => $menu['id'],
                    'position' => $parentPosition
                );
                $parentMenuId = UserMenus::insertGetId($parentMenu);

                if (isset($menu['children']) && count($menu['children']) > 0) {
                    $chiledPosition = 0;
                    foreach ($menu['children'] as $children) {
                        $childMenu = array(
                            'parents_id' => $parentMenuId,
                            'users_id' => $userId,
                            'menus_id' => $children['id'],
                            'position' => $chiledPosition
                        );
                        UserMenus::insertGetId($childMenu);
                        $chiledPosition++;
                    }
                }
                $parentPosition++;
            }
        }
    }

    public function update($id, Request $request)
    {
        $rules = [
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'email' => 'required|string|email|unique:users,email,' . $id . ",id",
            //'Password' => 'required|string'
        ];
        $input = $request->all();

        $message = [];
        $validator = Validator::make($input, $rules, $message);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator->errors())->withInput();
        } else {

            $assignedOutput = $input["assigned_output"];
            //echo ''.$assignedOutput;
            unset($input["_token"]);
            unset($input["assigned_output"]);

            if (empty($input["password"])) {
                unset($input["password"]);
            } else {
                $input["password"] = PasswordEncryptHelper::encrypt_decrypt('encrypt', $request->password);
            }
            $input["updated_at"] = date("Y-m-d H:i:s");
            User::where('id', '=', $id)->update($input);
            UserMenus::where('users_id', '=', $id)->delete();

            $this->assignMenus($id, $assignedOutput);


            \Session::flash('message', 'Administrators updated successfully!');
            return redirect('admin/administrators');
        }
    }

    public function edit($id)
    {

        $q = new User();
        $data['model'] = $q->find($id);
        
        $data['userMenus'] = $data['model']->menus->where("parents_id", 0);
        $data["title"] = "Administrators";
        $menus = Menus::whereNotIn('id', UserMenus::select('menus_id')->where('users_id', $data['model']->id)->get()->pluck('menus_id'))->orderBy('id', 'asc')->get();
        $data["menus"] = $menus;

        $assignMenus = array();

        $selectedMenus = array();

        if (count($data['userMenus']) > 0) {
            $i = 0;
            foreach ($data['userMenus'] as $val) {
                $menuModel = Menus::find($val->menus_id);
                $jsonArray["id"] = $val->menus_id;
                $childrenModel = $data['model']->menus->where("parents_id", $val->id)->where("users_id", $id);
                $childArray = array();
                $selectedMenus[$i]["id"] = $val->menus_id;
                $selectedMenus[$i]["Name"] = $menuModel->name;
                if (count($childrenModel) > 0) {
                    $j = 0;
                    foreach ($childrenModel as $childModel) {
                        $menuModel = Menus::find($childModel->menus_id);
                        $selectedMenus[$i]["children"][$j]["id"] = $menuModel->id;
                        $selectedMenus[$i]["children"][$j]["Name"] = $menuModel->name;

                        $childArray[$j]["id"] = $childModel->menus_id;
                        $j++;
                    }
                    $jsonArray["children"] = $childArray;
                }
                $assignMenus[$i] = $jsonArray;
                unset($jsonArray["children"]);
                $i++;
            }
            $assignMenus = json_encode($assignMenus);
        } else {
            $assignMenus = "";
        }
        
        $data["selectedMenus"] = $selectedMenus;
        $data["assignMenus"] = $assignMenus;
        $this->breadcrumbs[2]['link'] = "#_";
        $this->breadcrumbs[2]['name'] = "Edit";

        $data['breadcrumbs'] = $this->breadcrumbs;

        return view('admin/administrators/edit', $data)->with('id', $id);
    }

    public function delete($id)
    {


        if ($id != 1) {
            User::where('id', $id)->delete();
            UserMenus::where('users_id', $id)->delete();
        }
        \Session::flash('error', 'Administrators deleted successfully!');
        return redirect('admin/administrators');
    }

}