<?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\ExceptionMappings;
use App\Models\ExceptionRelations;
use App\Models\ExceptionMappingLevels;

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

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

        foreach($ExceptionMappings as $im)
        {
            foreach($im->exception_relations as $ir)
            {
                if($ir->swimlane_ids != "")
                {
                    $ir->swimlane_names = BoardSwimlanes::whereIn("swimlane_id", explode(',', $ir->swimlane_ids))->pluck('name')->implode(', ');
                }

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

            }

        }

        return view('exception_mapping.index')
            ->with('ExceptionMappings', $ExceptionMappings);

    }

    /**
     * Show the form for creating a new KanbanAccounts.
     *
     * @return Response
     */
    public function create()
    {
        $boards = Boards::get();
        $levels = ExceptionMappingLevels::whereIn("id", ExceptionMappings::pluck("level_id"))->get();

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

           $board->tree_stages = $tree;
        }
        
        return view('exception_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 = ExceptionMappingLevels::create(["label" => $request->level_new]);
            $level_id = $g_ss_map_level->id;
        }else
        {
            $level_id = $request->level_select;
        }

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

        $exception_map_relations = [];
        foreach($request->boards as $b)
        {
            $exception_map_relations_single = [];
            $exception_map_relations_single['exception_mapping_id'] = $exception_map->id;
            $exception_map_relations_single['board_id'] = $b;

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

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

        if(count($exception_map_relations) > 0)
        {
            ExceptionRelations::insert($exception_map_relations);
        }

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

    }

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

        $boards = Boards::get();

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

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

           $board->tree_stages = $tree;

           $selected_items = ExceptionRelations::where("exception_mapping_id", $id)->where("board_id", $board->id)->select("swimlane_ids", "stage_ids")->first();

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

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

            return redirect(route('exception_mapping.index'));
        }
        
        return view('exception_mapping.edit')->with('ExceptionMappings', $ExceptionMappings)->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 = ExceptionMappingLevels::create(["label" => $request->level_new]);
            $level_id = $g_ss_map_level->id;
        }else
        {
            $level_id = $request->level_select;
        }

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


        $exception_map_relations = [];
        foreach($request->boards as $b)
        {
            $exception_map_relations_single = [];
            $exception_map_relations_single['exception_mapping_id'] = $id;
            $exception_map_relations_single['board_id'] = $b;

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

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

        ExceptionRelations::where('exception_mapping_id', $id)->delete();

        if(count($exception_map_relations) > 0)
        {
            ExceptionRelations::insert($exception_map_relations);
        }

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

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

    }

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

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

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

        $ExceptionMappings->delete();

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

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