<?php

namespace App\Http\Livewire;

use Livewire\Component;

class PresenceReport extends Component
{

    public $calendar;

    public $records;

    public $date;

    public $member_ids = [];


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

    public $court_filter;
    public $instructor_filter;
    public $motivation_filter;


    public $members = [];

    public $newMembers = [];

    public $ids = [];

    public $course_name;
    public $from;
    public $to;
    public $court_id;
    public $instructor_id;
    public $search;

    public function mount()
    {
        $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->from = "00:00:00";
        $this->to = "23:59:59";

        $this->date = date("Y-m-d");
        setlocale(LC_ALL, 'it_IT');
    }

    public function render()
    {
        setlocale(LC_ALL, 'it_IT');

        $this->records = [];
        $this->courses = [];

        $from = $this->date . " " . $this->from;
        $to = $this->date . " " . $this->to;

        $calendars = \App\Models\Calendar::where('from', '>=', $from)->where('from', '<=', $to)->orderBy('from')->get();

        foreach ($calendars as $calendar) {

            $presences = \App\Models\Presence::where('calendar_id', $calendar->id)->where('status', '<>', 99);
            $presences_annullate = \App\Models\Presence::where('calendar_id', $calendar->id)->where('status', 99);
            
            // filtra per campo court_id
            if (!is_null($this->court_id) && $this->court_id > 0) {
                $presences->where('court_id', $this->court_id);
                $presences_annullate->where('court_id', $this->court_id);
            }

            // filtra per campo istructor_id/user_id
            if (!is_null($this->instructor_id) && $this->instructor_id > 0) {
                $presences->where(function ($query) {
                    $query->where('instructor_id', $this->instructor_id)
                        ->orWhere('user_id', $this->instructor_id);
                });
                $presences_annullate->where(function ($query) {
                    $query->where('instructor_id', $this->instructor_id)
                        ->orWhere('user_id', $this->instructor_id);
                });
            }

            // filtra per campo search (nome/cognome)
            if (!is_null($this->search) && $this->search != "") {
                $search_value = $this->search;
                $presences->whereHas('member', function ($q) use ($search_value) {
                    $q->where(function ($qq) use ($search_value) {
                        $qq->whereRaw("CONCAT(TRIM(first_name), ' ', TRIM(last_name)) LIKE ?", ["%{$search_value}%"])
                        ->orWhereRaw("CONCAT(TRIM(last_name), ' ', TRIM(first_name)) LIKE ?", ["%{$search_value}%"]);
                    });
                });
                $presences_annullate->whereHas('member', function ($q) use ($search_value) {
                    $q->where(function ($qq) use ($search_value) {
                        $qq->whereRaw("CONCAT(TRIM(first_name), ' ', TRIM(last_name)) LIKE ?", ["%{$search_value}%"])
                        ->orWhereRaw("CONCAT(TRIM(last_name), ' ', TRIM(first_name)) LIKE ?", ["%{$search_value}%"]);
                    });
                });
            }

            $presences = $presences->pluck('member_id')->toArray();
            $presences_annullate = $presences_annullate->pluck('member_id')->toArray();

            $days = ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'];
            $dow = date('w', strtotime($calendar->from));
            $d = $days[$dow];

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

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

            $mids = [];

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

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

                $court = '';
                $instructor = '';
                $motivation = '';

                $presence = \App\Models\Presence::where('member_id', $member->member->id)->where('calendar_id', $calendar->id)->first();
                if ($presence) {
                    $court = $presence->court ? $presence->court->name : "";
                    $instructor = [
                        $presence->user ? $presence->user->name : "",
                        $presence->instuctor && $presence->instructor !== $presence->user ? $presence->instuctor->name : "",
                    ];
                    $instructor = implode(", ", array_filter($instructor));
                    $motivation = $presence->motivation ? $presence->motivation->name : "";
                }

                $status = '';
                if (in_array($member->member->id, $presences)) {
                    $status = "<span class='fw-bold' style='color:#0c6197'>Presente</span>";
                } else {
                    if (in_array($member->member->id, $presences_annullate)) {
                        $status = "<span class='fw-bold' style='color:gray'>Annullata</span>";
                    } else {
                        if (date("Ymd") > date("Ymd", strtotime($calendar->from))) {
                            $status = "<span class='fw-bold' style='color:red'>Assente</span>";
                        }
                    }
                }

                if ($calendar->status == 99) {
                    $status = "<span class='fw-bold' style='color:gray'>Annullata</span>";
                }

                $this->records[$calendar->name][$h][] = array(
                    "last_name" => $member->member->last_name,
                    "first_name" => $member->member->first_name,
                    "court" => $court,
                    "instructor" => $instructor,
                    "status" => $status,
                    'motivation' => $motivation
                );

                $mids[] = $member->member->id;
            }

            $presences_recuperi = \App\Models\Presence::where('calendar_id', $calendar->id)->whereNotIn('member_id', $mids);
            if (!is_null($this->court_id) && $this->court_id > 0) {
                $presences_recuperi->where('court_id', $this->court_id);
            }
            if (!is_null($this->instructor_id) && $this->instructor_id > 0) {
                $presences_recuperi->where(function ($query) {
                    $query->where('instructor_id', $this->instructor_id)
                        ->orWhere('user_id', $this->instructor_id);
                });
            }
            if (!is_null($this->search) && $this->search != "") {
                $search_value = $this->search;
                $presences_recuperi->whereHas('member', function ($q) use ($search_value) {
                    $q->where(function ($qq) use ($search_value) {
                        $qq->whereRaw("CONCAT(TRIM(first_name), ' ', TRIM(last_name)) LIKE ?", ["%{$search_value}%"])
                        ->orWhereRaw("CONCAT(TRIM(last_name), ' ', TRIM(first_name)) LIKE ?", ["%{$search_value}%"]);
                    });
                });
            }
            $presences_recuperi = $presences_recuperi->get();
            foreach ($presences_recuperi as $p) {
                $court = $p->court ? $p->court->name : "";
                $instructor = [
                    $p->user ? $p->user->name : "",
                    $p->instuctor && $p->instructor !== $p->user ? $p->instuctor->name : "",
                ];
                $instructor = implode(", ", array_filter($instructor));
                $motivation = $p->motivation ? $p->motivation->name : "";
                $status = "<span class='fw-bold' style='color:gray'>Recupero</span>";
                $this->records[$calendar->name][$h][] = array(
                    "last_name" => $p->member->last_name,
                    "first_name" => $p->member->first_name,
                    "court" => $court,
                    "instructor" => $instructor,
                    "status" => $status,
                    'motivation' => $motivation
                );
            }

            /*
            $calendar_recuperi = \App\Models\Calendar::where('manual', 1)->where('id', $calendar->id)->pluck('id')->toArray();
            $presences_recuperi = \App\Models\Presence::whereIn('calendar_id', $calendar_recuperi)->where('member_id', $this->dataId)->get();
            foreach($presences_recuperi as $p)
            {
                $this->member_presences[] = array('calendar_id' => $p->calendar->id, 'from' => $p->calendar->from, 'to' => $p->calendar->to, 'status' => '<span style="color:#7136f6">Recupero</span>');//\App\Models\Presence::where('member_id', $this->dataId)->get();
                $this->recuperi += 1;
            } 
                */

            //array_push($this->courses, $calendar->course_id);

            // sort records per cognome-nome
            if (isset($this->records[$calendar->name]) && isset($this->records[$calendar->name][$h])) {
                usort($this->records[$calendar->name][$h], function($a, $b) {
                    $last_name_compare = strcmp($a['last_name'], $b['last_name']);
                    $first_name_compare = strcmp($a['first_name'], $b['first_name']);
    
                    return $last_name_compare != 0 ? $last_name_compare : $first_name_compare;
                });
            }
        }

        $this->courses = \App\Models\Calendar::orderBy('name')->groupBy('name')->pluck('name')->toArray();

        /*$this->courses = array_unique($this->courses);
        $this->courses = array_map(function ($course_id) {
            try {
                return \App\Models\Course::findOrFail($course_id);
            } catch (\Throwable $e) {
                return null;
            }
        }, $this->courses);
        $this->courses = array_filter($this->courses);*/

        return view('livewire.presence_report');
    }

    public function prev()
    {
        $this->date = date("Y-m-d", strtotime("-1 day", strtotime($this->date)));
    }

    public function next()
    {
        $this->date = date("Y-m-d", strtotime("+1 day", strtotime($this->date)));
    }

    public function today()
    {
        $this->date = date("Y-m-d");
    }
}
