<?php

namespace App\Http\Controllers\administrator\Construction;

use App\ConstructionModel\BOQModel;
use App\ProjectModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Yajra\DataTables\DataTables;
use DB;
use Gate;

class CECApproval extends Controller
{
    function __construct(){
        $this->middleware('permission:Construction-CEO-Approval-BOQ-List',['only'=>['index']]);
        $this->middleware('permission:Construction-CEO-Approval-Cash-Advance-List',['only'=>['cash_advance_index']]);
    }
    public function index(Request $request){
        $prepare_by = $request->prepare_by;
        $title = $request->title;
        $project = $request->project;
        $building_type = $request->building_type;
        $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","");
        $products = "";

        if($request->ajax()){
            $data =BOQModel::join("nso007_project_stock","nso007_project_stock.id","nso007_boq_construction.project_id")
                ->select("nso007_boq_construction.*","nso007_project_stock.project_name")
                ->when(empty(\Branch::branch_key()), function ($query) {
                    $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
                })
                ->when(request('prepare_by'),function($query) use ($prepare_by){
                    $query->where("prepared_by","LIKE","%".$prepare_by."%");
                })
                ->when(request('title'),function($query) use($title){
                    $query->where("title","LIKE","%".$title."%");
                })
                ->when(request('project'),function($query) use ($project){
                    $query->where("project_id",$project);
                })
                ->when(request('building_type'),function($query) use ($building_type){
                    $query->where("building_type",$building_type);
                })
                ->where("nso007_boq_construction.status",3)
                ->orderBy('nso007_boq_construction.created_at','DESC')
                ->get();
            return  DataTables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('date',function($data){
                    return date('d-m-Y',strtotime($data->date));
                })
                ->editColumn('status',function($data){
                    if($data->status==1) return "<span style='color:rgb(184, 95, 11)'>Pendding</span>";
                    else if($data->status==0) return "<span style='color:rgb(42, 156, 8)'>Approved</span>";
                    else if($data->status==2) return "<span style='color:rgb(185, 51, 17)'>Rejected</span>";
                    else if($data->status==3) return "<span style='color:rgb(42, 156, 8)'>Approved (Financial)</span>";
                    else if($data->status==4) return "<span style='color:rgb(42, 156, 8)'>Approved (CEO)</span>";
                    else {}
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Construction-CEO-Approval-BOQ-Show'))
                        $button .= " <a title='Show Detail' href='".route('construction-boq.show',Crypt::encrypt($data->id))."?type=ceo"."' class='btn btn-sm btn-info' ><i class='fa fa-eye'></i></a> ";
                    if($data->status==1 || $data->status==3 ){
                        if(Gate::check('Construction-CEO-Approval-BOQ-Appove'))
                            $button .= " <a data-status = '1' data-id='".Crypt::encrypt($data->id)."' title='Approve'  class='btn btn-sm btn-success boq_approval' style='margin-left:5px !important;'><i class='fa fa-check' ></i></a> ";
                        if(Gate::check('Construction-CEO-Approval-BOQ-Reject'))
                            $button .= " <a data-status = '2' data-id='".Crypt::encrypt($data->id)."'  title='Reject'  class='btn btn-sm btn-danger boq_approval' style='margin-left:5px !important;'><i class='fa fa-times' ></i></a> ";
                    }

                    return $button;
                })
                ->rawColumns(['status'=>'status','action'=>'action'])
                ->make(true);
        }
        
        return view("administrator.construction.ceo-approval.boq.index",compact('projects','products'));
    }
    public function update_approval(Request $request)
    {
        // dd($request->all());
        $id         = Crypt::decrypt($request->r_id);
        $status     = ($request->status);
        $boq        = BOQModel::find($id);
        $des        = $request->description;

        if($boq->status == 3 || $boq->status == 4 ){
            if($status == 1){
                $boq->status = 0;
            }
        }
        if($boq->status == 1 && $status == 1){
            $boq->status = 4;
        }
        if($boq->status == 1 && $status == 2){
            $boq->status = 2;
        }
        if($boq->status == 3 && $status == 2){
            $boq->status = 2;
        }
        $boq->ceo_user_id = Auth::user()->id;
        $boq->reason_reject_ceo = $des != '' ? $des : null;
        $boq->update();

        \LogActivity::addToLog('BOQ approve successfully !');
        return redirect()->route('construction-ceo-approval-boq.index')->with('success','CEO Approval has been Update');
    }
    public function cash_advance_index(Request $request)
    {
        $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","");
        if($request->Ajax()){
            $project_id = $request->project_id;
            $contractor_name = $request->contractor_name;
                $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_task_contractor_work_construction","nso007_task_contractor_work_construction.construction_id","nso007_construction_table.id")
                ->join("nso007_zone_construction","nso007_zone_construction.id","nso007_construction_table.zone_name")
                ->join('nso007_payment_list_history_construction','nso007_payment_list_history_construction.task_id','nso007_task_contractor_work_construction.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_payment_list_history_construction.created_at as request_date',
                'nso007_payment_list_history_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());
                })
                ->when(request('project_id'),function($query) use ($project_id){
                    $query->where("nso007_construction_table.project_id",$project_id);
                })
                ->when(request('contractor_name'),function($query) use ($contractor_name){
                    $query->where("nso007_constructor_construction.name","LIKE","%".$contractor_name."%");
                })
                ->where('nso007_payment_list_history_construction.type',3)
                ->groupBy('nso007_payment_list_history_construction.created_at')
                ->get();
            return  Datatables::of($data)
                ->setRowId('id')
                ->setRowData([
                    'created_at' => function($data) {
                        return $data->request_date;
                    }
                ])
    
                ->addIndexColumn()
                ->editColumn('start_work_date',function($data){
                    return date('d-m-Y',strtotime($data->start_work_date));
                })
                ->addColumn('deadline',function($data){
                    return date("d-m-Y",strtotime("$data->start_work_date +$data->duration month"));
                })
                ->editColumn('date',function($data){
                    return date('d-m-Y H:i:s',strtotime($data->request_date));
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if($data->type==2||$data->type==3) 
                    {
                        if(Gate::check('Construction-CEO-Approval-Cash-Advance-Approve'))
                        {
                            $button .= "<button class='btn btn-sm btn-success' data-id='".$data->id."' data-created_at = '".$data->request_date."' onclick='display_form_approval(this)'>
                                <span class='fa fa-check'></span>
                            </button>";
                        }
                        if(Gate::check('Construction-CEO-Approval-Cash-Advance-Reject'))
                        {
                            $button .= "<button style='margin-left:5px;' class='btn btn-sm btn-danger' data-id='".$data->id."' data-created_at = '".$data->request_date."' onclick='display_form_reject(this)'>
                                <span class='fa fa-times'></span>
                            </button>";
                        } 
                    }
                    else {

                    }
                    return $button;
                })  
                ->addColumn('status',function($data)
                {
                    if($data->type==2) return "<span style='color: rgb(197, 125, 31);'>Requesting</span>";
                    else if($data->type==3) return "<span style='color: green;'>Approved by Financial</span>";
                    else if($data->type==1) return "<span style='color: green;'>Approved</span>";
                    else if($data->type==4) return "<span style='color: green;'>Approved by CEO</span>";
                    else {

                    }
                })
                ->rawColumns(['status'=>'status','action'=>'action'])    
                ->make(true);
        }
        return view("administrator.construction.ceo-approval.cash-advance-index",compact('projects'));
    }
    public function get_index_detail(Request $request)
    {
        $construction_id = $request->construction_id;
        $created_at = $request->created_at;

        return json_encode(
            DB::table('nso007_payment_list_history_construction')
            ->join("nso007_task_contractor_work_construction","nso007_task_contractor_work_construction.id",'nso007_payment_list_history_construction.task_id')
            ->select(
                "nso007_payment_list_history_construction.*",
                "nso007_task_contractor_work_construction.name",
                "nso007_task_contractor_work_construction.title",
                "nso007_task_contractor_work_construction.percentage_completed",
                "nso007_task_contractor_work_construction.amount as fee_amount",
                "nso007_task_contractor_work_construction.paid_amount as fee_paid_amount"
                )
            ->where('nso007_payment_list_history_construction.construction_id',$construction_id)
            ->where("nso007_payment_list_history_construction.created_at",date("Y-m-d H:i:s",strtotime($created_at)))
            ->whereBetween("nso007_payment_list_history_construction.type",[1,4])
            ->get()
        );
    }
    public function store_approve_cash_advance()
    {
        $construction_id = $_GET['construction_id'];
        $created_at = $_GET['created_at'];
        $check_db = DB::table('nso007_payment_list_history_construction')->where('construction_id',$construction_id)->where('created_at',date('Y-m-d H:i:s',strtotime($created_at)))->whereBetween('type',[2,3])->get();
        if(!empty($check_db)){
            if(count($check_db)>0)
            {
                foreach($check_db as $key=>$value)
                {
                    if($value->type==2){
                        DB::table('nso007_payment_list_history_construction')->where('construction_id',$construction_id)->where('created_at',date('Y-m-d H:i:s',strtotime($created_at)))->where('task_id',$value->task_id)->update(['type'=>4,'ceo_user_id'=>Auth::user()->id]);
                    }else if($value->type==3){
                        DB::table('nso007_payment_list_history_construction')->where('construction_id',$construction_id)->where('created_at',date('Y-m-d H:i:s',strtotime($created_at)))->where('task_id',$value->task_id)->update(['type'=>1,'ceo_user_id'=>Auth::user()->id]);

                        DB::table('nso007_task_contractor_work_construction')->where('id',$value->task_id)->update(['cash_advance_amount'=>DB::raw("cash_advance_amount + ".$value->cash_advance_amount),'paid_amount'=>DB::raw('paid_amount + '.$value->cash_advance_amount)]);

                        DB::table('nso007_construction_table')->where("id",$construction_id)->update(['total_cash_advance'=>DB::raw("total_cash_advance + ".$value->cash_advance_amount),"total_paid_amount"=>DB::raw('total_paid_amount + '.$value->cash_advance_amount)]);
                    }
                    else{
                        return \back();
                    }
                }
            }else{
                
                return \back()->with('warning','Your request is fail!');
            }
        }
        else{
            return \back()->with('warning','Your request is fail!');
        }
        \LogActivity::addToLog('Cash Advance approve successfully !');
        return \back()->with('success','successfuly!');
        
    }
    public function store_reject_cash_advance()
    {
        $construction_id    = $_GET['construction_id'];
        $created_at         = $_GET['created_at'];
        $des                = $_GET['description'];
        $check_db = DB::table('nso007_payment_list_history_construction')->where('construction_id',$construction_id)->where('created_at',date('Y-m-d H:i:s',strtotime($created_at)))->get();
        if(!empty($check_db)){
            if(count($check_db)>0)
            {
                foreach($check_db as $key=>$value)
                {
                    DB::table('nso007_payment_list_history_construction')
                        ->where('construction_id',$construction_id)
                        ->where('created_at',date('Y-m-d H:i:s',strtotime($created_at)))
                        ->update([
                            'type'              => 5,
                            'ceo_user_id'       => Auth::user()->id,
                            'reason_reject_ceo' => $des ? $des : null
                        ]);
                }
            }else{
                
                return \back()->with('warning','Your request is fail!');
            }
        }
        else{
            return \back()->with('warning','Your request is fail!');
        }
        \LogActivity::addToLog('Cash Advance reject successfully !');
        return \back()->with('success','successfuly!');
        
    }
    
    public function get_request_cash_advance($id)
    {
        // return json_encode(DB::table('nso007_payment_list_history_construction')->where('task_id',$id)->where('t')->first());
    }
    public function  aa(){
        dd(1);
    }
}
