<?php

namespace App\Http\Controllers\administrator\Construction;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\ProjectModel;
use App\ConstructionModel\ProductModel;
use App\ConstructionModel\ConstructorModel;
use App\ConstructionModel\TaskWorkingGroupModel;
use Illuminate\Support\Facades\Auth;
use DB;
use DataTables;
use Illuminate\Support\Facades\Crypt;

class ContractorTaskResponsibilitiesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('administrator.construction.contractor-task-responsibilities.index');
    }
    public function get_index()
    {
        $data =DB::table('nso007_construction_table')->join("nso007_project_stock","nso007_project_stock.id","nso007_construction_table.project_id")
            ->join('nso007_constructor_construction','nso007_constructor_construction.id','nso007_construction_table.contractor_id')
            ->join('nso007_task_working_group_construction','nso007_task_working_group_construction.id','nso007_construction_table.work_group_type_id')
            ->select("nso007_construction_table.*","nso007_project_stock.project_name",'nso007_task_working_group_construction.name as group_work_name','nso007_constructor_construction.name as contractor_name')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->orderBy('nso007_construction_table.created_at','DESC')
            ->get();
        return  Datatables::of($data)
            ->setRowId('id')
            ->addIndexColumn()
            ->editColumn('date',function($data){
                return date('d-m-Y',strtotime($data->date));
            })
            
            ->addColumn('action', function($data) {
                $button ="";
                $button .= " <a title='Contract' href='".route('task_responsibilities_contractor.show',Crypt::encrypt($data->id))."' class='btn btn-sm btn-info' ><i class='fa fa-file-o'></i></a> ";

                $button .= " <a title='ឧបសម្ព័ន្ធ ០១' style='margin-left:5px;' href='".route('show-contract-task.show_contract_task',Crypt::encrypt($data->id))."' class='btn btn-sm btn-primary' ><i class='fa fa-file-text-o' aria-hidden='true'></i></a> ";

                $button .= " <a title='ឧបសម្ព័ន្ធ ០២' style='margin-left:5px;' href='".route('task_responsibilities_contractor.show',Crypt::encrypt($data->id))."' class='btn btn-sm btn-success' ><i class='fa fa-file-text' aria-hidden='true'></i></a> ";

                $button .= " <a title='Edit' href='".route('task_responsibilities_contractor.edit',Crypt::encrypt($data->id))."' class='btn btn-sm btn-primary' style='margin-left:5px !important;'><i class='fa fa-edit' ></i></a> ";
                
                return $button;
            })  
            ->rawColumns(['status'=>'status','action'=>'action'])    
            ->make(true);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })
        ->pluck("project_name","id")->prepend("Please Select","");
        $work_group_types = TaskWorkingGroupModel::pluck('name','id')->prepend("Please Select","");
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
             })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');

        return view("administrator.construction.contractor-task-responsibilities.create",compact('projects','contractors','work_group_types'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'contractor_id'=>'required'
        ]);
        $type_constructor = DB::table('nso007_constructor_construction')->where('id',$request->contractor_id)->first()->type;
        if($type_constructor==0){
            $this->validate($request,[
                'project_id'=>'required',
                'date'=>'required',
                'start_work_date'=>'required',
                'work_group_type_id'=>'required',
                'deposit_amount'=>'required',
                'type_of_house'=>'required',
                'duration'=>'required',
                'responsibility.*'=>'required',
                'title_responsibility.*'=>'required',
                'task.*'=>'required',
                'amount.*'=>'required',
                'title_task'=>'required',

            ]);
        }
        else{
            $this->validate($request,[
                'project_id'=>'required',
                'date'=>'required',
                'start_work_date'=>'required',
                'work_group_type_id'=>'required',
                'deposit_amount'=>'required',
                'task.*'=>'required',
                'amount.*'=>'required',
                'title_task'=>'required'
            ]);
        }

        ######Insert Into Construction Table
        $data_construction = array(
            'contractor_id'=>$request->contractor_id,
            'work_group_type_id'=>$request->work_group_type_id,
            'project_id'=>$request->project_id,
            'zone_name'=>$request->zone_name,
            'start_work_date'=>date('Y-m-d',strtotime($request->start_work_date)),
            'type_of_house'=>$request->type_of_house,
            'deposit_amount'=>$request->deposit_amount,
            'duration'=>$request->duration,
            'date'=>date("Y-m-d",strtotime($request->date)),
            'user_id'=>Auth::user()->id,
            'total_paid_amount'=>$request->deposit_amount,
            'des_duration'=>$request->des_duration,
            'des_type_house'=>$request->des_type_house
        );
        DB::table('nso007_construction_table')->insert($data_construction);
        $construction_insert_id =  DB::table('nso007_construction_table')->max("id");
        if($type_constructor==0){
            ####### Insert Into nso007_description_construction_info Table ##############
            if(isset($request->des_title))
            {
                foreach($request->des_title as $key=>$value){
                    $data_description_construction_info = array(
                        'description_name'=>$request->des_title[$key],
                        'description_data'=>$request->des_value[$key],
                        'other'=>$request->other[$key],
                        'construction_id'=>$construction_insert_id
                    );
                    DB::table('nso007_description_construction_info')->insert($data_description_construction_info);
                }
            }
        }
        
        if($type_constructor==0){
            ######## Insert into nso007_task_responsibility_contractor_construction ##########################
            foreach($request->responsibility as $index=>$value){
                $data_responsibilities = array(
                    'construction_id'=>$construction_insert_id,
                    'title'=>$request->title_responsibility[$index],
                    'responsibility_name'=>$request->responsibility[$index],
                    'description'=>$request->description_responsibility[$index]
                );
                DB::table('nso007_task_responsibility_contractor_construction')->insert($data_responsibilities);
            }
        }

        
        ########Insert into nso007_task_contractor_work_construction
        $total_amount = 0;
        foreach($request->task as $k=>$value1){
            $data_task = array(
                'construction_id'=>$construction_insert_id,
                'title'=>$request->title_task[$k],
                'name'=>$request->task[$k],
                'amount'=>$request->amount[$k],
                'description'=>$request->description_task[$k]
            );
            DB::table('nso007_task_contractor_work_construction')->insert($data_task);
            $total_amount += $request->amount[$k];
        }

        DB::table('nso007_construction_table')->where('id',$construction_insert_id)->update(['total_amount'=>$total_amount]);

        \LogActivity::addToLog('Task and Responsibility of contractor create successfully !');
        return redirect()->route('task_responsibilities_contractor.index')->with('success','Create Successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $id = Crypt::decrypt($id);
        $construction_info = DB::table("nso007_construction_table")
                            ->select(
                                "nso007_construction_table.project_id",
                                "nso007_construction_table.work_group_type_id",
                                "nso007_construction_table.zone_name",
                                "nso007_construction_table.type_of_house",
                                "nso007_construction_table.contractor_id",
                                "nso007_construction_table.duration",
                                "nso007_construction_table.des_type_house",
                                "nso007_construction_table.des_duration",
                            )
                            ->where("nso007_construction_table.id",$id)
                            ->first();
        $responsibilities = DB::table('nso007_task_responsibility_contractor_construction')->where("construction_id",$id)->groupBy('title')->orderBy('id')->get();

        $responsibilities_detail = DB::table('nso007_task_responsibility_contractor_construction')->where("construction_id",$id)->orderBy('id')->get();


        $description_construction_info = DB::table('nso007_description_construction_info')->where("construction_id",$id)->get();

        $group_work = DB::table('nso007_task_working_group_construction')->where("id",$construction_info->work_group_type_id)->first();

        $project_info = ProjectModel::where("id",$construction_info->project_id)->first();
        $province_km=optional($project_info->provices)->province_km;
        $district_km=optional($project_info->districts)->district_km;
        $commune_km=optional($project_info->communes)->commune_km;
        $village_km=optional($project_info->villages)->village_km;
        $project_address = (!empty($project_info->house_number)?("ផ្ទះលេខ ".$project_info->house_number):"").(!empty($project_info->street_number)?(" ផ្លូវលេខ ".$project_info->street_number):"").' ភូមិ '.$village_km.' ឃុំ/សង្កាត់ '.$commune_km.' ស្រុក/ខណ្ឌ '.$district_km.' ខេត្ត/ក្រុង '.$province_km;

        $constructor_info = DB::table('nso007_constructor_construction')->where("id",$construction_info->contractor_id)->first();

        return view("administrator.construction.contractor-task-responsibilities.contract-constructor",compact('project_info','group_work','construction_info','project_address','constructor_info','description_construction_info','responsibilities','responsibilities_detail')); 
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $id = Crypt::decrypt($id);
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })
        ->pluck("project_name","id")->prepend("Please Select","");
        $work_group_types = TaskWorkingGroupModel::pluck('name','id')->prepend("Please Select","");
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
             })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');

        $data =DB::table('nso007_construction_table')->where('nso007_construction_table.id',$id)->first();

        $data_description_construction_info = DB::table('nso007_description_construction_info')->where('construction_id',$id)->get();

        $data_responsibilities = DB::table('nso007_task_responsibility_contractor_construction')->where('construction_id',$id)->groupBy('title')->get();

        $data_task = DB::table('nso007_task_contractor_work_construction')->where('construction_id',$id)->groupBy('title')->get();

        $type_constructor = DB::table('nso007_constructor_construction')->where('id',$data->contractor_id)->first()->type;

        return view("administrator.construction.contractor-task-responsibilities.edit",compact('projects','contractors','work_group_types','data','data_description_construction_info','data_responsibilities','data_task','type_constructor'));
    }
    public function get_detail_responsibility(Request $request)
    {
        $title = $request->title;
        $construction_id = $request->construction_id;
        return json_encode(DB::table('nso007_task_responsibility_contractor_construction')->where('construction_id',$construction_id)->where('title',$title)->get());
    }
    public function get_detail_task(Request $request)
    {
        $title = $request->title;
        $construction_id = $request->construction_id;
        return json_encode(DB::table('nso007_task_contractor_work_construction')->where('construction_id',$construction_id)->where('title',$title)->get());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $type_constructor = DB::table('nso007_constructor_construction')->where('id',$request->contractor_id)->first()->type;
        if($type_constructor==0){
            $this->validate($request,[
                'project_id'=>'required',
                'date'=>'required',
                'start_work_date'=>'required',
                'work_group_type_id'=>'required',
                'deposit_amount'=>'required',
                'type_of_house'=>'required',
                'duration'=>'required',
                'responsibility.*'=>'required',
                'title_responsibility.*'=>'required',
                'task.*'=>'required',
                'amount.*'=>'required',
                'title_task'=>'required'
            ]);
        }
        else{
            $this->validate($request,[
                'project_id'=>'required',
                'date'=>'required',
                'start_work_date'=>'required',
                'work_group_type_id'=>'required',
                'deposit_amount'=>'required',
                'task.*'=>'required',
                'amount.*'=>'required',
                'title_task'=>'required'
            ]);
        }

        ######Insert Into Construction Table
        $data_construction = array(
            'contractor_id'=>$request->contractor_id,
            'work_group_type_id'=>$request->work_group_type_id,
            'project_id'=>$request->project_id,
            'zone_name'=>$request->zone_name,
            'start_work_date'=>date('Y-m-d',strtotime($request->start_work_date)),
            'type_of_house'=>$request->type_of_house,
            'deposit_amount'=>$request->deposit_amount,
            'duration'=>$request->duration,
            'date'=>date("Y-m-d",strtotime($request->date)),
            'user_id'=>Auth::user()->id,
            'total_paid_amount'=>$request->deposit_amount,
            'des_type_house'=>$request->des_type_house,
            'des_duration'=>$request->des_duration
        );
        DB::table('nso007_construction_table')->where('id',$id)->update($data_construction);
        $construction_insert_id =  $id;
        
        ####### Insert Into nso007_description_construction_info Table ##############
        DB::table('nso007_description_construction_info')->where("construction_id",$construction_insert_id)->delete();
        if($type_constructor==0){
            
            if(isset($request->des_title))
            {
                foreach($request->des_title as $key=>$value){
                    $data_description_construction_info = array(
                        'description_name'=>$request->des_title[$key],
                        'description_data'=>$request->des_value[$key],
                        'other'=>$request->other[$key],
                        'construction_id'=>$construction_insert_id
                    );
                    DB::table('nso007_description_construction_info')->insert($data_description_construction_info);
                }
            }
        }

        ######## Insert into nso007_task_responsibility_contractor_construction ##########################
        DB::table('nso007_task_responsibility_contractor_construction')->where('construction_id',$construction_insert_id)->delete();
        if($type_constructor==0){
            foreach($request->responsibility as $index=>$value){
                $data_responsibilities = array(
                    'construction_id'=>$construction_insert_id,
                    'title'=>$request->title_responsibility[$index],
                    'responsibility_name'=>$request->responsibility[$index],
                    'description'=>$request->description_responsibility[$index]
                );
                DB::table('nso007_task_responsibility_contractor_construction')->insert($data_responsibilities);
            }
        }
        
        ########Insert into nso007_task_contractor_work_construction
        DB::table('nso007_task_contractor_work_construction')->where("construction_id",$construction_insert_id)->delete();

        $total_amount = 0;

        foreach($request->task as $k=>$value1){
            $data_task = array(
                'construction_id'=>$construction_insert_id,
                'title'=>$request->title_task[$k],
                'name'=>$request->task[$k],
                'amount'=>$request->amount[$k],
                'description'=>$request->description_task[$k]
            );
            DB::table('nso007_task_contractor_work_construction')->insert($data_task);
            $total_amount = $request->amount[$k];
        }

        DB::table('nso007_construction_table')->where('id',$construction_insert_id)->update(['total_amount'=>$total_amount]);

        \LogActivity::addToLog('Task and Responsibility of contractor update successfully !');
        return redirect()->route('task_responsibilities_contractor.index')->with('success','Update Successfully');
    }

    public function check_task_index()
    {
        return view('administrator.construction.contractor-task-responsibilities.check-task');
    }
    public function get_check_task_index()
    {
        $data =DB::table('nso007_construction_table')->join("nso007_project_stock","nso007_project_stock.id","nso007_construction_table.project_id")
            ->join('nso007_constructor_construction','nso007_constructor_construction.id','nso007_construction_table.contractor_id')
            ->join('nso007_task_working_group_construction','nso007_task_working_group_construction.id','nso007_construction_table.work_group_type_id')
            ->select("nso007_construction_table.*","nso007_project_stock.project_name",'nso007_task_working_group_construction.name as group_work_name','nso007_constructor_construction.name as contractor_name','nso007_constructor_construction.type')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->orderBy('nso007_construction_table.created_at','DESC')
            ->get();
        return  Datatables::of($data)
            ->setRowId('id')
            ->addIndexColumn()
            ->editColumn('date',function($data){
                return date('d-m-Y',strtotime($data->date));
            })
            ->addColumn('deadline',function($data){
                $deadline = "";
                $deadline = date('d-m-Y', strtotime("$data->start_work_date +$data->duration month"));
                return $deadline;
            })
            ->addColumn('action', function($data) {
                $button ="";
                $button .= " <a title='Show Task'​ target='_blank' href='".route('task_contractor.show_task_index',Crypt::encrypt($data->id))."' class='btn btn-sm btn-info' ><i class='fa fa-eye'></i></a> ";
                
                return $button;
            })  
            ->editColumn('type',function($data){
                if($data->type==0) return "Contract";
                else return "Freelance";
            })
            ->editColumn('start_work_date',function($data){
                return date('d-m-Y',strtotime($data->start_work_date));
            })
            ->rawColumns(['status'=>'status','action'=>'action'])    
            ->make(true);
    }

    public function show_task_index($id=null,Request $request)
    {
        if($request->ajax()){
            $task_id = $request->task_id;
            $max_percentage_completed_work = DB::table('nso007_payment_list_history_construction')->where("task_id",$task_id)->where('type','!=',5)->max("percentage_work_current");
            return json_encode($max_percentage_completed_work);
        }
        $id = Crypt::decrypt($id);
        $data_task_title = DB::table('nso007_task_contractor_work_construction')
            ->where('construction_id',$id)->groupBy('title')->orderBy('id')->get();
        $data_task = DB::table('nso007_task_contractor_work_construction')
            ->where('construction_id',$id)->get();
        
        return view('administrator.construction.contractor-task-responsibilities.check-task-show',compact('data_task','data_task_title'));
    }
    public function save_percentage_work(Request $request)
    {
        $id = $request->id;
        $percentage = $request->percentage;
        DB::table('nso007_task_contractor_work_construction')->where('id',$id)->update(['percentage_completed'=>$percentage]);
        \LogActivity::addToLog('save percentage of working successfully !');
        return json_encode(DB::table('nso007_task_contractor_work_construction')->where('id',$id)->select('percentage_completed')->first()->percentage_completed);
    }
    public function show_contract_task($id)
    {
        $id = Crypt::decrypt($id);
        $construction_info = DB::table("nso007_construction_table")
                            ->select(
                                "nso007_construction_table.project_id",
                                "nso007_construction_table.work_group_type_id",
                                "nso007_construction_table.zone_name",
                                "nso007_construction_table.type_of_house",
                                "nso007_construction_table.contractor_id",
                                "nso007_construction_table.duration",
                                "nso007_construction_table.des_type_house",
                                "nso007_construction_table.des_duration",
                            )
                            ->where("nso007_construction_table.id",$id)
                            ->first();

        $constructor_info = DB::table('nso007_constructor_construction')->where("id",$construction_info->contractor_id)->first();

        return view("administrator.construction.contractor-task-responsibilities.contract-task-constructor",compact('construction_info','constructor_info')); 
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
