<?php

namespace App\Http\Livewire;

use Livewire\Component;

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

    public $changed = false;

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

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

        $this->course_colors = \App\Models\CourseColor::get();
        foreach ($this->course_colors as $color) {
            $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');
    }
}
