<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin;
use App\Role;
use App\Department;

class AdminController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Admin $admin)
    {
        $this->authorize('view', $admin);

        $data = [];
        $data['admin']  = $admin;
        $data['admins'] = $admin::with('department')->get();

        return view('admin.admins.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Admin $admin)
    {
        $this->authorize('create', $admin);
        
        $data = [];
        $data['admin']          = $admin;
        $data['curentroles']    = $admin->roles()->pluck('id')->toArray();
        $data['create'] = 1;
        $data['roles']  = Role::all();
        $data['departments'] = Department::pluck('dep_name','dep_id');
        return view('admin.admins.form', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, Admin $admin)
    {
        $this->authorize('create', $admin);

        if( $request->isMethod('post') ) {

            $this->validate(
                $request,
                [
                    'name' => 'required|string|min:3',
                    'last_name' => 'required|string|min:3',
                    'email' => 'required|unique:admins|email',
                    'password' => 'required|min:6|confirmed',
                    'dep_id'   => 'required|integer|exists:departments,dep_id',
                    'phone' => 'nullable|string|min:9',
                    'status ' => 'in:0,1',
                    'is_super_admin ' => 'in:0,1',
                    'roles' => 'required|min:1',
                    'roles.*' => 'required|integer|exists:roles,id',

                ]
            );


            //'username' => 'required|string|min:3|unique:admins,username,'.$admin->id,



            $admin = new Admin();


            $admin->name           = $request->name;
            $admin->last_name      = $request->last_name;
            $admin->email          = $request->email;
            //$admin->username       = $request->username;
            $admin->password       = bcrypt($request->password);
            $admin->phone          = $request->phone;
            $admin->status         = $request->status;
            $admin->is_super_admin = $request->is_super_admin;
            $admin->dep_id         = $request->dep_id;


            $admin->save();

            $admin->roles()->sync($request->roles);

            return redirect()->route('admin.admin.index')->with('result', 'Dodat novi administrator: "' . $admin->full_name . '"');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Admin $admin)
    {
        $this->authorize('update', $admin);
        $data = [];
        $data['admin']          = $admin;
        $data['curentroles']   = $admin->roles()->pluck('id')->toArray();
        $data['create'] = 0;
        $data['roles']  = Role::all();
        $data['departments'] = Department::pluck('dep_name','dep_id');
        return view('admin.admins.form', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Admin $admin)
    {
        $this->authorize('update', $admin);



        if( $request->isMethod('PUT') ) {
            //dd($data);
            $this->validate(
                $request,
                [
                    'name' => 'required|string|min:3',
                    'last_name' => 'required|string|min:3',
                    'email' => 'nullable|email|unique:admins,email,'.$admin->id,
                    'newpassword' => 'nullable|min:6|confirmed',
                    'dep_id'   => 'required|integer|exists:departments,dep_id',
                    'phone' => 'nullable|string|min:9',
                    'status' => 'in:0,1',
                    'is_super_admin' => 'in:0,1',
                    'roles' => 'required|min:1',
                    'roles.*' => 'required|integer|exists:roles,id',


                ]
            );


            //'username' => 'required|string|min:3|unique:admins,username,'.$admin->id,

           



            $admin->name           = $request->name;
            $admin->last_name      = $request->last_name;
            $admin->email          = $request->email;
            //$admin->username       = $request->username;
            $admin->phone          = $request->phone;
            $admin->status         = $request->status;
            $admin->is_super_admin = $request->is_super_admin;
            $admin->dep_id         = $request->dep_id;

            if ($request->filled('newpassword')) {
                $admin->password       = bcrypt($request->newpassword);
            }

            $admin->save();

            $admin->roles()->sync($request->roles);

            //echo '<pre>'.print_r($request->all(),true).'</pre>'; exit;

            return redirect()->route('admin.admin.index')->with('result', 'Podaci o administratoru "' . $admin->full_name . '" su izmenjeni');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, Admin $admin)
    {
        //
        $this->authorize('delete', $admin);

        if( $request->isMethod('DELETE') ) {

            

            if(Admin::count() == 1){
                return redirect()->route('admin.admin.index')->with('error', 'Ne mozete obrisati jedinog korisnika');
            }

            if( $admin->is_super_admin ) {
                $remaining_superadmins = Admin::where('is_super_admin', 1)->where('id', '<>', $admin->id)->count();
                if($remaining_superadmins == 0){
                    return redirect()->route('admin.admin.index')->with('error', 'Ne mozete obrisati jedinog super admin-a');
                }
            }

            if( auth('admin')->user()->id == $admin->id ) {
                return redirect()->route('admin.admin.index')->with('error', 'Ne mozete sami obrisati sopstveni nalog');
            }

            $name = $admin->full_name;
            $admin->destroy($admin->id);
            return redirect()->route('admin.admin.index')->with('result', 'Nalog korisnika "'.$name.'" je obrisan');
        }
    }
}
