<?php

namespace App\Http\Livewire;

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

class Presence extends Component
{

    public $calendar;

    public $records;

    public $member_ids = [];

    public $court_id, $instructor_id, $motivation_id, $motivation_manual_id, $note, $manual;
    public $save_court_id, $save_instructor_id, $save_notes;

    public $newMemberFirstName, $newMemberLastName, $newMemberEmail, $newMemberToComplete, $newMemberFiscalCode, $newMemberFiscalCodeExist, $newMemberMotivationId;
    public $newMemberExists = false;

    public $userName, $userEmail;

    public $added = false;

    public $filter = '';

    public $courts = [];
    public $instructors = [];
    public $motivations = [];
    public $motivations_add = [];

    public $insertUser = 'exist';
    public $course_limit;
    public $motivation_course_id = null;
    public $motivation_course_name = 0;
    public $motivation_course_level = 0;
    public $motivation_course_type = 0;
    public $motivation_course_frequency = 0;

    public $course_names = [];
    public $course_levels = [];
    public $course_types = [];
    public $course_frequencies = [];

    public $members = [];

    public $add_member_id = 0;
    public $add_member_courses = [];

    public $newMembers = [];

    public $ids = [];

    public function mount()
    {

        setlocale(LC_ALL, 'it_IT');

        $this->calendar = \App\Models\Calendar::findOrFail($_GET["calendarId"]);
        $this->court_id = $this->calendar->court_id;
        $this->instructor_id = $this->calendar->instructor_id;
        $this->motivation_manual_id = $this->calendar->motivation_manual_id;
        $this->manual = $this->calendar->manual;
        $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
            ->where(function ($query) {
                $query->where('is_archived', false)
                    ->orWhereNull('is_archived');
            })
            ->where(function ($query) {
                $query->where('is_deleted', false)
                    ->orWhereNull('is_deleted');
            })->orderBy('last_name')->orderBy('first_name')->get();
        $this->note = $this->calendar->note;
        $this->courts = \App\Models\Court::select('*')->where('enabled', true)->get();
        $this->instructors = \App\Models\User::select('*')->where('level', 2)->where('enabled', true)->orderBy('name', 'asc')->get();
        $this->motivations = \App\Models\Motivation::select('*')->where('enabled', true)->where('type', 'del')->get();
        $this->motivations_add = \App\Models\Motivation::select('*')->where('enabled', true)->where('type', 'add')->get();
        $this->save_court_id = 0;
        $this->save_instructor_id = 0;
        $this->save_notes = '';

        $this->insertUser = 'exist';
        $this->course_limit = now()->endOfDay();

        // $this->course_names = \App\Models\Course::whereDate('date_from', '<=', $this->course_limit)->whereDate('date_to', '>=', $this->course_limit)->where('active', true)->where('enabled', true)->orderBy('name')->groupBy('name')->pluck('name');
        $this->course_names = [];
        $this->course_levels = [];
        $this->course_types = [];
        $this->course_frequencies = [];

        $this->newMemberExists = false;
    }

    public function updatedAddMemberId()
    {
        if ($this->insertUser == 'exist') {
            $this->add_member_courses = \App\Models\MemberCourse::where('member_id', $this->add_member_id)->groupBy('course_id')->pluck('course_id');
            $this->course_names = \App\Models\Course::whereDate('date_from', '<=', $this->course_limit)->whereDate('date_to', '>=', $this->course_limit)->where('active', true)->where('enabled', true)->whereIn('id', $this->add_member_courses)->orderBy('name')->groupBy('name')->pluck('name');
            $this->course_levels = [];
            $this->course_types = [];
            $this->course_frequencies = [];

            $this->motivation_course_id = null;
            $this->motivation_course_name = 0;
            $this->motivation_course_level = 0;
            $this->motivation_course_type = 0;
            $this->motivation_course_frequency = 0;
        }
    }

    public function updatedInsertUser()
    {
        $this->add_member_id = 0;

        if ($this->insertUser == 'exist') {
            $this->course_names = [];
        } else {
            $this->course_names = \App\Models\Course::whereDate('date_from', '<=', $this->course_limit)->whereDate('date_to', '>=', $this->course_limit)->where('active', true)->where('enabled', true)->orderBy('name')->groupBy('name')->pluck('name');
        }

        $this->course_levels = [];
        $this->course_types = [];
        $this->course_frequencies = [];

        $this->motivation_course_id = null;
        $this->motivation_course_name = 0;
        $this->motivation_course_level = 0;
        $this->motivation_course_type = 0;
        $this->motivation_course_frequency = 0;

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

    function updatedMotivationCourseName()
    {
        if ($this->motivation_course_name > 0 && $this->motivation_course_name != '') {
            $this->motivation_course_id = null;
            $this->motivation_course_level = 0;
            $this->motivation_course_type = 0;
            $this->motivation_course_frequency = 0;

            $levels_ids = [];
            $levels_query = \App\Models\Course::whereDate('date_from', '<=', $this->course_limit)->whereDate('date_to', '>=', $this->course_limit)->where('active', true)->where('enabled', true)->where('name', $this->motivation_course_name);
            if ($this->insertUser == 'exist') {
                $levels_query->whereIn('id', $this->add_member_courses);
            }
            $levels = $levels_query->get();

            foreach ($levels as $l) {
                $levels_ids[] = $l->course_level_id;
            }

            $this->course_levels = \App\Models\CourseLevel::where('enabled', true)->whereIn('id', $levels_ids)->orderBy('name')->get();
            $this->course_types = [];
            $this->course_frequencies = [];
        } else {
            $this->course_levels = [];
            $this->course_types = [];
            $this->course_frequencies = [];
        }
    }

    function updatedMotivationCourseLevel()
    {
        if ($this->motivation_course_name > 0 && $this->motivation_course_name != '' && $this->motivation_course_level > 0 && $this->motivation_course_level != '') {
            $this->motivation_course_id = null;
            $this->motivation_course_type = 0;
            $this->motivation_course_frequency = 0;

            $type_ids = [];
            $types_query = \App\Models\Course::whereDate('date_from', '<=', $this->course_limit)->whereDate('date_to', '>=', $this->course_limit)->where('active', true)->where('enabled', true)->where('name', $this->motivation_course_name)->where('course_level_id', $this->motivation_course_level);
            if ($this->insertUser == 'exist') {
                $types_query->whereIn('id', $this->add_member_courses);
            }
            $types = $types_query->get();
            foreach ($types as $t) {
                $type_ids[] = $t->course_type_id;
            }

            $this->course_types = \App\Models\CourseType::where('enabled', true)->whereIn('id', $type_ids)->orderBy('name')->get();
            $this->course_frequencies = [];
        } else {
            $this->course_types = [];
            $this->course_frequencies = [];
        }
    }

    function updatedMotivationCourseType()
    {
        if ($this->motivation_course_name > 0 && $this->motivation_course_name != '' && $this->motivation_course_level > 0 && $this->motivation_course_level != '' && $this->motivation_course_type > 0 && $this->motivation_course_type != '') {
            $this->motivation_course_id = null;
            $this->motivation_course_frequency = 0;

            $frequency_ids = [];
            $frequencies_query = \App\Models\Course::whereDate('date_from', '<=', $this->course_limit)->whereDate('date_to', '>=', $this->course_limit)->where('active', true)->where('enabled', true)->where('name', $this->motivation_course_name)->where('course_level_id', $this->motivation_course_level)->where('course_type_id', $this->motivation_course_type);
            if ($this->insertUser == 'exist') {
                $frequencies_query->whereIn('id', $this->add_member_courses);
            }
            $frequencies = $frequencies_query->get();

            foreach ($frequencies as $f) {
                $frequency_ids[] = $f->course_frequency_id;
            }

            $this->course_frequencies = \App\Models\CourseFrequency::where('enabled', true)->whereIn('id', $frequency_ids)->orderBy('name')->get();
        } else {
            $this->course_frequencies = [];
        }
    }

    function updatedMotivationCourseFrequency()
    {
        if ($this->motivation_course_name > 0 && $this->motivation_course_name != '' && $this->motivation_course_level > 0 && $this->motivation_course_level != '' && $this->motivation_course_type > 0 && $this->motivation_course_type != '' && $this->motivation_course_frequency > 0 && $this->motivation_course_frequency != '') {
            $this->motivation_course_id = null;

            $course_query = \App\Models\Course::whereDate('date_from', '<=', $this->course_limit)->whereDate('date_to', '>=', $this->course_limit)->where('active', true)->where('enabled', true)->where('name', $this->motivation_course_name)->where('course_level_id', $this->motivation_course_level)->where('course_type_id', $this->motivation_course_type)->where('course_frequency_id', $this->motivation_course_frequency);
            if ($this->insertUser == 'exist') {
                $course_query->whereIn('id', $this->add_member_courses);
            }
            $course = $course_query->first();

            $this->motivation_course_id = $course->id;
        } else {
            $this->motivation_course_id = null;
        }
    }

    public function updatedNewMemberMotivationId()
    {
        $this->emit('reload');
    }

    public function updatedNewMemberFirstName()
    {
        $this->checkUserExists();
    }

    public function updatedNewMemberLastName()
    {
        $this->checkUserExists();
    }

    private function checkUserExists(): void
    {
        $first = trim((string) $this->newMemberFirstName);
        $last = trim((string) $this->newMemberLastName);

        if ($first === '' || $last === '') {
            $this->newMemberExists = false;
            return;
        }

        $first = mb_strtolower($first);
        $last  = mb_strtolower($last);

        $this->newMemberExists = \App\Models\Member::query()
            ->where(function ($q) {
                $q->where('is_deleted', false)
                ->orWhereNull('is_deleted');
            })
            ->whereRaw('LOWER(TRIM(first_name)) = ?', [$first])
            ->whereRaw('LOWER(TRIM(last_name))  = ?', [$last])
            ->exists();
    }

    public function render()
    {

        $this->records = [];

        setlocale(LC_ALL, 'it_IT');

        $presenceMembers = [];

        if (!$this->manual) {

            // Carco tutti gli iscritti a un corso padre in quel giorno con un range orario simile
            $days = ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'];
            $dow = date('w', strtotime($this->calendar->from));
            $d = $days[$dow];

            $h = date('H:i', strtotime($this->calendar->from));
            $h_to = date('H:i', strtotime($this->calendar->to));

            // Elenco corsi per tipologia in base al calendario
            $courses = \App\Models\Course::where('name', $this->calendar->name)->where('date_from', '<=', $this->calendar->from)->where('date_to', '>=', $this->calendar->to)->pluck('id')->toArray();

            $months = date("n", strtotime($this->calendar->from));

            // Elenco utenti iscritti al corso "padre"
            // $members_courses = \App\Models\MemberCourse::where('when', 'like', "%" . $d . "%")
            //     ->where('when', 'like', '%"from":"' . $h . '"%')
            //     ->whereNot('months', 'like', '%"m":' . $months . ',"status":2%')
            //     ->whereDate('date_from', '<=', $this->calendar->from)                                 
            //     ->whereDate('date_to', '>=', $this->calendar->from)      
            //     ->whereIn('course_id', $courses)
            //     ->pluck('member_id')->toArray();

            // $members_courses = \App\Models\MemberCourse::whereRaw("JSON_CONTAINS(`when`, JSON_OBJECT('day', JSON_ARRAY(?), 'from', ?), '$')", [$d, $h])->where('months', 'like', '%"m":' . $months . ',%')->whereIn('course_id', $courses)->pluck('member_id')->toArray();
            $members_courses = \App\Models\MemberCourse::query()
                ->whereRaw("JSON_CONTAINS(`when`, JSON_OBJECT('day', JSON_ARRAY(?), 'from', ?, 'to', ?), '$')", [$d, $h, $h_to])
                ->whereRaw("JSON_CONTAINS(months, JSON_OBJECT('m', CAST(? AS UNSIGNED)), '$')", [$months])
                ->whereRaw("NOT JSON_CONTAINS(months, JSON_OBJECT('m', CAST(? AS UNSIGNED), 'status', 2), '$')", [$months])
                ->whereRaw("NOT JSON_CONTAINS(months, JSON_OBJECT('m', CAST(? AS UNSIGNED), 'status', '2'), '$')", [$months])
                ->whereIn('course_id', $courses)
                ->pluck('member_id')
                ->toArray();

            if ($this->filter != '') {
                $filter = $this->filter;
                $members = \App\Models\Member::whereIn('id', $members_courses)->where(function ($query) use ($filter) {
                    $query->whereRaw("CONCAT(first_name, ' ', last_name) like '%" . $filter . "%'")
                        ->orWhereRaw("CONCAT(last_name, ' ', first_name) like '%" . $filter . "%'");
                })
                    ->where(function ($query) {
                        $query->where('is_archived', false)
                            ->orWhereNull('is_archived');
                    })
                    ->where(function ($query) {
                        $query->where('is_deleted', false)
                            ->orWhereNull('is_deleted');
                    })->orderBy('last_name')->orderBy('first_name')->get();
            } else
                $members = \App\Models\Member::whereIn('id', $members_courses)
                    ->where(function ($query) {
                        $query->where('is_archived', false)
                            ->orWhereNull('is_archived');
                    })
                    ->where(function ($query) {
                        $query->where('is_deleted', false)
                            ->orWhereNull('is_deleted');
                    })->orderBy('last_name')->orderBy('first_name')->get();

            // $presences = \App\Models\Presence::where('calendar_id', $this->calendar->id)->pluck('member_id')->toArray();
            // $my_presences = \App\Models\Presence::where('calendar_id', $this->calendar->id)->where('user_id', \Auth::user()->id)->pluck('member_id')->toArray();

            foreach ($members as $member) {
                $presenceMembers[] = $member->id;
                //$this->member_ids[] = $member->id;
                $this->records[] = $this->getMember($member);
            }
        }

        // Aggiungo i membri iscritti
        $members_presences = \App\Models\Presence::where('calendar_id', $this->calendar->id)->whereNotIn('member_id', $presenceMembers)->pluck('member_id')->toArray();

        if ($this->filter != '') {
            $filter = $this->filter;
            $members = \App\Models\Member::whereIn('id', $members_presences)->where(function ($query) use ($filter) {
                $query->whereRaw("CONCAT(first_name, ' ', last_name) like '%" . $filter . "%'")
                    ->orWhereRaw("CONCAT(last_name, ' ', first_name) like '%" . $filter . "%'");
            })
                ->where(function ($query) {
                    $query->where('is_archived', false)
                        ->orWhereNull('is_archived');
                })
                ->where(function ($query) {
                    $query->where('is_deleted', false)
                        ->orWhereNull('is_deleted');
                })->get();
        } else
            $members = \App\Models\Member::whereIn('id', $members_presences)
                ->where(function ($query) {
                    $query->where('is_archived', false)
                        ->orWhereNull('is_archived');
                })
                ->where(function ($query) {
                    $query->where('is_deleted', false)
                        ->orWhereNull('is_deleted');
                })->get();

        foreach ($members as $member) {
            //$this->member_ids[] = $member->id;
            $this->records[] = $this->getMember($member);
        }

        foreach ($this->newMembers as $m) {
            $member = \App\Models\Member::findOrFail($m);
            //$this->member_ids[] = $member->id;
            $this->records[] = $this->getMember($member);
        }

        /*$calendars = \App\Models\Calendar::get();
        foreach($calendars as $c)
        {
            $this->records[] = array('id' => $c->id, 'title' => $c->course->name, 'start' => $c->from, 'end' => $c->to);
        }*/
        return view('livewire.presence');
    }

    public function getDateX()
    {
        setlocale(LC_ALL, 'it_IT');
        $days = ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'];
        $months = ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'];
        return $days[date('w', strtotime($this->calendar->from))] . " " . date("d", strtotime($this->calendar->from)) . " " . $months[date("n", strtotime($this->calendar->from)) - 1];
    }

    public function getMember($member)
    {
        $latestCert = \App\Models\MemberCertificate::where('member_id', $member->id)
            ->orderBy('expire_date', 'desc')
            ->first();

        $certificate = '';
        $y = "|";
        if ($latestCert) {
            $latest_date = $latestCert->expire_date;
            $status = '';
            if ($latest_date < date("Y-m-d")) {
                $status = "0"; // Expired
            } else if ($latest_date <= date("Y-m-d", strtotime("+1 month"))) {
                $status = "1"; // Expiring soon
            } else {
                $status = "2"; // Valid
            }
            $y = $status . "|" . date("d/m/Y", strtotime($latest_date));
        }

        $presence = false;
        $my_presence = false;
        $motivation = '';
        $status = 0;
        $court = '';
        $instructor = '';
        $additional_instructor = '';
        $notes = '';

        $has_presence = \App\Models\Presence::where('calendar_id', $this->calendar->id)->where('member_id', $member->id)->first();
        if ($has_presence) {
            $presence = true;
            $my_presence = $has_presence->user_id == \Auth::user()->id;
            if ($has_presence->motivation_id > 0) {
                $motivation = \App\Models\Motivation::findOrFail($has_presence->motivation_id)->name;
            }
            $status = $has_presence->status;
            $instructor = \App\Models\User::findOrFail($has_presence->user_id)->name;

            if ($has_presence->court_id > 0) {
                $court = \App\Models\Court::findOrFail($has_presence->court_id)->name;
            }
            if ($has_presence->instructor_id > 0 && $has_presence->instructor_id !== $has_presence->user_id) {
                $additional_instructor = \App\Models\User::findOrFail($has_presence->instructor_id)->name;
            }
            if (!is_null($has_presence->notes)) {
                $notes = $has_presence->notes;
            }
        }

        if (in_array($member->id, $this->newMembers)) {
            $presence = true;
            $my_presence = true;
        }

        return array(
            'id' => $member->id,
            'first_name' => $member->first_name,
            'last_name' => $member->last_name,
            'certificate' => $y,
            'presence' => $presence,
            'my_presence' => $my_presence,
            'status' => $status,
            'motivation' => $motivation,
            'court' => $court,
            'instructor' => $instructor,
            'additional_instructor' => $additional_instructor,
            'notes' => $notes,
        );
    }

    public function save($ids)
    {
        $this->saveAndStay($ids);
        $last_date = explode(" ", $this->calendar->from)[0];

        return redirect()->to("/calendar?last_date={$last_date}");
    }

    public function saveAndStay($ids)
    {
        $this->calendar->court_id = $this->court_id;
        $this->calendar->instructor_id = $this->instructor_id;
        $this->calendar->note = $this->note;
        if ($this->motivation_id != "" && $this->motivation_id != null)
            $this->calendar->motivation_id = $this->motivation_id;
        if ($this->motivation_manual_id != "" && $this->motivation_manual_id != null)
            $this->calendar->motivation_manual_id = $this->motivation_manual_id;
        $this->calendar->save();

        // $x = \App\Models\Presence::where('calendar_id', $this->calendar->id)->where('user_id', \Auth::user()->id)->where('status', '<>', 99)->first();
        // $mid = null;
        // if ($x) {
        //     $mid = $x->motivation_id;
        //     $x->delete();
        // }

        // Mappa degli ultimi motivation_id per ogni member_id dell'utente e calendario correnti
        $userId     = \Auth::user()->id;
        $calendarId = $this->calendar->id;

        $motivation_query = \App\Models\Presence::query()
            ->select('member_id', 'motivation_id', 'motivation_course_id')
            ->where('calendar_id', $calendarId)
            ->where('user_id', $userId)
            ->where('status', '<>', 99)
            ->whereIn('id', function ($q) use ($calendarId, $userId) {
                $q->selectRaw('MAX(id)')
                    ->from('presences')
                    ->where('calendar_id', $calendarId)
                    ->where('user_id', $userId)
                    ->where('status', '<>', 99)
                    ->groupBy('member_id');
            })
            ->get()
            ->keyBy('member_id');

        $motivationMap = $motivation_query->map(fn($row) => $row->motivation_id)->toArray();
        $motivationCourseMap = $motivation_query->map(fn($row) => $row->motivation_course_id)->toArray();

        // Elimino tutti i dati correnti che devono essere sostituiti
        \App\Models\Presence::query()
            ->where('calendar_id', $calendarId)
            ->where('user_id', $userId)
            ->where('status', '<>', 99)
            ->delete();

        // Ricreo le presenze per ogni membro contenuto in $ids
        foreach ($ids as $id) {
            $p = new \App\Models\Presence();
            $p->member_id = $id;
            $p->calendar_id = $calendarId;

            // Se per quel membro esisteva un motivation_id, lo riuso, altrimenti lo lascio null
            $p->motivation_id = $motivationMap[$id] ?? null;
            $p->motivation_course_id = $motivationCourseMap[$id] ?? null;
            $p->user_id = $userId;
            $p->status = 0;

            // Salvo eventuale court_id (se presente e maggiore di 0)
            if ($this->save_court_id > 0) {
                $p->court_id = $this->save_court_id;
            }

            // Salvo eventuale instructor_id (se presente e maggiore di 0)
            if ($this->save_instructor_id > 0) {
                $p->instructor_id = $this->save_instructor_id;
            }

            // Salvo eventuali note (se non vuote)
            if ($this->save_notes != '') {
                $p->notes = $this->save_notes;
            }

            $p->save();
        }

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

    public function saveManualCalendar()
    {
        $userId = \Auth::user()->id;
        $calendarId = $this->calendar->id;

        $presences = \App\Models\Presence::where('calendar_id', $calendarId)
                        ->where('user_id', $userId)
                        ->where('status', '<>', 99)
                        ->get();

        foreach ($presences as $presence) {
            // Salvo eventuale court_id (se presente e maggiore di 0)
            if ($this->save_court_id > 0) {
                $presence->court_id = $this->save_court_id;
            }

            // Salvo eventuale instructor_id (se presente e maggiore di 0)
            if ($this->save_instructor_id > 0) {
                $presence->instructor_id = $this->save_instructor_id;
            }

            // Salvo eventuali note (se non vuote)
            if ($this->save_notes != '') {
                $presence->notes = $this->save_notes;
            }

            $presence->save();
        }

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

    public function cancel($ids, $motivation_id)
    {

        $presences = \App\Models\Presence::where('calendar_id', $this->calendar->id)->whereIn('member_id', $ids)->get();
        foreach ($presences as $presence) {
            $presence->motivation_id = $motivation_id;
            $presence->status = 99;
            $presence->save();
        }
        return redirect()->to('/presences?calendarId=' . $this->calendar->id);
    }

    public function addMember($ids)
    {

        $this->added = true;
        //if (!in_array($id, $this->newMembers))
        //    $this->newMembers[] = $id;
        if (!is_array($ids)) {
            $ids = [$ids];
        }

        $this->member_ids = $ids;

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

    public function cancelCalendar()
    {
        $this->calendar->motivation_id = $this->motivation_id;
        $this->calendar->status = 99;
        $this->calendar->save();
        return redirect()->to('/calendar');
    }

    public function createMember()
    {

        if (!$this->added) {
            $this->newMemberFiscalCodeExist = false;
            $this->validate([
                "newMemberMotivationId" => 'required',
            ]);
            /*$this->validate([
                // 'newMemberFiscalCode'=>'required|max:16',
                'newMemberFirstName'=>'required',
                'newMemberLastName'=>'required',
                //'newMemberEmail'=>'required',
            ]);*/

            // Check fiscal code exist
            $exist = false;
            if ($this->newMemberFiscalCode != '') {
                $check = \App\Models\Member::where('fiscal_code', $this->newMemberFiscalCode)->get();
                $exist = $check->count() > 0;
            }
            if (!$exist) {
                $member = \App\Models\Member::create([
                    'first_name' => strtoupper($this->newMemberFirstName),
                    'last_name' => strtoupper($this->newMemberLastName),
                    'email' => strtoupper($this->newMemberEmail),
                    'to_complete' => true,
                    'fiscal_code' => $this->newMemberFiscalCode,
                    'status' => true
                ]);

                //if (!in_array($member->id, $this->newMembers))
                //    $this->newMembers[] = $member->id;

                $p = new \App\Models\Presence();
                $p->member_id = $member->id;
                $p->calendar_id = $this->calendar->id;
                $p->motivation_id = $this->newMemberMotivationId;
                $p->motivation_course_id = $this->motivation_course_id;
                $p->user_id = \Auth::user()->id;
                $p->status = 0;
                $p->court_id = null;
                $p->instructor_id = null;
                $p->notes = null;
                $p->save();

                $this->emit('reload');
                $this->emit('saved');
                /*$this->newMemberFirstName = '';
                $this->newMemberLastName = '';
                $this->newMemberEmail = '';
                $this->newMemberFiscalCode = '';*/
            } else {
                $this->newMemberFiscalCodeExist = true;
            }
        } else {

            if ($this->member_ids != null) {
                $this->validate([
                    "newMemberMotivationId" => 'required',
                ]);

                $validator = Validator::make(
                    [
                        'motivation_course_id' => $this->motivation_course_id,
                    ],
                    [
                        'motivation_course_id' => 'nullable|integer',
                    ]
                );

                foreach ($this->member_ids as $m) {
                    $validator->after(function ($validator) use ($m) {
                        if (!$this->motivation_course_id) {
                            return;
                        }

                        $exists = \App\Models\MemberCourse::where('member_id', $m)->where('course_id', $this->motivation_course_id)->exists();

                        if (!$exists) {
                            $validator->errors()->add(
                                'motivation_course_id',
                                'Il corso selezionato non è associato a questo utente.'
                            );
                        }
                    });

                    $validator->validate();

                    //if ($this->manual)
                    //{
                    //\App\Models\Presence::where('calendar_id', $this->calendar->id)->where('user_id', \Auth::user()->id)->where('status', '<>', 99)->delete();
                    //foreach($ids as $id)
                    //{
                    $p = new \App\Models\Presence();
                    $p->member_id = $m;
                    $p->calendar_id = $this->calendar->id;
                    $p->motivation_id = $this->newMemberMotivationId;
                    $p->motivation_course_id = $this->motivation_course_id;
                    $p->user_id = \Auth::user()->id;
                    $p->status = 0;
                    $p->court_id = null;
                    $p->instructor_id = null;
                    $p->notes = null;
                    $p->save();
                    //}
                    /*}
                    else
                    {
                        if (!in_array($m, $this->newMembers))
                            $this->newMembers[] = $m;
                    }*/
                }
            }

            //$this->member_id = 0;
            $this->member_ids = [];
            $this->added = false;

            $this->emit('reload');
            $this->emit('saved');
        }

        $this->resetCreationFields();
    }

    public function resetCreationFields()
    {
        $this->insertUser = 'new';
        $this->motivation_course_id = null;
        $this->motivation_course_name = null;
        $this->motivation_course_level = null;
        $this->motivation_course_type = null;
        $this->motivation_course_frequency = null;
        $this->newMemberMotivationId = null;
        $this->newMemberFirstName = null;
        $this->newMemberLastName = null;
        $this->newMemberEmail = null;
        $this->newMemberFiscalCode = null;

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

    public function createInstructor()
    {

        $user = \App\Models\User::create([
            'name' => $this->userName,
            'email' => $this->userEmail,
            'password' => '',
            'level' => 2,
            'enabled' => true
        ]);

        $this->instructor_id = $user->id;
        $this->instructors = \App\Models\User::select('*')->where('level', 2)->where('enabled', true)->orderBy('name', 'asc')->get();
        $this->emit('saved');
    }

    public function removeSingle($id)
    {

        \App\Models\Presence::where('calendar_id', $this->calendar->id)->where('member_id', $id)->delete();
        $this->emit('reload');
    }

    public function revert($id)
    {
        $p = \App\Models\Presence::where('calendar_id', $this->calendar->id)->where('member_id', $id)->first();
        $p->motivation_id = null;
        $p->status = 0;
        $p->save();
        $this->emit('reload');
    }
}
