<?php

namespace App\Http\Controllers;

use App\Http\Controllers\AppBaseController;

use App\Models\KanbanAccounts;
use App\Models\BoardSwimlanes;
use App\Models\Boards;
use App\Models\BoardTasks;
use App\Models\WorkloadMappings;
use App\Models\WorkloadRelations;
use App\Models\BoardCollaborators;
use App\Models\DailyWorkloadSnapshot;
use App\Models\WorkloadMappingLevels;
use App\Models\RoleLevels;

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

class WorkloadController extends AppBaseController
{
    /**
     * Display a listing of the Swimline Report.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $boards = Boards::orderBy('order')->get();

        

        if(isset($request->date) && $request->date!="")
        {
            $role_id = \Auth::user()->role->id;
            
            if($role_id == 1)
            {
                $levels = WorkloadMappingLevels::get();
            }
            else
            {
                $level_ids = RoleLevels::where('role_id', $role_id)->where('type', 'workload')->pluck('level_id');

                $levels = WorkloadMappingLevels::whereIn("id", $level_ids)->get();
            }

            $newDate = Carbon::createFromFormat('d-m-Y', $request->date)
                                    ->format('Y-m-d');

            $data['head'] = DailyWorkloadSnapshot::where('type', 'head')->where("level_id", $request->level_select)->where('date', $newDate)->first();
            $data['body'] = DailyWorkloadSnapshot::where('type', 'body')->where("level_id", $request->level_select)->where('date', $newDate)->get();
            $data['vertical_total'] = DailyWorkloadSnapshot::where('type', 'vertical_t')->where("level_id", $request->level_select)->where('date', $newDate)->first();

            // echo "<pre>";
            // print_r(json_decode($data['body'][0]->data));
            // exit;

            return view('workload.snapshot')
                ->with('boards', $boards)->with('data', $data)->with('request',$request)->with('levels', $levels);
        }
        else
        {
            $role_id = \Auth::user()->role->id;
            
            if($role_id == 1)
            {
                $levels = WorkloadMappingLevels::whereIn("id", WorkloadMappings::pluck("level_id"))->get();
            }
            else
            {
                $level_ids = RoleLevels::where('role_id', $role_id)->where('type', 'workload')->pluck('level_id');

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

            $mappings = WorkloadMappings::where("level_id", $request->level_select)->get();

            $data = [];
            $data['mapped']=[];
            $data['notmapped']=[];

            $data = $this->process_data($boards, $mappings, $data, $request);

            return view('workload.index')
                ->with('boards', $boards)->with('data', $data)->with('request',$request)->with('levels', $levels);
        }

    }

    public function process_data($boards, $mappings, $data, $request = null)
    {

        $data['vertical_total'] = [];

        
        $collab_ids = [];
        foreach($mappings as $m)
        {
            foreach($m->workload_relations as $wr)
            {
                $collabs = explode(",",$wr->collaborator_ids);

                $collab_ids = array_merge($collabs, $collab_ids);
            }
        }
        
        $collab_ids = array_unique($collab_ids);

        $mapped_swimlanes = [];
        $mapped_stages = [];
        $vertical_total = [];

        foreach($collab_ids as $collab)
        {
            $collab_detail = BoardCollaborators::where('collaborator_id', $collab)->first();
            if($collab_detail)
            {
               $staff_name = strtoupper($collab_detail->name);
               $horizontal_total = 0;
               $horizontal_logged_total = 0;
               $horizontal_task_total = 0;
               foreach($mappings as $key_map => $mapping)
                {
                    $mapped_swimlanes_inner = [];
                    $mapped_stages_inner = [];
                    
                    foreach($mapping->workload_relations as $sr)
                    {
                        $mapped_swimlanes_inner = array_merge($mapped_swimlanes_inner,explode(',', $sr->swimlane_ids));

                        $mapped_stages_inner = array_merge($mapped_stages_inner,explode(',', $sr->stage_ids));
                        
                    }
                    foreach($boards as $kb => $b)
                    {
                        $data['mapped'][$staff_name][$key_map][0]=$staff_name;
                        $qry = BoardTasks::where('board_id',$b->id)->whereIn('kb_swimlane_id', $mapped_swimlanes_inner)->whereIn('kb_workflow_stage_id', $mapped_stages_inner);

                        $qry->where('assigned_user_id',$collab_detail->collaborator_id);

                        $task_count = $qry->count();
                        $time_count = $qry->sum('time_estimate');
                        $logged_time_count = $qry->sum('timers_total');
                        $vertical_total[$kb] = array("task_total" => ((isset($vertical_total[$kb]["task_total"])) ? $vertical_total[$kb]["task_total"] : 0) + $task_count, "time_total" => ((isset($vertical_total[$kb]["time_total"])) ? $vertical_total[$kb]["time_total"] : 0) + $time_count , "logged_time_total" => ((isset($vertical_total[$kb]["logged_time_total"])) ? $vertical_total[$kb]["logged_time_total"] : 0) + $logged_time_count);
                        $data['mapped'][$staff_name][$key_map][$b->id]["task"] = isset($data['mapped'][$staff_name][$key_map][$b->id]["task"]) ? $data['mapped'][$staff_name][$key_map][$b->id]["task"] + $task_count : $task_count;
                        $data['mapped'][$staff_name][$key_map][$b->id]["time"] = isset($data['mapped'][$staff_name][$key_map][$b->id]["time"]) ? $data['mapped'][$staff_name][$key_map][$b->id]["time"] + $time_count : $time_count;
                        $data['mapped'][$staff_name][$key_map][$b->id]["logged_time"] = isset($data['mapped'][$staff_name][$key_map][$b->id]["logged_time"]) ? $data['mapped'][$staff_name][$key_map][$b->id]["logged_time"] + $logged_time_count : $logged_time_count;
                        $horizontal_total = $horizontal_total+$time_count;
                        $horizontal_logged_total = $horizontal_logged_total+$logged_time_count;
                        $horizontal_task_total = $horizontal_task_total+$task_count;
                    }
                    if(isset($data['mapped'][$staff_name][$key_map][(count($boards) + 1)]["time_total"]))
                    {
                        $horizontal_total = $data['mapped'][$staff_name][$key_map][(count($boards) + 1)]["time_total"] + $horizontal_total;
                        $horizontal_logged_total = $data['mapped'][$staff_name][$key_map][(count($boards) + 1)]["logged_time_total"] + $horizontal_logged_total;
                        $horizontal_task_total = $data['mapped'][$staff_name][$key_map][(count($boards) + 1)]["task_total"] + $horizontal_task_total;
                    }

                    $data['mapped'][$staff_name][$key_map][(count($boards) + 1)]= array("time_total" => $horizontal_total,"logged_time_total" => $horizontal_logged_total, "task_total" => $horizontal_task_total);
                } 
            }
        }

        $data['vertical_total'] = $vertical_total;

        return $data;

    }

    public function process_data_dashboard($boards, $mappings, $data, $request = null)
    {

        $data_new = [];

        $data['vertical_total'] = [];

        
        $collab_ids = [];
        foreach($mappings as $m)
        {
            foreach($m->workload_relations as $wr)
            {
                $collabs = explode(",",$wr->collaborator_ids);

                $collab_ids = array_merge($collabs, $collab_ids);
            }
        }
        
        $collab_ids = array_unique($collab_ids);

        $mapped_swimlanes = [];
        $mapped_stages = [];
        $vertical_total = [];

        foreach($collab_ids as $collab)
        {
            $collab_detail = BoardCollaborators::where('collaborator_id', $collab)->first();
            if($collab_detail)
            {
               $staff_name = strtoupper($collab_detail->name);
               $horizontal_total = 0;
               $horizontal_logged_total = 0;
               $horizontal_task_total = 0;
               foreach($mappings as $key_map => $mapping)
                {
                    $mapped_swimlanes_inner = [];
                    $mapped_stages_inner = [];
                    
                    foreach($mapping->workload_relations as $sr)
                    {
                        $mapped_swimlanes_inner = array_merge($mapped_swimlanes_inner,explode(',', $sr->swimlane_ids));

                        $mapped_stages_inner = array_merge($mapped_stages_inner,explode(',', $sr->stage_ids));
                        
                    }
                    foreach($boards as $kb => $b)
                    {
                        $data['mapped'][$staff_name][$key_map][0]=$staff_name;
                        $qry = BoardTasks::where('board_id',$b->id)->whereIn('kb_swimlane_id', $mapped_swimlanes_inner)->whereIn('kb_workflow_stage_id', $mapped_stages_inner);

                        $qry->where('assigned_user_id',$collab_detail->collaborator_id);

                        $task_count = $qry->count();
                        $time_count = $qry->sum('time_estimate');
                        $logged_time_count = $qry->sum('timers_total');
                        $vertical_total[$kb] = array("task_total" => ((isset($vertical_total[$kb]["task_total"])) ? $vertical_total[$kb]["task_total"] : 0) + $task_count, "time_total" => ((isset($vertical_total[$kb]["time_total"])) ? $vertical_total[$kb]["time_total"] : 0) + $time_count , "logged_time_total" => ((isset($vertical_total[$kb]["logged_time_total"])) ? $vertical_total[$kb]["logged_time_total"] : 0) + $logged_time_count);
                        $data['mapped'][$staff_name][$key_map][$b->id]["task"] = isset($data['mapped'][$staff_name][$key_map][$b->id]["task"]) ? $data['mapped'][$staff_name][$key_map][$b->id]["task"] + $task_count : $task_count;
                        $data['mapped'][$staff_name][$key_map][$b->id]["time"] = isset($data['mapped'][$staff_name][$key_map][$b->id]["time"]) ? $data['mapped'][$staff_name][$key_map][$b->id]["time"] + $time_count : $time_count;
                        $data['mapped'][$staff_name][$key_map][$b->id]["logged_time"] = isset($data['mapped'][$staff_name][$key_map][$b->id]["logged_time"]) ? $data['mapped'][$staff_name][$key_map][$b->id]["logged_time"] + $logged_time_count : $logged_time_count;
                        $horizontal_total = $horizontal_total+$time_count;
                        $horizontal_logged_total = $horizontal_logged_total+$logged_time_count;
                        $horizontal_task_total = $horizontal_task_total+$task_count;
                    }
                    if(isset($data['mapped'][$staff_name][$key_map][(count($boards) + 1)]["time_total"]))
                    {
                        $horizontal_total = $data['mapped'][$staff_name][$key_map][(count($boards) + 1)]["time_total"] + $horizontal_total;
                        $horizontal_logged_total = $data['mapped'][$staff_name][$key_map][(count($boards) + 1)]["logged_time_total"] + $horizontal_logged_total;
                        $horizontal_task_total = $data['mapped'][$staff_name][$key_map][(count($boards) + 1)]["task_total"] + $horizontal_task_total;
                    }

                    $data['mapped'][$staff_name][$key_map][]= array("time_total" => $horizontal_total,"logged_time_total" => $horizontal_logged_total, "task_total" => $horizontal_task_total);
                } 
            }
        }

        $data['vertical_total'] = $vertical_total;

        foreach($boards as $kb => $b)
        {
            $data_new[$kb]['name'] = $b->name;
            $data_new[$kb]['total'] = $this->vertical_string($vertical_total[$kb]);

        }

        return $data_new;

    }

    public function vertical_string($vertical_total)
    {
        $str = [];

        $str ['task']= "Tasks: ".$vertical_total["task_total"];

        if(($vertical_total["time_total"] / 60) > 59)
        {
            $str['et']=  "ET : ".number_format((($vertical_total["time_total"] / 60) / 60),2)." Hrs";
        }
        else
        {
            $str['et']=  "ET : ".number_format((($vertical_total["time_total"] / 60)),2)." Mins";
        }

        if(($vertical_total["logged_time_total"] / 60) > 59)
        {
            $str['lt']=  "  LT : ".number_format((($vertical_total["logged_time_total"] / 60) / 60),2)." Hrs";
        }
        else
        {
            $str['lt']=  "  LT : ".number_format((($vertical_total["logged_time_total"] / 60)),2)." Mins";
        }

        return $str;

    }
}