<?php

namespace App\Livewire\Cards;

use Livewire\Component;
use Illuminate\Support\Facades\Auth;

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

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

        if (Auth::user()) {
            if ($card->attendees()->where('user_id', Auth::user()->id)->count() > 0) {
                $card->attendee = $card->attendees()->where('user_id', auth()->user()->id)->first();
                $this->name = $card->attendee->name;
                $this->phone_no = $card->attendee->phone_no;
                $this->people_no = $card->attendee->people_no;
                $this->timeslots = $card->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([
            'user_id' => auth()->user()->id,
        ], [
            'name' => $this->name,
            'phone_no' => $this->phone_no,
            'people_no' => $this->people_no,
            'timeslots' => $this->timeslots,
        ]);

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

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