Your IP : 216.73.216.130


Current Path : /home/forge/stage.sksb.smartcon-survey.com/app/Livewire/
Upload File :
Current File : /home/forge/stage.sksb.smartcon-survey.com/app/Livewire/CustomSplitBarChart.php

<?php

namespace App\Livewire;

use App\Filters\AgeFilter;
use App\Filters\PositionFilter;
use App\Models\Department;
use App\Models\Interview;
use App\Models\JobType;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Livewire\Component;

class CustomSplitBarChart extends Component
{
    public array $data;

    public array $labels;

    public array $changes = [];

    public string $currentTab;

    public int $topicId;

    public string $question;

    public string $title;

    final public function render(): View
    {

        $interviews = Interview::where([
            ['topic_id', $this->topicId],
            ['is_test', 0],
        ])->whereRaw('YEAR(created_at) >= YEAR(NOW()) - 1')->get();

        // Add total to labels:
        $base = $this->current($interviews)->count();
        // TODO: Refactor this (too many queries, performance issues)
        $totalVal = $this->getValue($this->current($interviews));
        $totalLastQuarterVal = $this->getValue($this->lastQuarter($interviews));

        $this->title = $this->question !== 'all' ? 'Anteil vollständig/eher zustimmende' : 'Anteil (sehr) zufriedener';

        $this->data[] = [
            'name' => 'Total',
            'info' => "Total<br> (n=$base)",
            'change' => $totalVal - $totalLastQuarterVal,
            'value' => $totalVal,
        ];

        if ($this->currentTab === 'department') {
            $labels = Department::all(['id', 'name'])->toArray();
            foreach ($labels as $k => $dep) {
                $id = $dep['id'];
                $baseInterviews = $interviews->filter(fn ($interview) => $interview->department_id == $id);
                $base = $this->current($baseInterviews)->count();
                $labels[$k]['name'] .= " (n=$base)";
                $this->data[] = [
                    'name' => $dep['name'],
                    'info' => $dep['name']." (n=$base)",
                    'value' => $this->getValue(
                        $this->current($baseInterviews)
                    ),
                    'change' => $this->getChange($baseInterviews),
                ];
            }

            $this->title = 'Abteilung';
        } elseif ($this->currentTab === 'jobtype') {
            $labels = JobType::all(['id', 'name'])->toArray();
            foreach ($labels as $k => $dep) {
                $id = $dep['id'];
                $baseInterviews = $interviews->filter(fn ($interview) => $interview->job_type == $id);
                $base = $this->current($baseInterviews)->count();
                $labels[$k]['name'] .= " (n=$base)";
                $this->data[] = [
                    'name' => $dep['name'],
                    'info' => $dep['name']." (n=$base)",
                    'value' => $this->getValue(
                        $this->current($baseInterviews)
                    ),
                    'change' => $this->getChange($baseInterviews),
                ];
            }

            $this->title = 'Arbeitszeit';
        } elseif ($this->currentTab === 'age') {
            $labels = AgeFilter::getFilters();
            foreach ($labels as $ageGroup) {
                $min = $ageGroup['min'];
                $max = $ageGroup['max'];
                $baseInterviews = $interviews->filter(fn ($interview) => $interview->age >= $min && $interview->age <= $max);
                $base = $this->current($baseInterviews)->count();
                $this->data[] = [
                    'name' => $ageGroup['name'],
                    'info' => $ageGroup['name']." (n=$base)",
                    'value' => $this->getValue(
                        $this->current($baseInterviews)
                    ),
                    'change' => $this->getChange($baseInterviews),
                ];
            }
            $this->title = 'Alter';
        } else {
            $labels = PositionFilter::getFilters();
            foreach ($labels as $position) {
                $id = $position['id'];
                $baseInterviews = $interviews->filter(fn ($interview) => $interview->leading_pos == $id);
                $base = $this->current($baseInterviews)->count();
                $this->data[] = [
                    'name' => "{$position['name']}",
                    'info' => "{$position['name']} (n=$base)",
                    'value' => $this->getValue(
                        $this->current($baseInterviews)
                    ),
                    'change' => $this->getChange($baseInterviews),
                ];
            }
            $this->title = 'Führungsposition';
        }

        return view('livewire.custom-split-bar-chart', [
            'legend' => $legend ?? 0,
        ]);
    }

    private function getChange(Collection $interviews)
    {
        $currentVal = $this->getValue($this->current($interviews));
        $lastVal = $this->getValue($this->lastQuarter($interviews));

        return $currentVal - $lastVal;
    }

    private function current(Collection $interviews)
    {
        return $interviews->filter(function ($int) {
            $now = Carbon::now();
            $date = $int->created_at;

            return $date->year == $now->year
                && $date->quarter == $now->quarter;
        });
    }

    private function lastQuarter(Collection $interviews): Collection
    {
        $now = Carbon::now()->subQuarter();

        return $interviews->filter(function ($int) use ($now) {
            $date = $int->created_at;

            return $date->year == $now->year
                && $date->quarter == $now->quarter;
        });
    }

    public function getValue($interviews): float
    {
        $top2 = $this->gettop2($interviews)->count();
        $total = $this->getAllAnswers($interviews)->count();

        if ($total <= 0) {
            return 0;
        }

        return round(
            $top2 / $total * 100,
            2
        );
    }

    public function getAllAnswers($interviews)
    {
        return $interviews
            ->map(function ($interview) {

                if ($this->question != 'all') {
                    return array_values(array_filter($interview->answers, fn ($key) => $key == $this->question, ARRAY_FILTER_USE_KEY));
                } else {
                    return $interview->answers;
                }
            })
            ->flatten()
            ->filter(fn ($answer) => is_numeric($answer));
    }

    public function gettop2($interviews)
    {
        return $interviews->map(function ($interview) {
            if ($this->question != 'all') {
                return array_values(array_filter($interview->answers, fn ($key) => $key == $this->question, ARRAY_FILTER_USE_KEY));
            } else {
                return $interview->answers;
            }
        })->flatten()->filter(fn ($answer) => is_numeric($answer) && in_array($answer, [1, 2]));
    }
}