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

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

use DataTables;

class InvoiceController extends AppBaseController
{

    public function index(Request $request)
    {
        $boards = Boards::get();

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

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

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

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

            return view('invoice.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 = InvoiceMappingLevels::whereIn("id", InvoiceMappings::pluck("level_id"))->get();
            }
            else
            {
                $level_ids = RoleLevels::where('role_id', $role_id)->where('type', 'invoice')->pluck('level_id');

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

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

        
    }
    /**
     * Display a listing of the Swimline Report.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function get_invoice_data(Request $request)
    {
        $data = [];

        if($request->board && $request->board != "")
        {

            $board = Boards::find($request->board);
                $mappings = InvoiceMappings::with(['invoice_relations' => function($q) use($board, $request) {
                    $q->where("board_id", $board->id);
                }])->where("level_id", $request->level_select)->get();

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

        }
        return Datatables::of($data)
                    ->make(true);

    }


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

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

        foreach($mappings as $key_map => $mapping)
        {
            $mapped_swimlanes_inner = [];
            $mapped_stages_inner = [];

            $horizontal_total = 0;
            foreach($mapping->invoice_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));
                
            }

            $qry = BoardTasks::where('board_id',$board->id)->whereIn('kb_swimlane_id', $mapped_swimlanes_inner)->whereIn('kb_workflow_stage_id', $mapped_stages_inner);

            $tasks = $qry->get();

            foreach($tasks as $task)
            {
                $timer = 0;

                // foreach($task->timers as $tt)
                // {
                //     $from = Carbon::parse($tt->started_at);
                //     $to = Carbon::parse($tt->ended_at);
                //     $diff = $to->diffInSeconds($from);

                //     $timer = $timer + $diff;
                // }

                $timer = $task->timers_total;


                $timer_text = get_time_text($timer);
                $estimated_timer_text = get_time_text($task->time_estimate);

                $single_task_arr = [];

                $single_task_arr["name"] = $task->name;
                $single_task_arr["estimated_time"] = $estimated_timer_text;
                $single_task_arr["actual_time"] = $timer_text;
                $single_task_arr["invoice"] = $task->invoice;
                $single_task_arr["time_percent"] = ($task->time_estimate) ? number_format(($timer * 100) / $task->time_estimate, 2) : 0;
                if($timer != "" && $timer != 0 && $task->invoice != "")
                {
                    $single_task_arr["fee"] = number_format($task->invoice / ($timer/60/60), 2);
                }
                else
                {
                    $single_task_arr["fee"] = "";
                }

                array_push($data, $single_task_arr);

            }
        }

        return $data;

    }
}