<?php

namespace App\Http\Controllers\Administrator\Construction;

use App\ConstructionModel\SubTaskWorkingModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DataTables;
use App\ConstructionModel\TaskWorkingGroupModel;
use App\SubCategoryModel;
use DB;
use Auth;
use Illuminate\Support\Facades\Crypt;
use Gate;

class TaskWorkingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct(){
        $this->middleware('permission:Construction-Work-Group-Type-List',['only'=>['index','get_data_index']]);
        $this->middleware('permission:Construction-Work-Group-Type-Create',['only'=>['create','store']]);
        $this->middleware('permission:Construction-Work-Group-Type-Edit',['only'=>['edit','update']]);
        $this->middleware('permission:Category-Task-List',['only'=>['index_sub_task']]);
        $this->middleware('permission:Work-Task-List',['only'=>['list_task_contractor']]);
        $this->middleware('permission:Category-Responsibilities-List',['only'=>['index_category_responsibilities']]);
        $this->middleware('permission:Work-Responsibilities-List',['only'=>['list_responsibilities_contractor']]);
    }
    public function index()
    {
        return view("administrator.construction.task-working.index");
    }
    public function get_data_index(Request $request)
    {
        $work_code = $request->work_code;
        $work_name = $request->work_name;
        $data = TaskWorkingGroupModel::when(request('work_code'),function($query) use ($work_code){
            $query->where("code",$work_code);
        })
        ->when(request('work_name'),function($query) use($work_name){
            $query->where("name",$work_name);
        })
        ->get();
        return  Datatables::of($data)
            ->setRowId('id')
            ->addIndexColumn()
            ->editColumn('type_of_building',function($data)
            {
                return $data->sub_category_name;
            })
            ->addColumn('action', function($data) {
                $button ="";
                if(Gate::check('Construction-Work-Group-Type-Edit'))
                    $button .= " <a title='Edit' href='".route('task-working-construction.edit',Crypt::encrypt($data->id))."' onclick='edit_task_group($data->id)' class='btn btn-sm btn-primary' ><i class='fa fa-edit'></i></a> ";
                return $button;
            })      
            ->make(true);
    }
    public function get_sub_task_data(Request $request)
    {
        return json_encode(SubTaskWorkingModel::where('task_working_group_id',$request->task_group_id)->orderBy("id")->get());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $type_of_building = SubCategoryModel::pluck("sub_category_name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.create',compact('type_of_building'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'name'=>'required',
            // 'sub_category_id'=>'required',
            // 'name_sub_task.*'=>'required'
        ]);
        if(isset($request->code)){
            $this->validate($request,[
                'code'=>'unique:nso007_task_working_group_construction',
            ]);
        }
        DB::beginTransaction();
        try {
            $data_group_task = new TaskWorkingGroupModel;
            $data_group_task->name = $request->name;
            $data_group_task->code = $request->code;
            $data_group_task->description = $request->description;
            // $data_group_task->sub_category_id = $request->sub_category_id;
            $data_group_task->user_id = Auth::user()->id;
            $data_group_task->save();
            // $group_task_id = TaskWorkingGroupModel::max("id");
            // foreach($request->name_sub_task as $key=>$value){
            //     SubTaskWorkingModel::insert(['task_working_group_id'=>$group_task_id,'name'=>$value,'description'=>$request->description_sub_task[$key]]);
            // }
            DB::commit();
            \LogActivity::addToLog('Task Working Created successfully!');
            return redirect()->route('task-working-construction.index')->with("success","Create Successfully!");
        } catch (Exception $e) {
             DB::rollback();
             return \back()->with('warning',$e);
        }
    }

    /**
     * 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($id)
    {
        $id = Crypt::decrypt($id);
        $data_task_group = TaskWorkingGroupModel::where("id",$id)->first();
        $data_sub_task_group = SubTaskWorkingModel::where("task_working_group_id",$id)->orderBy("id")->get();
        $sub_category = SubCategoryModel::pluck("sub_category_name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.edit',compact('data_task_group','data_sub_task_group','sub_category'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name'=>'required'
        ]);
        if(isset($request->code))
        {
            $this->validate($request,[
                'code'=>'unique:nso007_task_working_group_construction,code,'.$id,
            ]);
        }
        DB::beginTransaction();
        try {
            $data_group_task = TaskWorkingGroupModel::find($id);
            $data_group_task->name = $request->name;
            $data_group_task->code = $request->code;
            $data_group_task->description = $request->description;
            // $data_group_task->sub_category_id = $request->sub_category_id;
            $data_group_task->user_id = Auth::user()->id;
            $data_group_task->save();

            // SubTaskWorkingModel::where('task_working_group_id',$id)->delete();
            // foreach($request->name_sub_task as $key=>$value){
            //     SubTaskWorkingModel::insert(['task_working_group_id'=>$id,'name'=>$value,'description'=>$request->description_sub_task[$key]]);
            // }
            DB::commit();
            \LogActivity::addToLog('Task Working Update successfully!');
            return redirect()->route('task-working-construction.index')->with("success","Update Successfully!");
        } catch (Exception $e) {
             DB::rollback();
             return \back()->with('warning',$e);
        }
    }
    public function save_edit_sub_task_data(Request $request)
    {
        SubTaskWorkingModel::where("id",$request->id)->update(["name"=>$request->name,'description'=>$request->des]);
        return json_encode("OK");
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        
    }
    public function index_sub_task(Request $request){
        if($request->ajax()){
            $group_work = $request->group_work;
            $work_name = $request->work_name;
            $data = DB::table('nso007_sub_task_working_construction')->when(request('group_work'),function($query) use ($group_work){
                $query->where("task_working_group_id",$group_work);
            })
            ->when(request('work_name'),function($query) use($work_name){
                $query->where("name","LIKE","%".$work_name."%");
            })
            ->get();
            return  Datatables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('group_work',function($data)
                {
                    return optional(DB::table('nso007_task_working_group_construction')->where("id",$data->task_working_group_id)->first())->name;
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Category-Task-Edit')){
                        $button .= " <a title='Edit' href='".route('task-working-construction.edit_create_sub_task',$data->id)."' class='btn btn-sm btn-primary' ><i class='fa fa-edit'></i></a> ";
                    }
                    return $button;
                })      
                ->make(true);
        }
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.list-sub-task',compact('group_work_types'));
    }
    public function create_sub_task(){
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.create-sub-task',compact('group_work_types'));
    }
    public function store_create_sub_task(Request $request){
        $this->validate($request,[
            'name'=>'required',
            'group_work'=>'required'
        ]);
        DB::table('nso007_sub_task_working_construction')->insert(['task_working_group_id'=>$request->group_work,'name'=>$request->name,'description'=>$request->description]);

        return redirect()->route('task-working-construction.index_sub_task')->with("success","Create successfully");
    }
    public function edit_create_sub_task($id){
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        $data = DB::table('nso007_sub_task_working_construction')->where("id",$id)->first();
        return view('administrator.construction.task-working.edit-sub-category-task',compact('data','group_work_types'));
    }
    public function save_edit_sub_task(Request $request,$id){
        $this->validate($request,[
            'name'=>'required',
            'group_work'=>'required'
        ]);
        DB::table('nso007_sub_task_working_construction')->where("id",$id)->update(['task_working_group_id'=>$request->group_work,'name'=>$request->name,'description'=>$request->description]);

        return redirect()->route('task-working-construction.index_sub_task')->with("success","Update successfully");
    }
    public function list_task_contractor(Request $request){
        if($request->ajax()){
            $data = DB::table('nso007_contactor_task_setup_construction')->get();
            return  Datatables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('amount',function($data)
                {
                    return "$".number_format($data->amount,2);
                })
                ->editColumn('group_work',function($data)
                {
                    return optional(DB::table('nso007_task_working_group_construction')->where("id",$data->group_work_id)->first())->name;
                })
                ->editColumn('sub_category_task',function($data){
                    return optional(DB::table('nso007_sub_task_working_construction')->where("id",$data->sub_category_task_id)->first())->name;
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Work-Task-Edit'))
                        $button .= " <a title='Edit' href='".route('task-working-construction.edit_task_contractor',$data->id)."' class='btn btn-sm btn-primary' ><i class='fa fa-edit'></i></a> ";
                    return $button;
                })      
                ->make(true);
        }
        return view('administrator.construction.task-working.list-task-contractor');
    }

    public static function validate_check_arry($db,$attr,$value){
        return DB::table($db)->whereIn($attr,$value)->count();
    }

    public function create_task_contractor(){
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        $sub_category_tasks = DB::table('nso007_sub_task_working_construction')->pluck("name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.create-task-contractor',compact('group_work_types','sub_category_tasks'));
    }
    public function store_task_contractor(Request $request){
        $this->validate($request,[
            'group_work'=>'required',
            'category_task'=>'required',
            'name.*'=>'required',
            'amount.*'=>'required'
        ]);
        
        // if($this::validate_check_arry("nso007_contactor_task_setup_construction","code",$request->code)>0){
        //     return \back()->with("danger","Code already token !");
        // }
        if($this::validate_check_arry("nso007_contactor_task_setup_construction","name",$request->name)>0){
            return \back()->with("danger","Name already token !");
        }
        foreach($request->name as $key=>$value){
            DB::table('nso007_contactor_task_setup_construction')->insert([
                'name'=>$request->name[$key],
                'amount'=>$request->amount[$key],
                'description'=>$request->description[$key],
                'group_work_id'=>$request->group_work,
                'sub_category_task_id'=>$request->category_task
            ]);
        }

        return redirect()->route('task-working-construction.list_task_contractor')->with("success",'Create successfully');
    }
    public function edit_task_contractor($id)
    {
        $data = DB::table('nso007_contactor_task_setup_construction')->where("id",$id)->first();
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        $sub_category_tasks = DB::table('nso007_sub_task_working_construction')->pluck("name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.edit-task-contractor',compact('group_work_types','sub_category_tasks','data'));
    }
    public function update_task_contractor(Request $request,$id)
    {
        $this->validate($request,[
            'group_work'=>'required',
            'sub_category_task'=>'required',
            // 'code'=>'required|unique:nso007_contactor_task_setup_construction,code,'.$id,
            'name'=>'required|unique:nso007_contactor_task_setup_construction,name,'.$id,
            'amount'=>'required'
        ]);
        DB::table('nso007_contactor_task_setup_construction')->where("id",$id)->update([
            // 'code'=>$request->code,
            'name'=>$request->name,
            'amount'=>$request->amount,
            'description'=>$request->description,
            'group_work_id'=>$request->group_work,
            'sub_category_task_id'=>$request->sub_category_task
        ]);

        return redirect()->route('task-working-construction.list_task_contractor')->with("success",'Update successfully');
    }
    public function get_sub_category_task($id){
        return json_encode(DB::table("nso007_sub_task_working_construction")->where("task_working_group_id",$id)->get());
    }

    public function index_category_responsibilities(Request $request){
        if($request->ajax()){
            $group_work = $request->group_work;
            $work_name = $request->work_name;
            $data = DB::table('nso007_category_responsibility_construction')->when(request('group_work'),function($query) use ($group_work){
                $query->where("task_working_group_id",$group_work);
            })
            ->when(request('work_name'),function($query) use($work_name){
                $query->where("name","LIKE","%".$work_name."%");
            })
            ->get();
            return  Datatables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('group_work',function($data)
                {
                    return optional(DB::table('nso007_task_working_group_construction')->where("id",$data->task_working_group_id)->first())->name;
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Category-Responsibilities-Edit'))
                        $button .= " <a title='Edit' href='".route('task-working-construction.edit_create_category_responsibilities',$data->id)."' class='btn btn-sm btn-primary' ><i class='fa fa-edit'></i></a> ";
                    return $button;
                })      
                ->make(true);
        }
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.category-responsibility',compact('group_work_types'));
    }
    public function create_category_responsibilities(){
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.create-category-responsibility',compact('group_work_types'));
    }
    public function store_create_category_responsibilities(Request $request){
        $this->validate($request,[
            'name'=>'required',
            'group_work'=>'required'
        ]);
        DB::table('nso007_category_responsibility_construction')->insert(['task_working_group_id'=>$request->group_work,'name'=>$request->name,'description'=>$request->description]);

        return redirect()->route('task-working-construction.index_category_responsibilities')->with("success","Create successfully");
    }
    public function edit_create_category_responsibilities($id){
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        $data = DB::table('nso007_category_responsibility_construction')->where("id",$id)->first();
        return view('administrator.construction.task-working.edit-category-responsibility',compact('data','group_work_types'));
    }
    public function save_edit_category_responsibilities(Request $request,$id){
        $this->validate($request,[
            'name'=>'required',
            'group_work'=>'required'
        ]);
        DB::table('nso007_category_responsibility_construction')->where("id",$id)->update(['task_working_group_id'=>$request->group_work,'name'=>$request->name,'description'=>$request->description]);

        return redirect()->route('task-working-construction.index_category_responsibilities')->with("success","Update successfully");
    }

    public function list_responsibilities_contractor(Request $request){
        if($request->ajax()){
            $data = DB::table('nso007_responsibilities_contractor_construction')
                    ->leftJoin("nso007_task_working_group_construction","nso007_task_working_group_construction.id","nso007_responsibilities_contractor_construction.work_group_id")
                    ->leftJoin("nso007_category_responsibility_construction","nso007_category_responsibility_construction.id","nso007_responsibilities_contractor_construction.category_responsibility_id")
                    ->select(
                        "nso007_responsibilities_contractor_construction.*",
                        "nso007_task_working_group_construction.name as group_work",
                        "nso007_category_responsibility_construction.name as category"
                    )
                    ->get();
            return  Datatables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('name',function($data){
                    return $data->name;
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Work-Responsibilities-Edit'))
                        $button .= " <a title='Edit' href='".route('task-working-construction.edit_responsibilities_contractor',$data->id)."' class='btn btn-sm btn-primary' ><i class='fa fa-edit'></i></a> ";
                    return $button;
                }) 
                ->rawColumns(['action'=>'action','name'=>'name'])     
                ->make(true);
        }
        return view('administrator.construction.task-working.list-responsibilities-contractor');
    }
    public function create_responsibilities_contractor(Request $request)
    {
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        $category_responsibilies = DB::table('nso007_category_responsibility_construction')->pluck("name","id")->prepend("Please Select","");
        return view('administrator.construction.task-working.create-responsibilities-contractor',compact('group_work_types','category_responsibilies'));
    }
    public function save_responsibilities_contractor(Request $request)
    {
        $this->validate($request,[
            // 'code.*'=>'required',
            'name.*'=>'required',
            'group_work'=>'required',
            'category_responsibility'=>'required'
        ]);

        // if($this::validate_check_arry("nso007_responsibilities_contractor_construction","code",$request->code)>0){
        //     return \back()->with("danger","Code already token !");
        // }
        // if($this::validate_check_arry("nso007_responsibilities_contractor_construction","name",$request->name)>0){
        //     return \back()->with("danger","Name already token !");
        // }
        
        foreach($request->name as $key=>$value){
            DB::table('nso007_responsibilities_contractor_construction')->insert(['name'=>$request->name[$key],'description'=>$request->description[$key],'work_group_id'=>$request->group_work,'category_responsibility_id'=>$request->category_responsibility]);
        }
        return redirect()->route('task-working-construction.list_responsibilities_contractor')->with("success","Create successfully !");
    }
    public function edit_responsibilities_contractor($id)
    {
        $group_work_types = DB::table('nso007_task_working_group_construction')->pluck("name","id")->prepend("Please Select","");
        $category_responsibilies = DB::table('nso007_category_responsibility_construction')->pluck("name","id")->prepend("Please Select","");
        $data = DB::table('nso007_responsibilities_contractor_construction')->where("id",$id)->first();
        return view('administrator.construction.task-working.edit-responsibilities-contractor',compact('data','group_work_types','category_responsibilies'));
    }
    public function update_responsibilities_contractor(Request $request, $id){
        $this->validate($request,[
            // 'code'=>'required|unique:nso007_responsibilities_contractor_construction,code,'.$id,
            // 'name'=>'required|unique:nso007_responsibilities_contractor_construction,name,',
            'name'=>'required',
            'group_work'=>'required',
            'category_responsibility'=>'required'
        ]);
        DB::table('nso007_responsibilities_contractor_construction')->where("id",$id)->update(['name'=>$request->name,'description'=>$request->description,'work_group_id'=>$request->group_work,'category_responsibility_id'=>$request->category_responsibility]);

        return redirect()->route('task-working-construction.list_responsibilities_contractor')->with("success","Create successfully !");
    }
    public function get_category_sponsibilities($id){
        return json_encode(DB::table("nso007_category_responsibility_construction")->where("task_working_group_id",$id)->get());
    }
    public function get_work_task($category_task_id){
        return json_encode(DB::table("nso007_contactor_task_setup_construction")->where('sub_category_task_id',$category_task_id)->get());
    }
    public function get_work_responsibilities($category_responsibilities_id){
        return json_encode(DB::table("nso007_responsibilities_contractor_construction")->where('category_responsibility_id',$category_responsibilities_id)->get());
    }
}
