<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use App\Models\Branch;
use App\Models\Department;
use Spatie\Permission\Models\Permission;
use App\Models\Teammaster;
use App\Imports\ImportTeamMaster;
use App\Exports\ExportTeamMaster;
use Maatwebsite\Excel\Facades\Excel;
use Auth, DB, Mail, Validator, File, DataTables, Exception; 

class TeamMasterController extends Controller{
    /** construct */
        public function __construct(){
            $this->middleware('permission:team_master-create', ['only' => ['create']]);
            $this->middleware('permission:team_master-edit', ['only' => ['edit']]);
            $this->middleware('permission:team_master-view', ['only' => ['view']]);
            $this->middleware('permission:team_master-delete', ['only' => ['delete']]);
        }
    /** construct */

    /** index */
        public function index(Request $request){
            if($request->ajax()){
                //$data = Teammaster::all();
                 $data = Teammaster::select('Team_master.*','branches.name as branch_title', 'department.name as department_name')
                    ->leftJoin('branches','branches.id','=','Team_master.branch_name')
                    ->leftJoin('department','department.id','=','Team_master.department')
                    ->where('Team_master.status', 'active')
                    ->orderBy('id' , 'desc');
               
                return Datatables::of($data)
                        ->addIndexColumn()
                        ->addColumn('action', function($data){
                            $return = '<div class="btn-group">';

                             if(auth()->user()->can('team_master-view')){
                                $return .= '<a href="'.route('team_master.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-eye"></i>
                                            </a> &nbsp;';
                             }   
                            
                             if(auth()->user()->can('team_master-edit')){
                                $return .= '<a href="'.route('team_master.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                                <i class="fa fa-pencil"></i>
                                            </a> &nbsp;';
                             }   

                             if (auth()->user()->can('team_master-delete')) {
                                $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                                    <i class="fa fa-bars"></i>
                                                </a> &nbsp;
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                                                    <li><a class="dropdown-item" href="javascript:;" onclick="change_status(this);" data-status="deleted" data-id="' . base64_encode($data->id) . '">Deleted</a></li>
                                                </ul>';
                             }

                            $return .= '</div>';

                            return $return;
                        })

                        /*->editColumn('percentage', function ($data) {
                            return $data->percentage."%";
                        })*/
                        ->editColumn('status', function ($data) {
                            if ($data->status == 'active') {
                                return '<span class="badge badge-pill badge-success">Active</span>';
                            } else if ($data->status == 'inactive') {
                                return '<span class="badge badge-pill badge-warning">Inactive</span>';
                            } else if ($data->status == 'deleted') {
                                return '<span class="badge badge-pill badge-danger">Deleted</span>';
                            }
                        })

                        ->rawColumns(['action' ,'percentage' ,'status'])
                        ->filter(function ($query) {
                                if (request()->get('master_name', false)) {
                                    $query->where('Team_master.team_name', 'like', "%" . request()->get("master_name") . "%");
                                }
                                if (request()->get('department_name', false)) {
                                    $query->where('department.name', 'like', "%" . request()->get("department_name") . "%");
                                }
                                if (request()->get('branch_name', false)) {
                                    $query->where('branches.name', 'like', "%" . request()->get("branch_name") . "%");
                                }
                            })
                        ->make(true);
            }
            return view('team_master.index');
        }
    /** index */

    /** create */
        public function create(Request $request){
          //  return view('team_master.create');
             $data = Branch::where(['status' => 'active'])->get();
           
            return view('team_master.create')->with(['data' => $data]);

        }
    /** create */
    /**carvarient */
        public function carvarient(Request $request){ 
            $id = ($request->id);
            $data_new = Department::select('name')->where(['branch_id' => $id])->where(['status' => 'active'])->get()->toArray();

            $d_name =  $data_new[0]['name'];

            $d_name_arr = explode(',', $d_name);
           

            $data_new = Branch::select('name','id')->whereIn('id',$d_name_arr)->where(['status' => 'active'])->dd();get();


            $d_arr = [];
            foreach ($data_new as $value) {
                $d_data = [];
                $d_data['id'] = $value->id;
                $d_data['name'] = $value->name;
                $d_arr[] = $color_data;
                
            }
            
            $data = [];

            $data['department'] = $d_arr;
           
            return json_encode(array('status'=> true ,'data' => $data));
        }
    /** carvarient */
     /**carvarient */
        public function car_drop_down_get(Request $request){ 
            $id = ($request->id);

            $data = [];

            $Carvarient_arr = [];
            if($request->option_check == 'department'){
                $Carvarient = Department::where(['branch_id' => $request->id,'status' => 'active'])->get();
                
                foreach ($Carvarient as $value) {
                    $color_data = [];
                    $color_data['id'] = $value->id;
                    $color_data['name'] = $value->name;
                    $Carvarient_arr[] = $color_data;                    
                }  
            }
            $data['Carvarient_arr'] = $Carvarient_arr;  

            return json_encode(array('status'=> true ,'data' => $data));
        }
    /** carvarient */
    /** insert */
        public function insert(Request $request){
            if($request->ajax()) { return true; }


            $crud = [
                'team_name' => $request->team_name,
                'branch_name' => $request->branch_name,
                'department' => $request->department,
                'status' => 'active',
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => auth()->user()->id,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => auth()->user()->id
            ];

            
            $last_id = Teammaster::insertGetId($crud);

            if ($last_id) {
                return redirect()->route('team_master')->with(['success' => 'Record inserted successfully']);
            } else {
                return redirect()->back()->with(['error'=>'Faild to insert Record!'])->withInput();
            }
        
        }
    /** insert */

    /** view */
        public function view(Request $request){
            $id = base64_decode($request->id);
            $data = Teammaster::where(['id' => $id])->first();
            $Branch_data = Branch::where(['status' => 'active'])->get();  
            $department = Department::where(['status' => 'active'])->get(); 
            return view('team_master.view')->with(['data'=>$data, 'Branch_data' => $Branch_data, 'department' => $department]);
            //return view('team_master.view');
        }
    /** view */
    
    /** edit */
        public function edit(Request $request){
            $id = base64_decode($request->id);
            $data = Teammaster::where(['id' => $id])->first();
            $Branch_data = Branch::where(['status' => 'active'])->get();  
            $department = Department::where(['status' => 'active'])->get();  
            return view('team_master.edit')->with(['data'=>$data,'Branch_data' => $Branch_data, 'department' => $department]);
        }
    /** edit */

    /** update */
        public function update(Request $request){
            if($request->ajax()){ return true; }
            $id = $request->id;
            
            $crud = [
                'team_name' => $request->team_name,
                'branch_name' => $request->branch_name,
                'department' => $request->department,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => auth()->user()->id
            ];

            
            DB::enableQueryLog();
            $update = Teammaster::where(['id' => $id])->update($crud);
            // dd(DB::getQueryLog());
            if ($update){
                return redirect()->route('team_master')->with(['success' => 'Record updated successfully']);
            }else{
                return redirect()->back()->with(['error'=>'Faild to update Record!'])->withInput();
            }
        }
    /** update */

    /** change-status */
        public function change_status(Request $request){
            if (!$request->ajax()) { exit('No direct script access allowed'); }
            $id = base64_decode($request->id);
            
            $data = Teammaster::where(['id' => $id])->first();

            if (!empty($data)) {
                $update = Teammaster::where(['id' => $id])->update(['status' => $request->status, 'updated_at' => date('Y-m-d H:i:s'), 'updated_by' => auth('sanctum')->user()->id]);
                if ($update) {
                    return response()->json(['code' => 200]);
                } else {
                    return response()->json(['code' => 201]);
                }
            } else {
                return response()->json(['code' => 201]);
            }
           
        }
    /** change-status **/

      /** Import */
        public function import(Request $request){
            $import = Excel::import(new ImportTeamMaster(), $request->file('file'));    
            if($import){
                Excel::store(new ImportTeamMaster(), 'TeamMaster_'.Date('YmdHis').'.xlsx' ,'excel_import');
                return redirect()->route('team_master')->with('sucess' ,'File Imported Sucessfully');
            }
        }
    /** Import */

    /** Export */
        public function export(Request $request){
            $slug = $request->slug;
            $name = 'TeamMaster_'.Date('YmdHis').'.xlsx';
    
            try {
                return Excel::download(new ExportTeamMaster($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error', $e->getMessage());
            }
        }
    /** Export */
   
}
