<?php

namespace App\Http\Controllers\AdminAuth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Yajra\Datatables\Datatables;
use App\Admin;

class AdminController extends Controller
{
    private $data = array(
        'route' => 'admin.admin.',
        'title' => 'Admin',
        'menu' => 'admin',
        'submenu' => 'admin',
    );
	
    public function __construct()
    {
        //$this->middleware('auth');
        $this->middleware(['permission:publish |admin']);
    }
	
    private function _validate($request, $id = null)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:admins,email'.(!empty($id)?','.$id:''),
            'school_name' => 'required',
            'address' => 'required',
            'start_date' => 'required',
            'end_date' => 'required',
            'password' => 'required_with:password_confirmation|max:255',
            'password_confirmation' => 'required_with:password|max:255|same:password',
            'image' => (!empty($id)?'mimes:jpeg,png,jpg,gif,svg':'required|mimes:jpeg,png,jpg,gif,svg'),
        ]);
        if ($id == null) {
            $this->validate($request, [
                'password' => 'required|max:255',
                'password_confirmation' => 'required|max:255|same:password',
            ]);
        }
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {
            $records = Admin::select('*');
			
            return Datatables::of($records)
              //return $this->dataTable->eloquent($records) 
                ->editColumn('created_at', function ($record) {
                    return $record->created_at->format(config('app.display_date'));
                })
                ->addColumn('role', function ($record) {
                    $roles = $record->getRoleNames()->toArray();
                    return !empty($roles)?implode(',', $roles):'-';
                })
                ->addColumn('status', function ($record) {
                    return '<input id="toggle-demo" value="'.$record->id.'" class="chk_status" data-toggle="toggle" data-on="Active" data-off="Inactive" data-size="small" data-onstyle="success"  type="checkbox" '.($record->status == "Active"?" checked":"" ).' >';
                })
                ->addColumn('action', function ($record) {
                    return '<a href="'.route($this->data['route'].'show',['id' =>$record->id]).'" class="btn btn-primary btn-sm" title="" data-toggle="tooltip" data-original-title="View"><i class="fa fa-eye-slash"></i></a>'.
                          '&nbsp;<a href="'.route($this->data['route'].'edit',['id' =>$record->id]).'" class="btn btn-info btn-sm" title="" data-toggle="tooltip" data-original-title="Edit"><i class="fa fa-pencil"></i></a>'.
                          '&nbsp;<button class="btn btn-danger btn-sm data-delete" data-id="'.$record->id.'" data-toggle="tooltip" data-original-title="Delete"><i class="fa fa-trash"></i></button>';
                })
                ->rawColumns(['status','action'])
                ->make(true);
        }

        $this->data['records'] = Admin::all();
        return view('admin.admin.index',$this->data);

    }

    public function create()
    {
        return view('admin.admin.create',$this->data);
    }


    public function store(Request $request)
    {
        $this->_validate($request);
        $input = $request->all();
		$input['image'] = $this->uploadFile($request, null, 'image', 'admin', false);
        $input['logo'] = $this->uploadFile($request, null, 'logo', 'admin', false);
        $input['password'] = bcrypt($request['password']);
        if(!empty($request->start_date))
        {
            $input['start_date'] = date('Y-m-d',strtotime($request->start_date));
        }
        else{
            $input['start_date'] = null;
        }
        if(!empty($request->end_date))
        {
            $input['end_date'] = date('Y-m-d',strtotime($request->end_date));
        }
        else{
            $input['end_date'] = null;
        }
        $record =  new Admin($input);

        $record->save();

        Session::flash('success', $this->data['title'].' inserted successfully.');
        return redirect()->route($this->data['route'].'index');
    }


    public function show($id)
    {
        $this->data['record'] = Admin::findOrFail($id);
        return view('admin.admin.show',$this->data);
    }


    public function edit($id)
    {
        $this->data['record'] = Admin::findOrFail($id);
        return view('admin.admin.create',$this->data);
    }


    public function update(Request $request, $id)
    {
        $record = Admin::findOrFail($id);
        /* Change Status Block */
        if ($request->ajax()) {
            $record->update($request->only(['status']));
            return \Illuminate\Support\Facades\Response::json(['result'=>'success']);
        }

        $this->_validate($request,$id);
        $input = $request->all();
        if(!empty($request->image))
        {
        $input['image'] = $this->uploadFile($request, null, 'image', 'admin', false);
        }
        else{
            unset($input['image']);
        }
        if(!empty($request->logo))
        {
        $input['logo'] = $this->uploadFile($request, null, 'logo', 'admin', false);
        }
        else{
            unset($input['logo']);
        }
        if(!empty($input['password'])){
            $input['password'] = bcrypt($request['password']);
        }else{
            unset($input['password']);
        }
        if(!empty($request->start_date))
        {
            $input['start_date'] = date('Y-m-d',strtotime($request->start_date));
        }
        else{
            $input['start_date'] = null;
        }
        if(!empty($request->end_date))
        {
            $input['end_date'] = date('Y-m-d',strtotime($request->end_date));
        }
        else{
            $input['end_date'] = null;
        }
        $record->syncRoles($request['role_id']);
        $record->update($input);

        Session::flash('info', $this->data['title'].' updated successfully.');
        return redirect()->route($this->data['route'].'index');
    }


    public function destroy($id)
    {
        $record = Admin::findOrFail($id);
        $record->delete();
        return \Illuminate\Support\Facades\Response::json(['result'=>'success','message'=>'Deleted Data successfully!']);
    }
}
