<?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\InvoiceMappings;
use App\Models\InvoiceRelations;
use App\Models\InvoiceMappingLevels;

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

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

        foreach($InvoiceMappings as $im)
        {
            foreach($im->invoice_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('invoice_mapping.index')
            ->with('InvoiceMappings', $InvoiceMappings);

    }

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

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

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

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

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

        $invoice_map_relations = [];
        foreach($request->boards as $b)
        {
            $invoice_map_relations_single = [];
            $invoice_map_relations_single['invoice_mapping_id'] = $invoice_map->id;
            $invoice_map_relations_single['board_id'] = $b;

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

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

        if(count($invoice_map_relations) > 0)
        {
            InvoiceRelations::insert($invoice_map_relations);
        }

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

    }

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

        $boards = Boards::get();

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

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

           $board->tree_stages = $tree;

           $selected_items = InvoiceRelations::where("invoice_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($InvoiceMappings)) {
            Flash::error('Invoice Mapping not found');

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

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


        $invoice_map_relations = [];
        foreach($request->boards as $b)
        {
            $invoice_map_relations_single = [];
            $invoice_map_relations_single['invoice_mapping_id'] = $id;
            $invoice_map_relations_single['board_id'] = $b;

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

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

        InvoiceRelations::where('invoice_mapping_id', $id)->delete();

        if(count($invoice_map_relations) > 0)
        {
            InvoiceRelations::insert($invoice_map_relations);
        }

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

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

    }

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

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

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

        $InvoiceMappings->delete();

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

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