<?php

namespace App\Http\Controllers;

use App\Http\Controllers\AppBaseController;

use App\Models\KanbanAccounts;
use App\Models\BoardSwimlanes;
use App\Models\BoardStages;
use App\Models\Boards;
use App\Models\WorkloadMappings;
use App\Models\WorkloadRelations;
use App\Models\BoardCollaborators;
use App\Models\WorkloadMappingLevels;

use Illuminate\Http\Request;
use Flash;
use Response;

class WorkloadMappingController extends AppBaseController
{
    /**
     * Display a listing of the Swimline Mapping.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $WorkloadMappings = WorkloadMappings::get();

        foreach($WorkloadMappings as $gsm)
        {
            foreach($gsm->workload_relations as $gsr)
            {
                if($gsr->swimlane_ids != "")
                {
                    $gsr->swimlane_names = BoardSwimlanes::whereIn("swimlane_id", explode(',', $gsr->swimlane_ids))->pluck('name')->implode(', ');
                }

                if($gsr->stage_ids != "")
                {
                    $gsr->stage_names = BoardStages::whereIn("stage_id", explode(',', $gsr->stage_ids))->pluck('name')->implode(', ');
                }

                if($gsr->collaborator_ids != "")
                {
                    $gsr->collab_names = BoardCollaborators::whereIn("collaborator_id", explode(',', $gsr->collaborator_ids))->where('board_id',$gsr->board_id)->pluck('name')->implode(', ');
                }

            }

        }

        return view('workload_mapping.index')
            ->with('WorkloadMappings', $WorkloadMappings);

    }

    /**
     * Show the form for creating a new KanbanAccounts.
     *
     * @return Response
     */
    public function create()
    {
        $boards = Boards::get();

        $levels = WorkloadMappingLevels::whereIn("id", WorkloadMappings::pluck("level_id"))->get();

        foreach($boards as $board)
        {
           $tree = $this->buildTree($board->stages->toArray());

           $board->tree_stages = $tree;
        }
        
        return view('workload_mapping.create')->with('boards', $boards)->with('levels', $levels);
    }

    public function buildTree(array $elements, $parentId = 0) 
    {
        $branch = array();

        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = $this->buildTree($elements, $element['stage_id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }


    public function store(Request $request)
    {
        $validated = $request->validate([
            'level_select' => 'required_without:level_new',
            'level_new' => 'required_without:level_select'
        ]);
        
        if($request->level_new != "")
        {
            $g_ss_map_level = WorkloadMappingLevels::create(["label" => $request->level_new]);
            $level_id = $g_ss_map_level->id;
        }else
        {
            $level_id = $request->level_select;
        }

        $workload_map = WorkloadMappings::create(["level_id" => $level_id, "label" => $request->label]);

        $workload_map_relations = [];
        foreach($request->boards as $b)
        {
            $workload_map_relations_single = [];
            $workload_map_relations_single['workload_mapping_id'] = $workload_map->id;
            $workload_map_relations_single['board_id'] = $b;

            if(isset($request->swimlanes[$b]) && count($request->swimlanes[$b]) > 0)
            {
                $workload_map_relations_single['swimlane_ids'] = implode(',',$request->swimlanes[$b]);
            }
            if(isset($request->stages[$b]) && count($request->stages[$b]) > 0)
            {
                $workload_map_relations_single['stage_ids'] = implode(',',$request->stages[$b]);
            }

            if(isset($request->collabs[$b]) && count($request->collabs[$b]) > 0)
            {
                $workload_map_relations_single['collaborator_ids'] = implode(',',$request->collabs[$b]);
            }

            if(isset($request->swimlanes[$b]) && isset($request->stages[$b]))
            {
                array_push($workload_map_relations, $workload_map_relations_single);
            }
            
            
        }

        if(count($workload_map_relations) > 0)
        {
            WorkloadRelations::insert($workload_map_relations);
        }

        return redirect(route('workload_mapping.index'));

    }

    public function edit($id)
    {
        $WorkloadMappings = WorkloadMappings::find($id);

        $boards = Boards::get();

        $levels = WorkloadMappingLevels::whereIn("id", WorkloadMappings::pluck("level_id"))->get();

        foreach($boards as $board)
        {
           $tree = $this->buildTree($board->stages->toArray());

           $board->tree_stages = $tree;
           

           $selected_items = WorkloadRelations::where("workload_mapping_id", $id)->where("board_id", $board->id)->select("swimlane_ids", "stage_ids", "collaborator_ids")->first();

           if($selected_items)
           {
                $board->selected_swimlanes = explode(",", $selected_items->swimlane_ids);
                $board->selected_stages = explode(",", $selected_items->stage_ids);
                $board->selected_collabs = explode(",", $selected_items->collaborator_ids);
           }
           else
           {
            $board->selected_swimlanes = [];
            $board->selected_stages = [];
            $board->selected_collabs = [];
           }
           
        }

        if (empty($WorkloadMappings)) {
            Flash::error('Workload Mapping not found');

            return redirect(route('workload_mapping.index'));
        }

        return view('workload_mapping.edit')->with('WorkloadMappings', $WorkloadMappings)->with('boards', $boards)->with('levels', $levels);
    }

    public function update($id, Request $request)
    {
        $validated = $request->validate([
            'level_select' => 'required_without:level_new',
            'level_new' => 'required_without:level_select'
        ]);

        if($request->level_new != "")
        {
            $g_ss_map_level = WorkloadMappingLevels::create(["label" => $request->level_new]);
            $level_id = $g_ss_map_level->id;
        }else
        {
            $level_id = $request->level_select;
        }

        $WorkloadMappings = WorkloadMappings::find($id);
        $WorkloadMappings->level_id = $level_id;
        $WorkloadMappings->label = $request->label;
        $WorkloadMappings->save();

        $workload_map_relations = [];
        foreach($request->boards as $b)
        {
            $workload_map_relations_single = [];
            $workload_map_relations_single['workload_mapping_id'] = $id;
            $workload_map_relations_single['board_id'] = $b;

            if(isset($request->swimlanes[$b]) && count($request->swimlanes[$b]) > 0)
            {
                $workload_map_relations_single['swimlane_ids'] = implode(',',$request->swimlanes[$b]);
            }
            if(isset($request->stages[$b]) && count($request->stages[$b]) > 0)
            {
                $workload_map_relations_single['stage_ids'] = implode(',',$request->stages[$b]);
            }

            if(isset($request->collabs[$b]) && count($request->collabs[$b]) > 0)
            {
                $workload_map_relations_single['collaborator_ids'] = implode(',',$request->collabs[$b]);
            }

            if(isset($request->swimlanes[$b]) && isset($request->stages[$b]) && isset($request->collabs[$b]))
            {
                array_push($workload_map_relations, $workload_map_relations_single);
            }
            
            
        }

        WorkloadRelations::where('workload_mapping_id', $id)->delete();

        if(count($workload_map_relations) > 0)
        {
            WorkloadRelations::insert($workload_map_relations);
        }

        
        Flash::success('Workload Mapping updated successfully.');

        return redirect(route('workload_mapping.index'));
    }

    public function destroy($id)
    {
        /** @var WorkloadMappings $WorkloadMappings */
        $WorkloadMappings = WorkloadMappings::find($id);

        if (empty($WorkloadMappings)) {
            Flash::error('Mapping not found');

            return redirect(route('workload_mapping.index'));
        }

        $WorkloadMappings->delete();

        Flash::success('Mapping deleted successfully.');

        return redirect(route('workload_mapping.index'));
    }
}