<?php

namespace App\Http\Controllers\administrator\Construction;

use App\ConstructionPolicyModel;
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;
use Illuminate\Support\Facades\Validator;
use Gate;
use App\JournalModel;
class ContractorTaskResponsibilitiesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
        $this->middleware('permission:Construction-Contractor-Task&Responsibilities-List',['only'=>['index','get_index']]);
        $this->middleware('permission:Construction-Contractor-Check-Task-Working-List',['only'=>['check_task_index','get_check_task_index']]);
        $this->middleware('permission:Construction-Contractor-Check-Task-Working-Show',['only'=>['show_task_index']]);
    }
    public function index()
    {
        return view('administrator.construction.contractor-task-responsibilities.index');
    }
    public function get_index(Request $request)
    {
        $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')
            ->join('nso007_zone_construction',"nso007_zone_construction.id","nso007_construction_table.zone_name")
            ->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_zone_construction.name as block_name','nso007_constructor_construction.type as contractor_type')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->where(function($query) use ($request){
                if(!empty($request->project_id)){
                    $query->where("nso007_construction_table.project_id",$request->project_id);
                }
                if(!empty($request->contractor_name)){
                    $query->where("nso007_constructor_construction.name","%".$request->contractor_name."%");
                }
                if(!empty($request->zone_id)){
                    $query->where("nso007_construction_table.zone_name",$request->zone_id);
                }
                if(!empty($request->work_group_type_id)){
                    $query->where("nso007_construction_table.work_group_type_id",$request->work_group_type_id);
                }
            })
            ->orderBy('nso007_construction_table.created_at','DESC');
        return  Datatables::of($data)
            ->setRowId('id')
            ->addIndexColumn()
            ->editColumn('date',function($data){
                return date('d-m-Y',strtotime($data->date));
            })
            ->editColumn('total_amount',function($data){
                return "$".number_format($data->total_amount,2);
            })
            ->addColumn('status',function ($data){
                $status = '';
                if($data->status == 0)
                {
                    $status = '<span class="text text-success">Complete</span>';
                }
                else if($data->status == 2)
                {
                    $status = '<span class="text text-danger">Terminate</span>';
                }
                return $status;
            })
            ->addColumn('action', function($data) {
                $button ="";
                if(Gate::check('Construction-Contractor-Task&Responsibilities-Contract-Policy'))
                    $button .='<a data-toggle="modal" data-target="#contract-policy" title="Contract Policy" class="btn btn-warning btn-sm btn-contract" data-id="'.$data->id.'"><i class="fa fa-file-code-o"></i></a>';
                if(Gate::check('Construction-Contractor-Task&Responsibilities-Print-Contract'))
                {
                    $button .= " <a title='Show Full Contract' style='margin-left:5px;' target='_blank' href='".route('task_responsibilities_contractor.show',Crypt::encrypt($data->id))."?type=show-full-contract' class='btn btn-sm btn-info' ><i class='fa fa-eye'></i></a> ";

                    $button .= " <a title='Contract' style='margin-left:5px;' target='_blank' 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;' target='_blank' 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;'  target='_blank' href='".route('task_responsibilities_contractor.show_contract_pricinple_construction',Crypt::encrypt($data->id))."' class='btn btn-sm btn-success' ><i class='fa fa-file-text' aria-hidden='true'></i></a> ";


                }
                if($data->status == 1)
                {
                    if(Gate::check('Construction-Contractor-Task&Responsibilities-Edit'))
                        $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> ";
                    if(Gate::check('Construction-Contractor-Task&Responsibilities-Cancel-Contract'))
                        $button .='<a data-toggle="modal" data-target="#terminate-contract" title="ផ្តាច់កុងត្រា" class="btn btn-danger btn-sm btn-terminate" style="margin-left:5px;" data-id="'.$data->id.'"><i class="fa fa-window-close"></i></a>';

                    if(Gate::check('Construction-Contractor-Task&Responsibilities-Delete')){
                        $button .='<a data-toggle="modal" data-target="#modal-delete-info" title="Delete" class="btn btn-danger btn-sm btn-delete-info" style="margin-left:5px;" data-id="'.$data->id.'"><i class="fa fa-trash"></i></a>';
                    }
                }
                if($data->contractor_type==1){
                    if($data->status == 1)
                    {
                        if(Gate::check('Construction-Contractor-Task&Responsibilities-Edit'))
                            $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','');
        $contractors = ConstructorModel::pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')->prepend('Please Select','');
        
        $zones = DB::table("nso007_zone_construction")->pluck("name","id")->prepend("Please Select","");
            
        return view("administrator.construction.contractor-task-responsibilities.create",compact('projects','contractors','work_group_types','zones'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function check_existing(Request $request){
        #check unique
        $check = DB::table('nso007_construction_table')->where('contractor_id',$request->contractor_id)
            ->where("work_group_type_id",$request->work_group_type_id)
            ->where("project_id",$request->project_id)
            ->where("zone_name",$request->zone_name)->count();
        if($check>0) return response()->json(['status'=>false,'message'=>'Contractor has already token for the Zone and Group Work Type ! Do you want to submit?']);
        else return response()->json(['status'=>true,'message'=>'Success']);
        #end
    }
    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',
                'total_duration_build'=>'required',
                'responsibility.*'=>'required',
                'title_responsibility.*'=>'required',
                'task.*'=>'required',
                'amount.*'=>'required',
                'title_task'=>'required',
                'total_amount'=>'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',
                'total_amount'=>'required',
                'duration.*'=>'required'
            ]);
        }

        #check unique
        $check = DB::table('nso007_construction_table')->where('contractor_id',$request->contractor_id)
            ->where("work_group_type_id",$request->work_group_type_id)
            ->where("project_id",$request->project_id)
            ->where("zone_name",$request->zone_name)
            ->where("type_of_house",$request->type_of_house)
            ->count();
        if($check>0) return redirect()->back()->with('warning','Contractor has already token !');
        #end

        ######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->total_duration_build,
            '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");
        
        ####### 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],
                'duration'=>$request->duration[$k],
                'task_type'=>$request->task_type[$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]);
        if($total_amount>0){
            $project = ProjectModel::find($request->project_id);
            $j=JournalModel::select(DB::raw("Max(journal_tran_id) as last_num"))->first();
            $journal = new JournalModel;
            $journal->branch_id=$project->branch_id;
            $journal->journal_parentid=0;
            $journal->journal_type=1;
            $journal->journal_acccode=51100;
            $journal->voucher_type=2;
            $journal->voucher_ref = "V-".\Globals::generate_voucher_number(($j->last_num+1),8);
            $journal->journal_debit = $total_amount;
            $journal->journal_credit = 0;
            $journal->journal_tran_id = $j->last_num+1;
            $journal->journal_transactiondate = date("Y-m-d H:i:s");
            $journal->journal_paydate = date("Y-m-d",strtotime($request->date));
            $journal->journal_currency =1;
            $journal->transaction_type = 'Contract-Price';
            $journal->journal_referenceid = $construction_insert_id;
            $journal->journal_by_project = $request->project_id;
            $journal->journal_by = auth()->user()->id;
            $journal->save();

            $jj=JournalModel::select(DB::raw("Max(id) as last_id"))->first();

            $journal=new JournalModel;
            $journal->branch_id=$project->branch_id;
            $journal->journal_parentid=$jj->last_id;
            $journal->journal_type=1;
            $journal->journal_acccode=21001;
            $journal->voucher_type=2;
            $journal->voucher_ref = "V-".\Globals::generate_voucher_number(($j->last_num+1),8);
            $journal->journal_debit = 0;
            $journal->journal_credit = $total_amount;
            $journal->journal_tran_id = $j->last_num+1;
            $journal->journal_transactiondate = date("Y-m-d H:i:s");
            $journal->journal_paydate = date("Y-m-d",strtotime($request->date));
            $journal->journal_currency =1;
            $journal->transaction_type = 'Contract-Price';
            $journal->journal_referenceid = $construction_insert_id;
            $journal->journal_by_project = $request->project_id;
            $journal->journal_by = auth()->user()->id;
            $journal->save();
        }

        \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);
        $type = isset($_GET['type'])?$_GET['type']:'';
        

        $construction_info = DB::table("nso007_construction_table")
                            ->join("nso007_zone_construction","nso007_zone_construction.id","nso007_construction_table.zone_name")
                            ->select(
                                "nso007_construction_table.id as construct_id",
                                "nso007_construction_table.project_id",
                                "nso007_construction_table.work_group_type_id",
                                "nso007_zone_construction.name as 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",
                                "nso007_construction_table.total_amount"
                            )
                            ->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();
        $construction_policy = ConstructionPolicyModel::where('construction_tableid',$construction_info->construct_id)->first();

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

        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','construction_policy','type','constructor_tasks_title'));
    }

    /**
     * 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","");
        
        // $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','');
            
        $contractors = ConstructorModel::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();

        $work_group_types = TaskWorkingGroupModel::where("id",$data->work_group_type_id)->pluck('name','id');  
        
        $responsibilities_categories = DB::table('nso007_category_responsibility_construction')->where("task_working_group_id",$data->work_group_type_id)->pluck("name","id")->prepend("Please Select","");

        $task_categories = DB::table('nso007_sub_task_working_construction')->where("task_working_group_id",$data->work_group_type_id)->pluck("name","id")->prepend("Please Select","");

        $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)->orderBy("id","ASC")->groupBy('title')->get();

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

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

        $zones = DB::table("nso007_zone_construction")->pluck("name","id")->prepend("Please Select","");

        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','zones','responsibilities_categories','task_categories'));
    }
    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)
    {
        #check unique
        $check = DB::table('nso007_construction_table')->where('contractor_id',$request->contractor_id)
            ->where("work_group_type_id",$request->work_group_type_id)
            ->where("project_id",$request->project_id)
            ->where("zone_name",$request->zone_name)
            ->where("type_of_house",$request->type_of_house)
            ->where("id","!=",$id)
            ->count();
        if($check>0) return redirect()->back()->with('warning','Contractor has already token !');
        #end
        
        $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',
                'total_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',
                'duration.*'=>'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->total_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(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],
                'duration'=>$request->duration[$k],
                'task_type'=>$request->task_type[$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]);

        if($total_amount>0){
            $project = ProjectModel::find($request->project_id);
            JournalModel::where("journal_referenceid",$construction_insert_id)
                        ->where("transaction_type","Contract-Price")
                        ->where("journal_acccode",51100)
                        ->update(
                            ['branch_id'=>$project->branch_id,
                            'journal_debit'=>$total_amount,
                            'journal_paydate'=>date("Y-m-d",strtotime($request->date)),
                            'journal_by_project'=>$request->project_id]);

            JournalModel::where("journal_referenceid",$construction_insert_id)
                        ->where("transaction_type","Contract-Price")
                        ->where("journal_acccode",21001)
                        ->update(
                            ['branch_id'=>$project->branch_id,
                            'journal_credit'=>$total_amount,
                            'journal_paydate'=>date("Y-m-d",strtotime($request->date)),
                            'journal_by_project'=>$request->project_id]);
        }

        \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(Request $request)
    {
        $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')
            ->join("nso007_zone_construction","nso007_zone_construction.id","nso007_construction_table.zone_name")
            ->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','nso007_zone_construction.name as block_name')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->where(function($query) use ($request){
                if(!empty($request->project_id)){
                    $query->where("nso007_construction_table.project_id",$request->project_id);
                }
                if(!empty($request->contractor_name)){
                    $query->where("nso007_constructor_construction.name","%".$request->contractor_name."%");
                }
                if(!empty($request->zone_id)){
                    $query->where("nso007_construction_table.zone_name",$request->zone_id);
                }
                if(!empty($request->work_group_type_id)){
                    $query->where("nso007_construction_table.work_group_type_id",$request->work_group_type_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 = "";
                $value = '';
                $deadline = date('d-m-Y', strtotime("$data->start_work_date +$data->duration month"));
                if($deadline<date('d-m-Y')){
                    $value = "<span style='color:red;'>".$deadline."</span>";
                }else{
                    $value = $deadline;
                }
                if($data->status==0){
                    $value = $deadline;
                }
                return $value;
            })
            ->editColumn('total_amount',function($data)
            {
                return "$".number_format($data->total_amount,2);
            })
            ->addColumn('action', function($data) {
                $button ="";
                if(Gate::check('Construction-Contractor-Check-Task-Working-Show'))
                        $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> ";
                $task_percentage = $this->completeConstruction($data->id);
                if($data->status == 1)
                {
                    if($task_percentage)
                    {
                        if(Gate::check('Construction-Contractor-Check-Task-Working-Close-Construction'))
                            $button .= '<a style="margin-left: 5px" data-id="'.$data->id.'" title="To Complete" class="btn btn-primary btn-sm btn-complete" data-toggle="modal" data-target="#complete-construction"><i class="fa fa-check-circle"></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','deadline'=>'deadline'])    
            ->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_construction =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')
            ->join("nso007_zone_construction","nso007_zone_construction.id","nso007_construction_table.zone_name")
            ->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','nso007_zone_construction.name as block_name')
            ->where('nso007_construction_table.id',$id)
            ->first();

        $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')
            ->join('nso007_construction_table','nso007_construction_table.id','nso007_task_contractor_work_construction.construction_id')
            ->where('nso007_task_contractor_work_construction.construction_id',$id)
            ->select('nso007_task_contractor_work_construction.*','nso007_construction_table.status as construction_status')
            ->get();
            
        return view('administrator.construction.contractor-task-responsibilities.check-task-show',compact('data_task','data_task_title','id','data_construction'));
    }
    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]);
        $construction = DB::table('nso007_task_contractor_work_construction')->where('id',$id)->first();
        $this->completeConstruction($construction->construction_id);
        \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_tasks_title = DB::table('nso007_task_contractor_work_construction')->where("construction_id",$id)->groupBy("title")->orderBy("id")->get();
        $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','constructor_tasks_title')); 
    }
    public function show_contract_pricinple_construction($id)
    {
        return view("administrator.construction.contractor-task-responsibilities.constractor-pricinple-contract"); 
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {   
        #1. Delete Payment History with Journal
        $payment_historys = DB::table("nso007_payment_list_history_construction")->where("construction_id",$id);
        if(!empty($payment_historys->get())&&count($payment_historys->get())>0){
            foreach($payment_historys->get() as $key=>$payment){
                # Delete Journal
                    # Delete payment (normal)
                    DB::table("nso007_journal")->where("journal_referenceid",$payment->id)
                    ->where("transaction_type","Contractor-Payment-Advance")->delete();

                    # Delete payment (cash advance)
                    DB::table("nso007_journal")->where("journal_referenceid",$payment->id)
                    ->where("transaction_type","Contractor-Payment")->delete();
            }
            $payment_historys->delete();
        }
        
        #2. Delete Responsibilities
        $responsibility_contractor = DB::table('nso007_task_responsibility_contractor_construction')->where("construction_id",$id);
        if(!empty($responsibility_contractor->get())&&count($responsibility_contractor->get())>0){
            $responsibility_contractor->delete();
        }

        #3. Delete Tasks
        DB::table('nso007_task_contractor_work_construction')->where("construction_id",$id)->delete();

        #4. Delete Description-Construction-Info
        DB::table('nso007_description_construction_info')->where("construction_id",$id)->delete();

        #5. Delete Construction Table with Journal
        $construction_table = DB::table('nso007_construction_table')->where('id',$id);
        if(!empty($construction_table->first())){
            DB::table("nso007_journal")->where("journal_referenceid",$id)
                ->where("transaction_type","Contract-Price")->delete();
            $construction_table->delete();
        }

        return response()->json(["message"=>"Success"], 200);
    }
    public function terminate(Request $request)
    {
        $construction_task = DB::table('nso007_construction_table')->where('id',$request->id)->where('status','<>',2)->first();
        if(empty($construction_task))
        {
           return response()->json(['success' => false,'message' => 'Construction not found']);
        }
        DB::table('nso007_construction_table')->where('id',$request->id)->update(['status' => 2]);
        DB::table('nso007_construction_terminate')->insert([
           'construction_tableid' => $request->id,
           'date' => !empty($request->date) ? date('Y-m-d',strtotime($request->date)) : null,
           'user_id' => auth()->user()->id
        ]);
        return response()->json(['success' => true,'message' => 'Construction terminate successfully']);
    }
    public function update_policy(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'id' => 'required',
            'policy' => 'required'
        ]);
        if($validator->fails())
        {
            return response()->json(['error' => $validator->errors()->all()]);
        }
        ConstructionPolicyModel::where('construction_tableid',$request->id)->delete();
        ConstructionPolicyModel::insert([
           'construction_tableid' => $request->id,
           'policy' => $request->policy,
           'user_id' => auth()->user()->id
       ]);
       return response()->json(['success' => true,'message' => 'Contract policy create successfully']);
    }
    public function completeConstruction($id)
    {
        $task_work = DB::table('nso007_task_contractor_work_construction')->where('construction_id',$id)->get();
        $task_work_completed = DB::table('nso007_task_contractor_work_construction')->where(['construction_id' => $id,'percentage_completed' => 100])->get();
        if(count($task_work) == count($task_work_completed))
        {
            return true;
        }
        return false;
    }
    public function complete_construction(Request $request)
    {
        DB::table('nso007_construction_table')->where('id',$request->id)->update(['status' => 0]);
        return response()->json(['success' => true,'message' => 'Construction complete successfully']);
    }
}
