<?php

namespace App\Livewire\Cards;

use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use App\Models\Attendee;

class GenericAttendanceModal extends Component
{
    public $card, $name, $phone_no, $people_no, $timeslots, $attendee;

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

        if (Auth::user()) {
            if ($card->attendees()->where('user_id', Auth::user()->id)->count() > 0) {
                $this->attendee = $card->attendees()->where('user_id', auth()->user()->id)->first();
                $this->name = $this->attendee->name;
                $this->phone_no = $this->attendee->phone_no;
                $this->people_no = $this->attendee->people_no;
                $this->timeslots = $this->attendee->timeslots;
            } else {
                $this->name = auth()->user()->name;
                $this->phone_no = auth()->user()->phone_no;
            }
        }

    }

    public function save()
    {
        $this->validate([
            'name' => 'required',
            'phone_no' => 'required',
            'people_no' => 'required',
            'timeslots' => 'required',
        ]);

        $attendee = $this->card->attendees()->updateOrCreate([
            'generic_card_id' => $this->card->id,
            'user_id' => auth()->user()->id,
        ], [
            'card_id' => null,
            'generic_card_id' => $this->card->id,
            'name' => $this->name,
            'phone_no' => $this->phone_no,
            'people_no' => $this->people_no,
            'timeslots' => $this->timeslots,
        ]);

        redirect()->route('cards.show.generic', $this->card->id);
    }

    public function render()
    {
        return view('livewire.cards.generic-attendance-modal');
    }
}
