<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\HierarchyFtth;
use App\Models\VersionGantt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Artisan;

class HierarchyFtthController extends Controller
{
    public function index()
    {
        try {
            $hierarchyFtths = HierarchyFtth::all();
            return response()->json($hierarchyFtths);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to retrieve hierarchy FTTHs.',
                'error' => $e->getMessage()
            ], 500);
        }
    }
    
    public function search(Request $request)
    {
        $payload = $request->all();
        $dataBuilder = $this->setUpPayload($payload, 'm_hierarchy_ftth');
        $builder = $dataBuilder['builder'];
        $countBuilder = $dataBuilder['count'];
        $dataGet = $builder->get();
        $totalRecord = $countBuilder->count();
        return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200);
    }

    public function store(Request $request)
    {
        try {
          $attributes = $request->only(['name', 'parent_id', 'project_id']);
          $hierarchyFtth = HierarchyFtth::create($attributes);

            return response()->json([
                'status'=>'success',
                'code' => 200,
                'message' => 'Hierarchy FTTH created successfully.',
                'data' => $hierarchyFtth
            ],200);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to create hierarchy FTTH.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function show($id)
    {
        $hierarchyFtth = HierarchyFtth::where('id', $id)->first();   
        try {
            return response()->json($hierarchyFtth);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to retrieve hierarchy FTTH.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $hierarchyFtth = HierarchyFtth::where('id', $id)->first();
        try {
            $hierarchyFtth->update($request->all());

            return response()->json([
                'message' => 'Hierarchy FTTH updated successfully.',
                'data' => $hierarchyFtth
            ],200);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to update hierarchy FTTH.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function destroy($id)
    {
        $hierarchyFtth = HierarchyFtth::where('id', $id)->first();
        try {
            $hierarchyFtth->delete();

            return response()->json([
                'message' => 'Hierarchy FTTH deleted successfully.',
                'data' => $hierarchyFtth
            ],200);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to delete hierarchy FTTH.',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function countProgress($hierarchy_id) {
      // $ftthIds = VersionGantt::select('hierarchy_ftth_id')
      //   ->where('proyek_id', $project_id)
      //   ->groupBy('hierarchy_ftth_id')
      //   ->get();
      // if($ftthIds){
      //   foreach ($ftthIds as $ftthId) {
      //     $gantts = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->sum('progress');
      //     $bobot_planning = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->sum('bobot');
      //     $ganttCount = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->count();

      //     $ftth = HierarchyFtth::find($ftthId->hierarchy_ftth_id);
      //     if($ftth){
      //       $round = $gantts/$ganttCount;
      //       $round_bobot = $bobot_planning/$ganttCount;
      //       $ftth->progress = round($round, 2);
      //       $ftth->bobot_planning = round($round_bobot, 2);
      //       try {
      //           $ftth->save();
      //       } catch (\Exception $e) {
      //           // Log the error or handle it in some other way
      //           Log::error($e->getMessage());
      //       }

      //       if($ftth->parent_id){
      //         $this->countParent($ftth); 
      //       }
      //     }
      //   }
      // }

      // calculate ke curva berdasarkan site
        Artisan::call('calculate:progressgantt', [
          'hierarchy_id' => $hierarchy_id
        ]);
    }

    public function countParent($ftth){
      $parent = HierarchyFtth::find($ftth->parent_id);
      $children = HierarchyFtth::where('parent_id', $ftth->parent_id)->sum('progress');
      $childrenCount = HierarchyFtth::where('parent_id', $ftth->parent_id)->count();
      if($parent){
        $round = $children/$childrenCount;
        $parent->progress = round($round, 2);
        try {
            $parent->save();
        } catch (\Exception $e) {
            // Log the error or handle it in some other way
            Log::error($e->getMessage());
        }
        if($parent->parent_id) {
          $this->countParent($parent);
        }
      }
    }

    public function getTreeByGantt($gantt_id)
    {
      $finalData = [];
      $gantt = VersionGantt::find($gantt_id);
      if ($gantt->hierarchy_ftth_id) {
        $ftth = HierarchyFtth::find($gantt->hierarchy_ftth_id);
        array_push($finalData, $ftth);
        if($ftth->parent_id){
          $this->getParents($finalData, $ftth->parent_id);
        }
      } else {
        return response()->json(['status'=>'success','data'=>$finalData,'code'=>200], 200);
      }
      return response()->json(['status'=>'success','data'=>$finalData,'code'=>200], 200);
    }

    public function getParents(&$data, $id){
      $ftth = HierarchyFtth::find($id);
      array_push($data, $ftth);
      if ($ftth->parent_id) {
        $this->getParents($data, $ftth->parent_id);
      }
    }
    
    public function getTreeByProject($project_id)
    {
        $data = HierarchyFtth::where('project_id', $project_id)->whereNull('parent_id')->orderByRaw('id ASC')->get();
        $finalData = [];
        foreach($data as $objRow){
            $objRow->key = rand(1, 1000);
            if (VersionGantt::where('hierarchy_ftth_id', $objRow->id)->exists()) {
                $dataGantt = VersionGantt::where('hierarchy_ftth_id', $objRow->id)->get();
                $progress = $this->ganttProgress('hierarchy_ftth_id', $objRow->id);
                foreach ($dataGantt as $gantt) {
                  $gantt->key = $objRow->key;
                  foreach ($progress as $p) {
                    if ($p->id == $gantt->id) {
                      $gantt->progress = $p->persentase_progress;
                      $gantt->bobot_planning = $p->bobot_planning ? $p->bobot_planning : 0;
                    }
                  }
                }
                $objRow->dataGantt = $dataGantt;
            }
            $objRow->children = $this->getChildren($project_id, $objRow->id);
            $finalData[] = $objRow;
        }

        return response()->json(['status'=>'success','data'=>$finalData,'code'=>200], 200);
    }
    public function countProgressTree($hierarchy_id)
    {
        Artisan::call('calculate:progressgantt', [
          'hierarchy_id' => $hierarchy_id
        ]);
        return response()->json(['status'=>'success','code'=>200], 200);
    }
    private function getChildren($project_id, $parent_id)
    {
        $finalData = [];
        $data = HierarchyFtth::where('project_id', $project_id)->where('parent_id', $parent_id)->orderByRaw('id ASC')->get();
     
        foreach($data as $objRow){
            $objRow->key = rand(1, 1000);
            if (VersionGantt::where('hierarchy_ftth_id', $objRow->id)->exists()) {
                $dataGantt = VersionGantt::where('hierarchy_ftth_id', $objRow->id)->get();
                $progress = $this->ganttProgress('hierarchy_ftth_id', $objRow->id);
                foreach ($dataGantt as $gantt) {
                  $gantt->key = $objRow->key;
                  foreach ($progress as $p) {
                    if ($p->id == $gantt->id) {
                      $gantt->progress = $p->persentase_progress;
                      $gantt->bobot_planning = $p->bobot_planning ? $p->bobot_planning : 0;
                    }
                  }
                }
                $objRow->dataGantt = $dataGantt;
            }
            $objRow->children = $this->getChildren($project_id, $objRow->id);
            $finalData[] = $objRow;
        }
        return $finalData;
    }    
    
    public function ganttProgress($column, $value){
      $progress = VersionGantt::select('m_version_gantt.id','m_activity.persentase_progress', 'm_activity.bobot_planning')
        ->join('m_activity', 'm_version_gantt.id', '=', 'm_activity.version_gantt_id')
        ->where("m_version_gantt.".$column, $value)
        ->where('m_activity.type_activity', "project")
        ->where('m_activity.parent_id', null)
        ->get();

      return $progress;
    }
}