<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Http\Middleware\TenantMiddleware;

class CalendarSettings extends Component
{
    public $course_colors = [];
    public $colors = [];

    public $changed = false;

    public function boot()
    {
        app(TenantMiddleware::class)->setupTenantConnection();
    }

    public function mount()
    {
        $this->changed = false;

        $course_names = [];
        $courses = \App\Models\Course::select('name')->where('enabled', true)->groupBy('name')->orderBy('name', 'asc')->get();
        foreach ($courses as $course) {
            $name = $course->name;
            array_push($course_names, $name);
            if (!\App\Models\CourseColor::where('name', $name)->exists()) {
                \App\Models\CourseColor::create([
                    'name' => $name,
                    'hex' => '#d6c7fe',
                ]);
            }
        }
        $course_names = array_values(array_unique($course_names));

        $this->course_colors = \App\Models\CourseColor::get();
        foreach ($this->course_colors as $index => $color) {
            if (!in_array($color->name, $course_names)) {
                unset($this->course_colors[$index]);
                continue;
            }

            $this->colors[$color->id] = $color->hex;
        }
    }

    public function render()
    {
        return view('livewire.calendar_settings');
    }

    public function updatedColors() {
        $this->changed = true;
    }

    public function store() {
        foreach ($this->colors as $id => $hex) {
            \App\Models\CourseColor::whereId($id)->update([
                'hex' => $hex,
            ]);
        }

        $this->changed = false;

        $this->emit('success');
    }
}
