<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ReportActivity;
use App\Models\Activity;
use App\Models\Project;

use DB;

class ControlMonitoringController extends Controller
{
    public function search(Request $request)
    {
        $payload = $request->all();
        $dataBuilder = $this->setUpPayload($payload, 'm_proyek');
        $builder = $dataBuilder['builder'];
        $countBuilder = $dataBuilder['count'];
        $dataGet = $builder->get();
        if($request->has("child_data")){
            $newDataGet = [];
            $child_data = $request->child_data;
            $date_start = $child_data['start_date'];
            $date_end = $child_data['date_end'];
            foreach ($dataGet as $value) {
                $ganttId = $this->getMaxVersionGantt($value->id);
                $allActivityIds = Activity::where("version_gantt_id", $ganttId)->where("proyek_id", $value->id)->pluck("id");
                $value->volume_planning = Activity::where("version_gantt_id", $ganttId)->where("proyek_id", $value->id)->sum("jumlah_pekerjaan");
                $value->biaya_actual = Activity::where("version_gantt_id", $ganttId)->where("proyek_id", $value->id)->sum("biaya_actual");
                $value->volume_actual = ReportActivity::where("activity_id", $allActivityIds->all())->sum("job_count_report");
                $listAct = [];
                $activityIds = ReportActivity::select("ma.id as id")->join("m_activity as ma", "ma.id", "=", "report_activity.activity_id")->where("ma.version_gantt_id", $ganttId)->where("ma.proyek_id", $value->id)->whereBetween("report_activity.report_date", [$date_start, $date_end])->groupBy("ma.id")->get()->pluck('id');
                $dataActivity = Activity::select("m_activity.*", "ms.name as uom")->leftJoin("m_satuan as ms", "ms.id","=","m_activity.satuan_id")->whereIn("m_activity.id", $activityIds->all())->get();
                foreach($dataActivity as $act){
                    $act->list_report = ReportActivity::select("report_activity.*", "mu.name as user_name", "mi.image as image_url")->leftJoin("m_users as mu", "mu.id", "=", "report_activity.user_id")->leftJoin("m_image as mi", function($join){
                        $join->on("mi.ref_id", "=", "report_activity.id")->where("mi.category", "report_activity");
                    })->where("report_activity.activity_id", $act->id)->whereBetween("report_activity.report_date", [$date_start, $date_end])->get();
                    $listAct[] = $act;
                }
                $value->report_data = $listAct;
                $newDataGet[] = $value;
            }
            $dataGet = $newDataGet;
        }
        $totalRecord = $countBuilder->count();
        return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200);
    }

    private function getMaxVersionGantt($id){
        return Activity::where("proyek_id", $id)->max("version_gantt_id");
    }
}