Luca Parisio 1 місяць тому
батько
коміт
d3d369332b
52 змінених файлів з 7400 додано та 237 видалено
  1. BIN
      .DS_Store
  2. 1 0
      app/Http/Kernel.php
  3. 84 0
      app/Http/Livewire/AbsenceReport.php
  4. 15 8
      app/Http/Livewire/Bank.php
  5. 182 0
      app/Http/Livewire/Calendar.php
  6. 81 2
      app/Http/Livewire/Course.php
  7. 480 0
      app/Http/Livewire/Presence.php
  8. 295 0
      app/Http/Livewire/PresenceReport.php
  9. 396 36
      app/Http/Livewire/Record.php
  10. 9 0
      app/Http/Livewire/RecordIN.php
  11. 7 0
      app/Http/Livewire/RecordOUT.php
  12. 1410 0
      app/Http/Livewire/RecordOld.php
  13. 31 0
      app/Http/Middleware/HstsMiddleware.php
  14. 15 0
      app/Models/Bank.php
  15. 38 0
      app/Models/Calendar.php
  16. 16 0
      app/Models/Court.php
  17. 17 0
      app/Models/Motivation.php
  18. 52 0
      app/Models/Presence.php
  19. 2 0
      app/Models/Record.php
  20. 2 1
      database/migrations/2025_11_14_115900_create_courts_table.php
  21. 3 2
      database/migrations/2025_11_14_120000_create_calendars_table.php
  22. 2 1
      database/migrations/2025_11_14_120100_create_presences_table.php
  23. 34 0
      database/migrations/2025_11_14_120101_add_field_user_id_to_presences_table.php
  24. 35 0
      database/migrations/2025_11_14_120102_create_motivations_table.php
  25. 36 0
      database/migrations/2025_11_14_120103_add_fields_to_calendars_table.php
  26. 33 0
      database/migrations/2025_11_14_120104_add_color_to_courses_table.php
  27. 33 0
      database/migrations/2025_11_14_120105_add_status_to_presences_table.php
  28. 46 0
      database/migrations/2025_11_14_120106_add_more_fields_to_calendars_table.php
  29. 34 0
      database/migrations/2025_11_14_120107_add_motivation_id_to_presences_table.php
  30. 33 0
      database/migrations/2025_11_14_120108_add_type_to_motivations_table.php
  31. 33 0
      database/migrations/2025_11_14_120109_add_manual_to_calendars_table.php
  32. 34 0
      database/migrations/2025_11_14_120110_add_motivation_id_to_calendars_table.php
  33. 39 0
      database/migrations/2025_11_14_120111_add_fields_to_presences_table.php
  34. 33 0
      database/migrations/2025_11_17_100244_add_visibility_to_banks_table.php
  35. 37 0
      database/migrations/2025_11_17_102344_add_more_fields_to_records_rows_table.php
  36. 8 0
      public/assets/js/fullcalendar.js
  37. 5 0
      public/assets/js/fullcalendar_locales.js
  38. 10 3
      resources/views/layouts/app.blade.php
  39. 58 0
      resources/views/livewire/absence_report.blade.php
  40. 12 0
      resources/views/livewire/bank.blade.php
  41. 342 0
      resources/views/livewire/calendar.blade.php
  42. 19 0
      resources/views/livewire/course.blade.php
  43. 243 0
      resources/views/livewire/court.blade.php
  44. 212 0
      resources/views/livewire/motivation.blade.php
  45. 715 0
      resources/views/livewire/presence.blade.php
  46. 169 0
      resources/views/livewire/presence_report.blade.php
  47. 726 170
      resources/views/livewire/records.blade.php
  48. 19 1
      resources/views/livewire/records_in.blade.php
  49. 1229 0
      resources/views/livewire/records_old.blade.php
  50. 29 12
      resources/views/livewire/records_out.blade.php
  51. 1 1
      resources/views/livewire/settings.blade.php
  52. 5 0
      routes/web.php

+ 1 - 0
app/Http/Kernel.php

@@ -21,6 +21,7 @@ class Kernel extends HttpKernel
         \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
         \App\Http\Middleware\TrimStrings::class,
         \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
+        \App\Http\Middleware\HstsMiddleware::class,
     ];
 
     /**

+ 84 - 0
app/Http/Livewire/AbsenceReport.php

@@ -0,0 +1,84 @@
+<?php
+
+namespace App\Http\Livewire;
+
+use Livewire\Component;
+
+class AbsenceReport extends Component
+{
+
+    public $records;
+
+    public $year;
+
+    public function mount()
+    {
+        setlocale(LC_ALL, 'it_IT');
+    }
+
+    public function render()
+    {
+        setlocale(LC_ALL, 'it_IT');
+
+        $this->records = [];
+
+        // $to = date("Y-m-d 23:59:59");
+        // $calendars = \App\Models\Calendar::where('from', '<=', $to)->orderBy('from')->get();
+
+        $month = date("n");
+        $this->year = ($month >= 9) ? date("Y") : date("Y") - 1;
+
+        $start = date("Y-m-d H:i:s", mktime(0, 0, 0, 9, 1, $this->year));
+        $end   = date("Y-m-d 23:59:59");
+
+        $calendars = \App\Models\Calendar::whereBetween('from', [$start, $end])->orderBy('from')->get();
+
+        foreach ($calendars as $calendar) {
+
+            $presences = \App\Models\Presence::where('calendar_id', $calendar->id)->where('status', '<>', 99);
+            $presences = $presences->pluck('member_id')->toArray();
+            $presences_annullate = \App\Models\Presence::where('calendar_id', $calendar->id)->where('status', 99)->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);
+            $courses = $courses->pluck('id')->toArray();
+
+            $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 . '"%')
+                ->whereNot('months', 'like', '%"m":' . $months . ',"status":2%')
+                ->whereDate('date_from', '<=', $calendar->from)                                 
+                ->whereDate('date_to', '>=', $calendar->from)      
+                ->whereIn('course_id', $courses)
+                ->orderBy('member_id')
+                ->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) {
+
+                $presence = \App\Models\Presence::where('member_id', $member->member->id)->where('calendar_id', $calendar->id)->first();
+
+                if (!in_array($member->member->id, $presences)) {
+                    if (!in_array($member->member->id, $presences_annullate)) {
+                        if (array_key_exists($member->member->id, $this->records)) {
+                            $this->records[$member->member->id]['total'] += 1;
+                            $this->records[$member->member->id]['date'] .= " - " . date("d/m", strtotime($calendar->from));
+                        } else
+                            $this->records[$member->member->id] = array("last_name" => $member->member->last_name, "first_name" => $member->member->first_name, "course" => $calendar->name, "total" => 1, "date" => date("d/m", strtotime($calendar->from)));
+                    }
+                }
+            }
+        }
+
+        array_multisort(array_column($this->records, 'total'), SORT_DESC, $this->records);
+
+        return view('livewire.absence_report');
+    }
+}

+ 15 - 8
app/Http/Livewire/Bank.php

@@ -3,11 +3,11 @@
 namespace App\Http\Livewire;
 
 use Livewire\Component;
-use Illuminate\Support\Facades\Auth;
 use App\Http\Middleware\TenantMiddleware;
+
 class Bank extends Component
 {
-    public $records, $name, $enabled, $dataId, $update = false, $add = false;
+    public $records, $name, $visibility, $enabled, $dataId, $update = false, $add = false;
 
     protected $rules = [
         'name' => 'required'
@@ -19,13 +19,15 @@ class Bank extends Component
 
     public $sortField ='name';
     public $sortAsc = true;
+
     public function boot()
     {
         app(TenantMiddleware::class)->setupTenantConnection();
     }
+
     public function mount(){
 
-        if(Auth::user()->level != env('LEVEL_ADMIN', 0))
+        if(\Auth::user()->level != env('LEVEL_ADMIN', 0))
             return redirect()->to('/dashboard');
 
     }
@@ -44,6 +46,7 @@ class Bank extends Component
 
     public function resetFields(){
         $this->name = '';
+        $this->visibility = 'IN';
         $this->enabled = true;
         $this->emit('load-data-table');
     }
@@ -51,7 +54,7 @@ class Bank extends Component
     public function render()
     {
         //$this->records = \App\Models\Bank::select('id', 'name', 'enabled')->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')->get();
-        $this->records = \App\Models\Bank::select('id', 'name', 'enabled')->get();
+        $this->records = \App\Models\Bank::select('id', 'name', 'visibility', 'enabled')->get();
         return view('livewire.bank');
     }
 
@@ -68,9 +71,10 @@ class Bank extends Component
         try {
             \App\Models\Bank::create([
                 'name' => $this->name,
+                'visibility' => $this->visibility,
                 'enabled' => $this->enabled
             ]);
-            session()->flash('success','Città creata');
+            session()->flash('success','Banca creata');
             $this->resetFields();
             $this->add = false;
         } catch (\Exception $ex) {
@@ -79,12 +83,14 @@ class Bank extends Component
     }
 
     public function edit($id){
+        $this->resetFields();
         try {
             $bank = \App\Models\Bank::findOrFail($id);
             if( !$bank) {
-                session()->flash('error','Città non trovata');
+                session()->flash('error','Banca non trovata');
             } else {
                 $this->name = $bank->name;
+                $this->visibility = $bank->visibility;
                 $this->enabled = $bank->enabled;
                 $this->dataId = $bank->id;
                 $this->update = true;
@@ -101,9 +107,10 @@ class Bank extends Component
         try {
             \App\Models\Bank::whereId($this->dataId)->update([
                 'name' => $this->name,
+                'visibility' => $this->visibility,
                 'enabled' => $this->enabled
             ]);
-            session()->flash('success','Città aggiornata');
+            session()->flash('success','Banca aggiornata');
             $this->resetFields();
             $this->update = false;
         } catch (\Exception $ex) {
@@ -125,7 +132,7 @@ class Bank extends Component
             session()->flash('success',"Città eliminata");
             return redirect(request()->header('Referer'));
         }catch(\Exception $e){
-            session()->flash('error','Errore (' . $e->getMessage() . ')');
+            session()->flash('error','Errore (' . $ex->getMessage() . ')');
         }
     }
 }

+ 182 - 0
app/Http/Livewire/Calendar.php

@@ -0,0 +1,182 @@
+<?php
+
+namespace App\Http\Livewire;
+
+use Livewire\Component;
+
+class Calendar extends Component
+{
+    public $records;
+
+    public $names = [];
+    public $course_types = [];
+    public $course_durations = [];
+    public $course_frequencies = [];
+    public $course_levels = [];
+
+    public $courts = [];
+    public $instructors = [];
+    public $motivations = [];
+
+    public $name_filter = null;
+
+    public $name = null;
+    public $from = null;
+    public $to = null;
+    
+    public $court_id = null;
+    public $instructor_id = null;
+    public $note = null;
+    
+    public $course_type_id = null;
+    public $course_duration_id = null;
+    public $course_frequency_id = null;
+    public $course_level_id = null;
+
+    public $motivation_id = null;
+
+    public $festivities = [];
+    public $css_festivities = '';
+
+    public $lastDate = null;
+
+    public function mount()
+    {
+        $this->names = \App\Models\Calendar::orderBy('name')->groupBy('name')->pluck('name')->toArray();
+        $this->course_types = \App\Models\CourseType::select('*')->where('enabled', true)->get();
+        $this->course_durations = \App\Models\CourseDuration::select('*')->where('enabled', true)->get();
+        $this->course_levels = \App\Models\CourseLevel::select('*')->where('enabled', true)->get();
+        $this->course_frequencies = \App\Models\CourseFrequency::select('*')->where('enabled', true)->get();
+        $this->courts = \App\Models\Court::select('*')->where('enabled', true)->get();
+        $this->instructors = \App\Models\User::select('*')->where('level', 2)->where('enabled', true)->get();
+        $this->motivations = \App\Models\Motivation::select('*')->where('enabled', true)->where('type', 'del')->get();
+
+        if (isset($_GET["name_filter"]))
+            $this->name_filter = $_GET["name_filter"];
+
+    }
+
+    public function render()
+    {
+        $reload = false;
+        $this->records = [];
+        if ($this->name_filter != null && $this->name_filter != "")
+        {
+            $calendars = \App\Models\Calendar::where('name', $this->name_filter)->get();
+            $reload = true;
+        }
+        else
+            $calendars = \App\Models\Calendar::get();
+        foreach($calendars as $c)
+        {
+            $s = $c->motivation ? $c->motivation->name : '';
+            $data = array('id' => $c->id, 'title' => ($c->course ? $c->course->name : $c->name) . ($c->status == 99 ? ' (annullata - ' . $s . ')' : ''), 'start' => $c->from, 'end' => $c->to);
+            if ($c->course && $c->course->color != '')
+                $data['color'] = $c->course->color;
+            if ($c->status == 99)
+                $data['color'] = "#808080";
+            $this->records[] = $data;
+        }
+
+        for ($anno = 2025; $anno <= 2036; $anno++) {
+
+            // $background_color = "transparent";
+            // $color = "black";
+            $this->records[] = array('id' => 0, 'title' => 'Capodanno', 'allDay' => true, 'start' => "$anno-01-01 00:00:00", 'end' => "$anno-01-01 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Epifania', 'allDay' => true, 'start' => "$anno-01-06 00:00:00", 'end' => "$anno-01-06 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Festa della Liberazione', 'allDay' => true, 'start' => "$anno-04-25 00:00:00", 'end' => "$anno-04-25 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Festa del Lavoro', 'allDay' => true, 'start' => "$anno-05-01 00:00:00", 'end' => "$anno-05-01 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Festa della Repubblica', 'allDay' => true, 'start' => "$anno-06-02 00:00:00", 'end' => "$anno-06-02 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Ferragosto', 'allDay' => true, 'start' => "$anno-08-15 00:00:00", 'end' => "$anno-08-15 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Ognissanti', 'allDay' => true, 'start' => "$anno-11-01 00:00:00", 'end' => "$anno-11-01 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Immacolata Concezione', 'allDay' => true, 'start' => "$anno-12-08 00:00:00", 'end' => "$anno-12-08 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Natale', 'allDay' => true, 'start' => "$anno-12-25 00:00:00", 'end' => "$anno-12-25 23:59:59", 'classNames' => ["festivity"]);
+            $this->records[] = array('id' => 0, 'title' => 'Santo Stefano', 'allDay' => true, 'start' => "$anno-12-26 00:00:00", 'end' => "$anno-12-26 23:59:59", 'classNames' => ["festivity"]);
+
+            $pasqua = date("Y-m-d", easter_date($anno));
+            $this->records[] = array('id' => 0, 'title' => 'Pasqua', 'allDay' => true, 'start' => "$pasqua 00:00:00", 'end' => "$pasqua 23:59:59", 'classNames' => ["festivity"]);
+            $pasquetta = date("Y-m-d", strtotime("$pasqua +1 day"));
+            $this->records[] = array('id' => 0, 'title' => 'Pasquetta', 'allDay' => true, 'start' => "$pasquetta 00:00:00", 'end' => "$pasquetta 23:59:59", 'classNames' => ["festivity"]);
+
+            $this->festivities[] = "$anno-01-01";
+            $this->festivities[] = "$anno-01-06";
+            $this->festivities[] = "$anno-04-25";
+            $this->festivities[] = "$anno-05-01";
+            $this->festivities[] = "$anno-06-02";
+            $this->festivities[] = "$anno-08-15";
+            $this->festivities[] = "$anno-11-01";
+            $this->festivities[] = "$anno-12-08";
+            $this->festivities[] = "$anno-12-25";
+            $this->festivities[] = "$anno-12-26";
+            $this->festivities[] = "$pasqua";
+            $this->festivities[] = "$pasquetta";
+        }
+
+        $this->festivities = array_map(function($date) {
+            return "[data-date='$date']";
+        }, $this->festivities);
+        $this->css_festivities = implode(", ", $this->festivities);
+        
+        $this->lastDate = null;
+        if (isset($_GET['last_date'])) {
+            try {
+                $this->lastDate = \Illuminate\Support\Facades\Date::createFromFormat('Y-m-d',  $_GET['last_date']);
+            } catch (\Throwable $e) {
+                $this->lastDate = null;
+            }
+
+            if (!$this->lastDate) {
+                $this->lastDate = null;
+            } else {
+                $this->lastDate = $this->lastDate->format("Y-m-d");
+            }
+        }
+
+        if ($reload)
+            $this->emit('reload-calendar', ["'" . json_encode($this->records) . "'"]);
+
+        return view('livewire.calendar');
+    }
+
+    public function createCalendar()
+    {
+
+        $calendar = new \App\Models\Calendar();
+        $calendar->course_id = null;
+        $calendar->court_id = $this->court_id != '' ? $this->court_id : null;
+        $calendar->name = $this->name;
+        $calendar->course_type_id = $this->course_type_id != '' ? $this->course_type_id : null;
+        $calendar->course_duration_id = $this->course_duration_id != '' ? $this->course_duration_id : null;
+        $calendar->course_frequency_id = $this->course_frequency_id != '' ? $this->course_frequency_id : null;
+        $calendar->course_level_id = $this->course_level_id != '' ? $this->course_level_id : null;
+        $calendar->instructor_id = $this->instructor_id != '' ? $this->instructor_id : null;
+        $calendar->from = $this->from;
+        $calendar->to = $this->to;
+        $calendar->note = $this->note;
+        $calendar->status = 0;
+        $calendar->manual = 1;
+        $calendar->save();
+
+        return redirect()->to('/presences?calendarId=' . $calendar->id);
+
+    }
+
+    public function cancelCalendar($id, $motivation_id)
+    {
+        $calendar = \App\Models\Calendar::findOrFail($id);
+        $calendar->motivation_id = $motivation_id;
+        $calendar->status = 99;
+        $calendar->save();
+        return redirect()->to('/calendar');
+    }
+
+    public function revertCalendarDeletion($id)
+    {
+        $calendar = \App\Models\Calendar::findOrFail($id);
+        $calendar->motivation_id = null;
+        $calendar->status = 0;
+        $calendar->save();
+        return redirect()->to('/calendar');
+    }
+
+}

+ 81 - 2
app/Http/Livewire/Course.php

@@ -217,8 +217,8 @@ class Course extends Component
                 $course->date_from = $this->date_from;
                 $course->date_to = $this->date_to;
                 $course->category_id = $this->category_id;
-                //$course->causal_id = $this->causal_id;
-                //$course->sub_causal_id = $this->sub_causal_id;
+                $course->causal_id = $this->causal_id;
+                $course->sub_causal_id = $this->sub_causal_id;
                 $course->max_members = $this->max_members;
                 $course->instructor_id = $this->instructor_id;
                 $course->year = $this->year;
@@ -241,9 +241,87 @@ class Course extends Component
 
                 $mFrom = getMonthName(date("n", strtotime($this->date_from)));
                 $mTo = getMonthName(date("n", strtotime($this->date_to)));
+
+                $course_name = $course->name;
+
+                // creo il calendario
+                $from = date("Y-m-d", strtotime($this->date_from));
+                $to = date("Y-m-d", strtotime($this->date_to));
+
+                $endDate = strtotime($to);
+
+                foreach($this->when as $d)
+                {
+
+                    foreach($d["day"] as $dd)
+                    {
+
+                        $day = '';
+                        switch ($dd) {
+                            case 'lun':
+                                $day = $days[0];
+                                break;
+                            case 'mar':
+                                $day = $days[1];
+                                break;
+                            case 'mer':
+                                $day = $days[2];
+                                break;
+                            case 'gio':
+                                $day = $days[3];
+                                break;
+                            case 'ven':
+                                $day = $days[4];
+                                break;
+                            case 'sab':
+                                $day = $days[5];
+                                break;
+                            case 'dom':
+                                $day = $days[6];
+                                break;
+                            default:
+                                $day = '';
+                                break;
+                        }
+                        
+                        if ($day != '')
+                        {
+                            for($i = strtotime($day, strtotime($from)); $i <= $endDate; $i = strtotime('+1 week', $i))
+                            {
+
+                                // Controllo che non esiste un corso così
+                                $exist = \App\Models\Calendar::where('from', date('Y-m-d ' . $d["from"] . ":00", $i))->where('to', date('Y-m-d ' . $d["to"] . ":00", $i))->where('name', $course_name)->first();
+
+                                if (!$exist && !in_array(date('Y-m-d', $i), $this->festivita))
+                                {
+
+                                    // Creo il calendario del corso
+                                    $calendar = new \App\Models\Calendar();
+                                    $calendar->course_id = $this->course->id;
+                                    $calendar->court_id = null;
+                                    $calendar->name = $course_name;
+                                    $calendar->course_type_id = null;
+                                    $calendar->course_duration_id = null;
+                                    $calendar->course_frequency_id = null;
+                                    $calendar->course_level_id = null;
+                                    $calendar->instructor_id = null;
+                                    $calendar->from = date('Y-m-d ' . $d["from"] . ":00", $i);
+                                    $calendar->to = date('Y-m-d ' . $d["to"] . ":00", $i);
+                                    $calendar->note = '';
+                                    $calendar->status = 0;
+                                    $calendar->save();
+
+                                }
+                                
+                            }
+                        }
+                    }
+                }
+
                 // Creo le causali di pagamento
                 //$causal = "PAGAMENTO CORSO [nome corso]-LIVELLO-FREQUENZA-ANNO-[tipo abbonamento]-[mese inizio]/[mese fine]
 
+                /*
                 $causal = "PAGAMENTO CORSO " . $this->name . " - " . $lev . " - " . $freq . " - " . $this->year . " - " . $mFrom . "/" . $mTo;
                 $cp = \App\Models\Causal::where('name', $causal)->first();
                 if (!$cp)
@@ -281,6 +359,7 @@ class Course extends Component
                     $ci->save();
                 }
                 $course->sub_causal_id = $ci->id;
+                */
 
                 $course->save();
 

+ 480 - 0
app/Http/Livewire/Presence.php

@@ -0,0 +1,480 @@
+<?php
+
+namespace App\Http\Livewire;
+
+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 $userName, $userEmail;
+
+    public $added = false;
+
+    public $filter = '';
+
+    public $courts = [];
+    public $instructors = [];
+    public $motivations = [];
+    public $motivations_add = [];
+
+    public $members = [];
+
+    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'])->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 = '';
+    }
+
+    public function updatedNewMemberMotivationId()
+    {
+        $this->emit('reload');
+    }
+
+    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));
+
+            // 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', ?), '$')", [$d, $h])
+                        ->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 . "%'");
+                })->orderBy('last_name')->orderBy('first_name')->get();
+            } else
+                $members = \App\Models\Member::whereIn('id', $members_courses)->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 . "%'");
+            })->get();
+        } else
+            $members = \App\Models\Member::whereIn('id', $members_presences)->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;
+        $lastEditData = \App\Models\Presence::query()
+            ->select('member_id', 'motivation_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')   // -> [member_id => (obj con motivation_id)]
+            ->map(fn($row) => $row->motivation_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 = $lastEditData[$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 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;
+
+        $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->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',
+                ]);
+                foreach ($this->member_ids as $m) {
+                    //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->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');
+        }
+    }
+
+    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');
+    }
+}

+ 295 - 0
app/Http/Livewire/PresenceReport.php

@@ -0,0 +1,295 @@
+<?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 $court_name = '';
+    public $instructor_name = '';
+
+    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();
+
+        if (!is_null($this->court_id) && $this->court_id > 0)
+            $this->court_name = \App\Models\Court::findOrFail($this->court_id)->name;
+        else
+            $this->court_name = '';
+
+        if (!is_null($this->instructor_id) && $this->instructor_id > 0)
+            $this->instructor_name = \App\Models\User::findOrFail($this->instructor_id)->name;
+        else
+            $this->instructor_name = '';
+
+        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>";
+                }
+
+                $show = true;
+                if ($this->court_name != '')
+                    $show = $this->court_name == $court;
+                if ($show && $this->instructor_name != '')
+                    $show = $this->instructor_name == $instructor;
+
+                if ($show)
+                {
+                    $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");
+    }
+}

+ 396 - 36
app/Http/Livewire/Record.php

@@ -41,7 +41,11 @@ class Record extends Component
     public $exportEmailAddress = '';
     public $exportEmailSubject = 'Prima Nota - Export';
     private $causalAmounts = [];
-
+    public $selectedMonth;
+    public $showMonthPicker = false;
+    public $selectedDay;
+    public $showDayPicker = false;
+    public $selectedYear;
     protected $rules = [
         'exportEmailAddress' => 'required_if:sendViaEmail,true|email',
         'exportEmailSubject' => 'required_if:sendViaEmail,true|string|max:255',
@@ -53,16 +57,17 @@ class Record extends Component
         'exportEmailSubject.required_if' => 'L\'oggetto dell\'email è obbligatorio.',
         'exportEmailSubject.max' => 'L\'oggetto dell\'email non può superare i 255 caratteri.',
     ];
-    public function boot()
-    {
-        app(TenantMiddleware::class)->setupTenantConnection();
 
-    }
     public function hydrate()
     {
         $this->emit('load-select');
     }
 
+    public function boot()
+    {
+        app(TenantMiddleware::class)->setupTenantConnection();
+    }
+
     public function mount()
     {
         $this->fromDate = date("Y-m-d");
@@ -76,14 +81,16 @@ class Record extends Component
 
         $this->exportEmailSubject = 'Prima Nota - Export del ' . date('d/m/Y');
 
-
         $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
 
         $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
 
         $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
-    }
 
+        $this->selectedMonth = date('Y-m');
+        $this->selectedDay = date('Y-m-d');
+        $this->selectedYear = date('Y');
+    }
     private function generateExportDataAndTotals($fromDate, $toDate)
     {
         Log::info('generateExportDataAndTotals: Start (combined method)', [
@@ -114,6 +121,10 @@ class Record extends Component
                 'records_rows.updated_at as row_updated_at'
             )
             ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            //->where('records.deleted', false)
+            ->where(function ($query) {
+                $query->where('records.deleted', false)->orWhereNull('records.deleted');
+            })
             ->whereBetween('date', [$fromDate, $toDate])
             ->where(function ($query) {
                 $query->where('type', 'OUT')
@@ -202,9 +213,9 @@ class Record extends Component
                     }
 
                     // CALCULATE TOTALS HERE (in the same loop)
-                    if (!$data->deleted) {
+                    /*if (!$data->deleted) {
                         $exportTotals[$data->payment_method->name][$data->type] += $amount;
-                    }
+                    }*/
 
                     $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
                     $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
@@ -271,6 +282,9 @@ class Record extends Component
         Log::info('generateExportDataAndTotals: Building final export records');
         $finalStart = microtime(true);
 
+        $tot = 0;
+        $count = 0;
+
         foreach ($groupedData as $groupKey => $group) {
             $causalsInGroup = array_keys($causalsCount[$groupKey]);
 
@@ -289,6 +303,10 @@ class Record extends Component
             }
 
             $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
+
+            if (!$group['deleted'])
+                $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
+
         }
 
         $finalTime = microtime(true) - $finalStart;
@@ -330,6 +348,10 @@ class Record extends Component
                 'records_rows.vat_id',
             )
             ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            //->where('records.deleted', false)
+            ->where(function ($query) {
+                $query->where('records.deleted', false)->orWhereNull('records.deleted');
+            })
             ->whereBetween('date', [$fromDate, $toDate])
             ->where(function ($query) {
                 $query->where('type', 'OUT')
@@ -395,6 +417,11 @@ class Record extends Component
     public function resetFilters()
     {
         $this->selectedPeriod = 'OGGI';
+        $this->selectedMonth = date('Y-m');
+        $this->selectedDay = date('Y-m-d');
+        $this->selectedYear = date('Y');
+        $this->showMonthPicker = false;
+        $this->showDayPicker = false;
         $this->filterCausals = [];
         $this->filterMember = null;
 
@@ -407,6 +434,7 @@ class Record extends Component
         $this->emit('filters-reset');
     }
 
+
     public function applyFilters()
     {
         $this->isFiltering = true;
@@ -450,6 +478,22 @@ class Record extends Component
                 $this->toDate = $lastMonth->endOfMonth()->format('Y-m-d');
                 break;
 
+            case 'MESE_PERSONALIZZATO':
+                if (!empty($this->selectedMonth)) {
+                    $firstDay = date('Y-m-01', strtotime($this->selectedMonth . '-01'));
+                    $lastDay = date('Y-m-t', strtotime($this->selectedMonth . '-01'));
+                    $this->fromDate = $firstDay;
+                    $this->toDate = $lastDay;
+                }
+                break;
+
+            case 'GIORNO_PERSONALIZZATO':
+                if (!empty($this->selectedDay)) {
+                    $this->fromDate = $this->selectedDay;
+                    $this->toDate = $this->selectedDay;
+                }
+                break;
+
             case 'ULTIMO TRIMESTRE':
                 $this->fromDate = $today->copy()->subMonths(3)->format('Y-m-d');
                 $this->toDate = $today->format('Y-m-d');
@@ -461,7 +505,6 @@ class Record extends Component
                 break;
         }
     }
-
     public function getCausals($records, $indentation)
     {
         foreach ($records as $record) {
@@ -518,19 +561,14 @@ class Record extends Component
         return $ret;
     }
 
-
-
-    public function render()
+    public function loadData($from, $to)
     {
-        $month = 0;
-        $year = 0;
-
-        $this->records = array();
-        $this->totals = array();
-        $this->causalAmounts = array();
 
         $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
 
+        $f = $from != '' ? $from : $this->appliedFromDate;
+        $t = $to != '' ? $to : $this->appliedToDate;
+
         $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
             ->select(
                 'records.*',
@@ -541,18 +579,28 @@ class Record extends Component
                 'records_rows.note',
                 'records_rows.when',
                 'records_rows.vat_id',
+                //'causals.name as causal_name',
+                'd.name as destination',
+                'o.name as origin',
             )
             ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
-            ->whereBetween('date', [$this->appliedFromDate, $this->appliedToDate])
+            ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
+            ->leftJoin('banks as d', 'records.destination_id', '=', 'd.id')
+            ->leftJoin('banks as o', 'records.origin_id', '=', 'o.id')
+            //->where('records.deleted', false)
+            /*->where(function ($query) {
+                $query->where('records.deleted', false)->orWhereNull('records.deleted');
+            })*/
+            ->whereBetween('date', [$f . " 00:00:00", $t . " 23:59:59"])
             ->where(function ($query) {
-                $query->where('type', 'OUT')
+                $query->where('records.type', 'OUT')
                     ->orWhere(function ($query) {
                         $query->where('records.corrispettivo_fiscale', true)
                             ->orWhere('records.commercial', false);
                     });
             })
             ->where(function ($query) use ($exclude_from_records) {
-                $query->where('type', 'OUT')
+                $query->where('records.type', 'OUT')
                     ->orWhere(function ($subquery) use ($exclude_from_records) {
                         $subquery->whereNotIn('member_id', $exclude_from_records);
                     });
@@ -581,10 +629,28 @@ class Record extends Component
             ->orderBy('records_rows.id', 'ASC')
             ->get();
 
-        $groupedData = [];
-        $causalsCount = [];
-        $causalsAmounts = [];
-        $nominativi = [];
+        foreach($datas as $data)
+        {
+            $causal = \App\Models\Causal::findOrFail($data->causal_id);
+            $data->causal_name = $causal->getTree();
+        }
+        
+        return $datas;
+
+    }
+
+    public function render()
+    {
+        $month = 0;
+        $year = 0;
+
+        $this->records = array();
+        $this->totals = array();
+        $this->causalAmounts = array();
+
+        $this->records = $this->loadData('', '');
+
+        /*
 
         foreach ($datas as $idx => $data) {
 
@@ -595,7 +661,8 @@ class Record extends Component
 
                 if (!$data->deleted) {
                     $amount = $data->amount;
-                    $amount += getVatValue($amount, $data->vat_id);
+                    if ($data->vat_id > 0)
+                        $amount += getVatValue($amount, $data->vat_id);
                 } else {
                     $amount = $data->amount;
                 }
@@ -608,6 +675,8 @@ class Record extends Component
                     if ($data->member) {
                         $nominativo = $data->member->last_name . " " . $data->member->first_name;
                     }
+                    if ($data->payment_method_id == 7)
+                        $values[] = array('id' => $data->record_id, 'amount' => $amount);
                 } else {
                     if ($data->supplier) {
                         $nominativo = $data->supplier->name;
@@ -651,6 +720,8 @@ class Record extends Component
             }
         }
 
+        Log::info('values', [$values]);
+
         foreach ($groupedData as $groupKey => $group) {
             $causalsInGroup = array_keys($causalsCount[$groupKey]);
 
@@ -683,6 +754,8 @@ class Record extends Component
                 $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
         }
 
+        */
+
         return view('livewire.records');
     }
 
@@ -787,6 +860,8 @@ class Record extends Component
             $exportRecords = $result['records'];
             $exportTotals = $result['totals'];
 
+            Log::info('TOTALS', [$exportTotals]);
+
             $dataGenTime = microtime(true) - $startTime;
             Log::info('Export: COMBINED data generation completed (NO SEPARATE TOTALS CALL)', [
                 'records_count' => count($exportRecords),
@@ -799,7 +874,7 @@ class Record extends Component
 
             if ($this->sendViaEmail) {
                 Log::info('Export: Dispatching to background job');
-                $this->dispatchExportJob($exportRecords, $exportTotals);
+                //$this->dispatchExportJob($exportRecords, $exportTotals);
                 Log::info('Export: Job dispatched successfully');
             } else {
                 Log::info('Export: Starting direct download export');
@@ -848,6 +923,85 @@ class Record extends Component
             Log::info('=== EXPORT END ===');
         }
     }
+
+    public function exportData()
+    {
+
+        $this->isExporting = true;
+        $this->emit('$refresh');
+        usleep(100000);
+
+        if ($this->sendViaEmail) {
+            Log::info('Export: Validating email fields');
+            $this->validate([
+                'exportEmailAddress' => 'required|email',
+                'exportEmailSubject' => 'required|string|max:255',
+            ]);
+            Log::info('Export: Email validation passed');
+        }
+
+        $this->isExporting = true;
+
+        try {
+            Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
+            $startTime = microtime(true);
+
+            $records = $this->loadData($this->exportFromDate, $this->exportToDate);            
+            
+            $dataGenTime = microtime(true) - $startTime;
+            
+
+
+            if ($this->sendViaEmail) {
+                Log::info('Export: Dispatching to background job');
+
+                // Invio mail
+
+                $this->dispatchExportJob($records);
+                Log::info('Export: Job dispatched successfully');
+            } else {
+                Log::info('Export: Starting direct download export');
+                $exportStartTime = microtime(true);
+
+                // Creo excel e scarico
+                $result = $this->exportExcel($records);
+
+                $exportTime = microtime(true) - $exportStartTime;
+
+                return $result;
+            }
+        } catch (\Illuminate\Validation\ValidationException $e) {
+            Log::error('Export: Validation error', [
+                'error' => $e->getMessage(),
+                'errors' => $e->errors()
+            ]);
+            $this->isExporting = false;
+            throw $e;
+        } catch (\Exception $e) {
+            Log::error('Export: General error', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'memory_usage' => memory_get_usage(true),
+                'memory_peak' => memory_get_peak_usage(true),
+                'execution_time' => microtime(true) - ($startTime ?? 0)
+            ]);
+
+            $this->isExporting = false;
+
+            if ($this->sendViaEmail) {
+                $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
+            } else {
+                session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
+            }
+        } finally {
+            Log::info('Export: Cleanup phase');
+            $this->isExporting = false;
+            $this->emit('export-complete');
+            $this->emit('hide-export-modal');
+            Log::info('=== EXPORT END ===');
+        }
+    }
+
     private function getEstimatedRecordCount($fromDate, $toDate)
     {
         $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
@@ -949,7 +1103,8 @@ class Record extends Component
     /**
      * Dispatch export job to queue
      */
-    private function dispatchExportJob($exportRecords, $exportTotals)
+    //private function dispatchExportJob($exportRecords, $exportTotals)
+    private function dispatchExportJob($records)
     {
         try {
             // Prepare filter descriptions for the job
@@ -968,8 +1123,9 @@ class Record extends Component
 
             // Dispatch job to background queue
             ExportPrimaNota::dispatch(
-                $exportRecords,
-                $exportTotals,
+                /*$exportRecords,
+                $exportTotals,*/
+                $records,
                 $this->exportEmailAddress,
                 $this->exportEmailSubject,
                 [
@@ -988,7 +1144,7 @@ class Record extends Component
                 'user_id' => auth()->id(),
                 'email' => $this->exportEmailAddress,
                 'date_range' => [$this->exportFromDate, $this->exportToDate],
-                'total_records' => count($exportRecords)
+                'total_records' => count($this->records)
             ]);
         } catch (\Exception $e) {
             Log::error('Failed to dispatch export job', [
@@ -1038,8 +1194,6 @@ class Record extends Component
         $activeWorksheet->setCellValue('C1', "Causale");
         $activeWorksheet->setCellValue('D1', "Nominativo");
         $activeWorksheet->setCellValue('E1', "Stato");
-        $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
-        $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
 
         $activeWorksheet->getStyle('A1:Q1')->getFill()
             ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
@@ -1047,6 +1201,8 @@ class Record extends Component
 
         $activeWorksheet->getStyle('A1:Q1')->getFont()->getColor()->setARGB('FFFFFFFF');
 
+
+        Log::info('exportWithData: Setting payment method headers');
         $idx = 0;
         foreach ($this->payments as $p) {
             if ($idx >= count($letters)) {
@@ -1388,7 +1544,6 @@ class Record extends Component
 
     private function getPreferredEmail()
     {
-        // Try multiple sources in order of preference
         $email = auth()->user()->email ?? null;
 
         if (empty($email)) {
@@ -1401,10 +1556,215 @@ class Record extends Component
         }
 
         if (empty($email)) {
-            // Get from user input or company default
             $email = config('mail.default_recipient', '');
         }
 
         return $email;
     }
+
+        public function updatedSelectedDay($value)
+    {
+        if (!empty($value)) {
+            $this->selectedPeriod = 'GIORNO_PERSONALIZZATO';
+            $this->fromDate = $value;
+            $this->toDate = $value;
+            $this->applyFilters();
+        }
+    }
+
+    public function selectDay($day)
+    {
+        $this->selectedDay = $day;
+        $this->showDayPicker = false;
+        $this->updatedSelectedDay($day);
+    }
+
+    public function toggleDayPicker()
+    {
+        $this->showDayPicker = !$this->showDayPicker;
+    }
+
+    public function selectToday()
+    {
+        $today = date('Y-m-d');
+        $this->selectDay($today);
+    }
+
+    public function selectYesterday()
+    {
+        $yesterday = date('Y-m-d', strtotime('-1 day'));
+        $this->selectDay($yesterday);
+    }
+
+    // Updated month methods to work with both custom month and day
+    public function updatedSelectedMonth($value)
+    {
+        if (!empty($value)) {
+            $this->selectedPeriod = 'MESE_PERSONALIZZATO';
+            $firstDay = date('Y-m-01', strtotime($value . '-01'));
+            $lastDay = date('Y-m-t', strtotime($value . '-01'));
+            $this->fromDate = $firstDay;
+            $this->toDate = $lastDay;
+            $this->applyFilters();
+        }
+    }
+
+    public function selectMonth($month)
+    {
+        $this->selectedMonth = $month;
+        $this->showMonthPicker = false;
+        $this->updatedSelectedMonth($month);
+    }
+
+    public function toggleMonthPicker()
+    {
+        $this->showMonthPicker = !$this->showMonthPicker;
+    }
+
+    private function exportExcel($records)
+    {
+        
+        $startTime = microtime(true);
+
+        $spreadsheet = new Spreadsheet();
+        $activeWorksheet = $spreadsheet->getActiveSheet();
+
+        $activeWorksheet->setCellValue('A1', "Data");
+        $activeWorksheet->setCellValue('B1', "Tipologia");
+        $activeWorksheet->setCellValue('C1', "Causale");
+        $activeWorksheet->setCellValue('D1', "Nominativo");
+        $activeWorksheet->setCellValue('E1', "Stato");
+        $activeWorksheet->setCellValue('F1', "Entrata");
+        $activeWorksheet->setCellValue('G1', "Uscita");
+        $activeWorksheet->setCellValue('H1', "Origine");
+        $activeWorksheet->setCellValue('I1', "Destinazione");
+        $activeWorksheet->setCellValue('J1', "Metodo di pagamento");
+
+        $activeWorksheet->getStyle('A1:J1')->getFill()
+            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+            ->getStartColor()->setARGB('FF0C6197');
+
+        $activeWorksheet->getStyle('A1:J1')->getFont()->getColor()->setARGB('FFFFFFFF');
+
+        $idx = 2;
+        foreach($records as $record)
+        {
+            $activeWorksheet->setCellValue('A' . $idx, date("d/m/Y", strtotime($record->date)));
+            $activeWorksheet->setCellValue('B' . $idx, $record->commercial ? 'Commerciale' : 'Non commerciale');
+            $activeWorksheet->setCellValue('C' . $idx, $record->causal_name);
+            $activeWorksheet->setCellValue('D' . $idx, $record->type == 'IN' ? ($record->member->first_name . " " . $record->member->last_name) : @$record->supplier->name);
+            $activeWorksheet->setCellValue('E' . $idx, $record->deleted ? 'Annullata' : '');
+            $activeWorksheet->setCellValue('F' . $idx, $record->type == 'IN' ? formatPrice($record->amount) : '');
+            $activeWorksheet->setCellValue('G' . $idx, $record->type == 'OUT' ? formatPrice($record->amount) : '');
+            $activeWorksheet->setCellValue('H' . $idx, $record->type == 'OUT' ? $record->origin : '');
+            $activeWorksheet->setCellValue('I' . $idx, $record->type == 'IN' ? $record->destination : '');
+            $activeWorksheet->setCellValue('J' . $idx, $record->payment_method->name);
+            $idx++;
+        }
+
+        $activeWorksheet->getColumnDimension('A')->setWidth(10);
+        $activeWorksheet->getColumnDimension('B')->setWidth(30);
+        $activeWorksheet->getColumnDimension('C')->setWidth(30);
+        $activeWorksheet->getColumnDimension('D')->setWidth(30);
+        $activeWorksheet->getColumnDimension('E')->setWidth(10);
+        $activeWorksheet->getColumnDimension('F')->setWidth(10);
+        $activeWorksheet->getColumnDimension('G')->setWidth(10);
+        $activeWorksheet->getColumnDimension('H')->setWidth(20);
+        $activeWorksheet->getColumnDimension('I')->setWidth(20);
+        $activeWorksheet->getColumnDimension('J')->setWidth(30);
+
+        $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
+        Log::info('exportWithData: Preparing to save file', [
+            'filename' => $filename,
+            //'total_processing_time' => microtime(true) - $startTime,
+            'memory_before_save' => memory_get_usage(true)
+        ]);
+
+        try {
+            $currentClient = session('currentClient', 'default');
+            $tempPath = sys_get_temp_dir() . '/' . $filename;
+
+            $writer = new Xlsx($spreadsheet);
+
+            $writer->save($tempPath);
+            
+            unset($spreadsheet, $activeWorksheet, $writer);
+            gc_collect_cycles();
+
+            Log::info('exportWithData: Uploading to S3');
+            $disk = Storage::disk('s3');
+            $s3Path = $currentClient . '/prima_nota/' . $filename;
+
+            $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
+            if (!$disk->exists($primaNotaFolderPath)) {
+                $disk->put($primaNotaFolderPath, '');
+            }
+
+            $uploadStart = microtime(true);
+            $fileContent = file_get_contents($tempPath);
+            $uploaded = $disk->put($s3Path, $fileContent, 'private');
+            $uploadTime = microtime(true) - $uploadStart;
+
+            if (!$uploaded) {
+                throw new \Exception('Failed to upload file to Wasabi S3');
+            }
+
+            Log::info("Export completed successfully", [
+                'client' => $currentClient,
+                'path' => $s3Path,
+                'file_size' => filesize($tempPath),
+                'records_processed' => $recordsProcessed,
+                'upload_time' => $uploadTime,
+                'total_time' => microtime(true) - $startTime,
+                'memory_peak' => memory_get_peak_usage(true)
+            ]);
+
+            if (file_exists($tempPath)) {
+                unlink($tempPath);
+            }
+
+            $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
+            return redirect($downloadUrl);
+        } catch (\Exception $e) {
+            Log::error('Export S3 error - falling back to local', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'client' => session('currentClient', 'unknown'),
+                'filename' => $filename,
+                'records_processed' => $recordsProcessed ?? 0,
+                'time_elapsed' => microtime(true) - $startTime
+            ]);
+
+            // Fallback logic remains the same...
+            $currentClient = session('currentClient', 'default');
+            $clientFolder = storage_path('app/prima_nota/' . $currentClient);
+
+            if (!is_dir($clientFolder)) {
+                mkdir($clientFolder, 0755, true);
+                Log::info("Created local client prima_nota folder: {$clientFolder}");
+            }
+
+            $localPath = $clientFolder . '/' . $filename;
+
+            if (isset($tempPath) && file_exists($tempPath)) {
+                rename($tempPath, $localPath);
+            } else {
+                $writer = new Xlsx($spreadsheet);
+                $writer->save($localPath);
+                unset($spreadsheet, $activeWorksheet, $writer);
+            }
+
+            gc_collect_cycles();
+
+            Log::warning("Export saved locally due to S3 error", [
+                'client' => $currentClient,
+                'local_path' => $localPath,
+                'error' => $e->getMessage()
+            ]);
+
+            session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
+            return response()->download($localPath)->deleteFileAfterSend();
+        }
+    }
+
 }

+ 9 - 0
app/Http/Livewire/RecordIN.php

@@ -51,10 +51,12 @@ class RecordIN extends Component
     public $courseId = 0;
     public $rateId = 0;
     public $months = array();
+    
 
     public $records, $dataId, $member_id, $supplier_id,
         $causal_id,
         $payment_method_id,
+        $destination_id,
         $date,
         $month,
         $year,
@@ -99,6 +101,7 @@ class RecordIN extends Component
 
     public $causals = array();
     public $payments = array();
+    public $banks = array();
     public $members = array();
     public $vats = array();
 
@@ -242,6 +245,7 @@ class RecordIN extends Component
         $this->member_id = null;
         $this->supplier_id = null;
         $this->payment_method_id = null;
+        $this->destination_id = null;
         $this->commercial = 0;
         $this->corrispettivo_fiscale = false;
         $this->date = date("Y-m-d");
@@ -351,6 +355,7 @@ class RecordIN extends Component
 
         $this->refreshMembers();
         $this->payments = \App\Models\PaymentMethod::select('id', 'name')->where('enabled', true)->whereIn('type', array('ALL', 'IN'))->orderBy('name')->get();
+        $this->banks = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', array('ALL', 'IN'))->orderBy('name')->get();
         $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
 
         if ($this->first) {
@@ -523,6 +528,7 @@ class RecordIN extends Component
                         'member_id' => $this->member_id,
                         'supplier_id' => null,
                         'payment_method_id' => $p->id,
+                        'destination_id' => $this->destination_id,
                         'commercial' => $this->commercial,
                         'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                         'date' => $this->date,
@@ -623,6 +629,7 @@ class RecordIN extends Component
                 'member_id' => $this->member_id,
                 'supplier_id' => $this->supplier_id,
                 'payment_method_id' => $this->payment_method_id,
+                'destination_id' => $this->destination_id,
                 'commercial' => $this->commercial,
                 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                 'date' => $this->date,
@@ -768,6 +775,7 @@ class RecordIN extends Component
                     $this->payment_method_id = $record->payment_method_id;
                 }
 
+                $this->destination_id = $record->destination_id;
                 $this->supplier_id = $record->supplier_id;
                 $this->amount = $record->amount;
                 $this->commercial = $record->commercial;
@@ -933,6 +941,7 @@ class RecordIN extends Component
                 'member_id' => $this->member_id,
                 'supplier_id' => $this->supplier_id,
                 'payment_method_id' => $this->payment_method_id,
+                'destination_id' => $this->destination_id,
                 'commercial' => $this->commercial,
                 'corrispettivo_fiscale' => $this->corrispettivo_fiscale,
                 'date' => date("Y-m-d", strtotime($this->date)),

+ 7 - 0
app/Http/Livewire/RecordOUT.php

@@ -53,6 +53,7 @@ class RecordOUT extends Component
         $supplier_id,
         $causal_id,
         $payment_method_id,
+        $origin_id,
         $date,
         $data_pagamento,
         $month,
@@ -82,6 +83,7 @@ class RecordOUT extends Component
 
     public $causals = array();
     public $payments = array();
+    public $banks = array();
     public $suppliers = array();
 
     public $rows = array();
@@ -143,6 +145,7 @@ class RecordOUT extends Component
         $this->member_id = null;
         $this->supplier_id = null;
         $this->payment_method_id = null;
+        $this->origin_id = null;
         $this->date = date("Y-m-d");
         $this->data_pagamento = date("Y-m-d");
         $this->attachment = null;
@@ -222,6 +225,7 @@ class RecordOUT extends Component
 
         $this->suppliers = \App\Models\Supplier::select('name', 'id')->orderBy('name')->get();
         $this->payments = \App\Models\PaymentMethod::select('id', 'name')->whereIn('type', array('ALL', 'OUT'))->where('enabled', true)->orderBy('name')->get();
+        $this->banks = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', array('ALL', 'OUT'))->orderBy('name')->get();
         $this->vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();
 
         $this->importCausals = [];
@@ -449,6 +453,7 @@ class RecordOUT extends Component
                 'member_id' => $this->member_id,
                 'supplier_id' => $this->supplier_id,
                 'payment_method_id' => $this->payment_method_id,
+                'origin_id' => $this->origin_id,
                 'date' => $this->date,
                 'data_pagamento' => $this->data_pagamento,
                 'attachment' => '',
@@ -610,6 +615,7 @@ class RecordOUT extends Component
                 $this->member_id = $record->member_id;
                 $this->supplier_id = $record->supplier_id;
                 $this->payment_method_id = $record->payment_method_id;
+                $this->origin_id = $record->origin_id;
                 $this->date = date("Y-m-d", strtotime($record->date));
                 $this->data_pagamento = $record->data_pagamento;
                 $this->type = $record->type;
@@ -760,6 +766,7 @@ class RecordOUT extends Component
                 'member_id' => $this->member_id,
                 'supplier_id' => $this->supplier_id,
                 'payment_method_id' => $this->payment_method_id,
+                'origin_id' => $this->origin_id,
                 'date' => $this->date,
                 'data_pagamento' => $this->data_pagamento,
                 'type' => $this->type,

+ 1410 - 0
app/Http/Livewire/RecordOld.php

@@ -0,0 +1,1410 @@
+<?php
+
+namespace App\Http\Livewire;
+
+use Livewire\Component;
+use DateInterval;
+use DatePeriod;
+use DateTime;
+
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Mail;
+use App\Mail\ExportNotification;
+use App\Jobs\ExportPrimaNota;
+use App\Http\Middleware\TenantMiddleware;
+
+class RecordOld extends Component
+{
+    public $records, $dataId, $totals;
+    public $in;
+    public $out;
+    public $payments = [];
+    public $fromDate;
+    public $toDate;
+    public $appliedFromDate;
+    public $appliedToDate;
+    public $exportFromDate;
+    public $exportToDate;
+    public $isExporting = false;
+    public $selectedPeriod = 'OGGI';
+    public $filterCausals = null;
+    public $filterMember = null;
+    public $isFiltering = false;
+    public array $recordDatas = [];
+    public array $labels = [];
+    public array $causals = [];
+    public $members = array();
+    public $sendViaEmail = false;
+    public $exportEmailAddress = '';
+    public $exportEmailSubject = 'Prima Nota - Export';
+    private $causalAmounts = [];
+
+    protected $rules = [
+        'exportEmailAddress' => 'required_if:sendViaEmail,true|email',
+        'exportEmailSubject' => 'required_if:sendViaEmail,true|string|max:255',
+    ];
+
+    protected $messages = [
+        'exportEmailAddress.required_if' => 'L\'indirizzo email è obbligatorio quando si sceglie di inviare via email.',
+        'exportEmailAddress.email' => 'Inserisci un indirizzo email valido.',
+        'exportEmailSubject.required_if' => 'L\'oggetto dell\'email è obbligatorio.',
+        'exportEmailSubject.max' => 'L\'oggetto dell\'email non può superare i 255 caratteri.',
+    ];
+    public function boot()
+    {
+        app(TenantMiddleware::class)->setupTenantConnection();
+
+    }
+    public function hydrate()
+    {
+        $this->emit('load-select');
+    }
+
+    public function mount()
+    {
+        $this->fromDate = date("Y-m-d");
+        $this->toDate = date("Y-m-d");
+
+        $this->appliedFromDate = date("Y-m-d");
+        $this->appliedToDate = date("Y-m-d");
+
+        $this->exportFromDate = date("Y-m-d");
+        $this->exportToDate = date("Y-m-d");
+
+        $this->exportEmailSubject = 'Prima Nota - Export del ' . date('d/m/Y');
+
+
+        $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
+
+        $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])->orderBy('last_name')->orderBy('first_name')->get();
+
+        $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->get();
+    }
+
+    private function generateExportDataAndTotals($fromDate, $toDate)
+    {
+        Log::info('generateExportDataAndTotals: Start (combined method)', [
+            'from_date' => $fromDate,
+            'to_date' => $toDate,
+            'memory_before' => memory_get_usage(true)
+        ]);
+
+        $exportRecords = array();
+        $exportTotals = array();
+
+        Log::info('generateExportDataAndTotals: Getting excluded members');
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+        Log::info('generateExportDataAndTotals: Excluded members retrieved', ['count' => count($exclude_from_records)]);
+
+        Log::info('generateExportDataAndTotals: Building main query');
+        $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
+            ->select(
+                'records.*',
+                'records_rows.id as row_id',
+                'records_rows.record_id',
+                'records_rows.causal_id',
+                'records_rows.amount',
+                'records_rows.note',
+                'records_rows.when',
+                'records_rows.vat_id',
+                'records_rows.created_at as row_created_at',
+                'records_rows.updated_at as row_updated_at'
+            )
+            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            ->whereBetween('date', [$fromDate, $toDate])
+            ->where(function ($query) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($query) {
+                        $query->where('records.corrispettivo_fiscale', true)
+                            ->orWhere('records.commercial', false);
+                    });
+            })
+            ->where(function ($query) use ($exclude_from_records) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($subquery) use ($exclude_from_records) {
+                        $subquery->whereNotIn('member_id', $exclude_from_records);
+                    });
+            });
+
+        Log::info('generateExportDataAndTotals: Applying causal filters');
+        if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
+            $causals = array();
+            foreach ($this->filterCausals as $z) {
+                $causals[] = $z;
+                $childs = \App\Models\Causal::where('parent_id', $z)->get();
+                foreach ($childs as $c) {
+                    $causals[] = $c->id;
+                    $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
+                    foreach ($childsX as $cX) {
+                        $causals[] = $cX->id;
+                    }
+                }
+            }
+            $datas->whereIn('causal_id', $causals);
+            Log::info('generateExportDataAndTotals: Causal filters applied', ['causal_count' => count($causals)]);
+        }
+
+        if ($this->filterMember != null && $this->filterMember > 0) {
+            $datas->where('member_id', $this->filterMember);
+            Log::info('generateExportDataAndTotals: Member filter applied', ['member_id' => $this->filterMember]);
+        }
+
+        Log::info('generateExportDataAndTotals: Executing query');
+        $queryStart = microtime(true);
+
+        $datas = $datas->orderBy('date', 'ASC')
+            ->orderBy('records.created_at', 'ASC')
+            ->orderBy('records_rows.id', 'ASC')
+            ->get();
+
+        $queryTime = microtime(true) - $queryStart;
+        Log::info('generateExportDataAndTotals: Query executed', [
+            'record_count' => $datas->count(),
+            'query_time' => $queryTime,
+            'memory_after_query' => memory_get_usage(true)
+        ]);
+
+        $groupedData = [];
+        $causalsCount = [];
+        $processedCount = 0;
+
+        // Initialize totals array
+        foreach ($this->payments as $p) {
+            $exportTotals[$p->name] = ["IN" => 0, "OUT" => 0];
+        }
+
+        Log::info('generateExportDataAndTotals: Starting combined data processing loop');
+        $loopStart = microtime(true);
+
+        foreach ($datas as $idx => $data) {
+            if ($processedCount % 100 == 0) {
+                Log::info('generateExportDataAndTotals: Processing progress', [
+                    'processed' => $processedCount,
+                    'total' => $datas->count(),
+                    'memory_current' => memory_get_usage(true),
+                    'memory_peak' => memory_get_peak_usage(true)
+                ]);
+            }
+
+            try {
+                $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
+                $paymentCheck = $data->payment_method->money;
+
+                if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
+                    if (!$data->deleted) {
+                        $amount = $data->amount;
+                        $amount += getVatValue($amount, $data->vat_id);
+                    } else {
+                        $amount = $data->amount;
+                    }
+
+                    // CALCULATE TOTALS HERE (in the same loop)
+                    if (!$data->deleted) {
+                        $exportTotals[$data->payment_method->name][$data->type] += $amount;
+                    }
+
+                    $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
+                    $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
+
+                    $nominativo = '';
+                    if ($data->type == "IN") {
+                        if ($data->member) {
+                            $nominativo = $data->member->last_name . " " . $data->member->first_name;
+                        }
+                    } else {
+                        if ($data->supplier) {
+                            $nominativo = $data->supplier->name;
+                        }
+                    }
+
+                    $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
+
+                    if (!isset($groupedData[$groupKey])) {
+                        $groupedData[$groupKey] = [
+                            'date' => $data->date,
+                            'type_label' => $typeLabel,
+                            'payment_method' => $data->payment_method->name,
+                            'transaction_type' => $data->type,
+                            'nominativo' => $nominativo,
+                            'amount' => 0,
+                            'deleted' => false,
+                            'causals' => [],
+                            'notes' => []
+                        ];
+                        $causalsCount[$groupKey] = [];
+                    }
+
+                    $groupedData[$groupKey]['amount'] += $amount;
+                    $causalsCount[$groupKey][$causalCheck->getTree()] = true;
+
+                    if (!empty($data->note)) {
+                        $groupedData[$groupKey]['notes'][] = $data->note;
+                    }
+
+                    if ($data->deleted) {
+                        $groupedData[$groupKey]['deleted'] = true;
+                    }
+                }
+
+                $processedCount++;
+            } catch (\Exception $e) {
+                Log::error('generateExportDataAndTotals: Error processing individual record', [
+                    'record_id' => $data->id ?? 'unknown',
+                    'error' => $e->getMessage(),
+                    'processed_so_far' => $processedCount
+                ]);
+                throw $e;
+            }
+        }
+
+        $loopTime = microtime(true) - $loopStart;
+        Log::info('generateExportDataAndTotals: Combined processing loop completed', [
+            'total_processed' => $processedCount,
+            'grouped_records' => count($groupedData),
+            'loop_time' => $loopTime,
+            'memory_after_loop' => memory_get_usage(true)
+        ]);
+
+        Log::info('generateExportDataAndTotals: Building final export records');
+        $finalStart = microtime(true);
+
+        foreach ($groupedData as $groupKey => $group) {
+            $causalsInGroup = array_keys($causalsCount[$groupKey]);
+
+            $causalDisplay = $group['type_label'];
+
+            if (count($causalsInGroup) > 1) {
+                $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
+            } else {
+                $detailDisplay = $causalsInGroup[0];
+            }
+
+            $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
+
+            if (!isset($exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']])) {
+                $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
+            }
+
+            $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
+        }
+
+        $finalTime = microtime(true) - $finalStart;
+        Log::info('generateExportDataAndTotals: Final processing completed', [
+            'final_export_records' => count($exportRecords),
+            'final_export_totals' => count($exportTotals),
+            'final_time' => $finalTime,
+            'total_time' => microtime(true) - $loopStart + $queryTime,
+            'memory_final' => memory_get_usage(true),
+            'memory_peak' => memory_get_peak_usage(true)
+        ]);
+
+        // Cleanup
+        unset($datas, $groupedData, $causalsCount);
+        gc_collect_cycles();
+
+        Log::info('generateExportDataAndTotals: Completed with cleanup', [
+            'memory_after_cleanup' => memory_get_usage(true)
+        ]);
+
+        return ['records' => $exportRecords, 'totals' => $exportTotals];
+    }
+
+    private function generateExportTotals($fromDate, $toDate)
+    {
+        $exportTotals = array();
+
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+
+        $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
+            ->select(
+                'records.*',
+                'records_rows.id as row_id',
+                'records_rows.record_id',
+                'records_rows.causal_id',
+                'records_rows.amount',
+                'records_rows.note',
+                'records_rows.when',
+                'records_rows.vat_id',
+            )
+            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            ->whereBetween('date', [$fromDate, $toDate])
+            ->where(function ($query) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($query) {
+                        $query->where('records.corrispettivo_fiscale', true)
+                            ->orWhere('records.commercial', false);
+                    });
+            })
+            ->where(function ($query) use ($exclude_from_records) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($subquery) use ($exclude_from_records) {
+                        $subquery->whereNotIn('member_id', $exclude_from_records);
+                    });
+            });
+
+        if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
+            $causals = array();
+            foreach ($this->filterCausals as $z) {
+                $causals[] = $z;
+                $childs = \App\Models\Causal::where('parent_id', $z)->get();
+                foreach ($childs as $c) {
+                    $causals[] = $c->id;
+                    $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
+                    foreach ($childsX as $cX) {
+                        $causals[] = $cX->id;
+                    }
+                }
+            }
+            $datas->whereIn('causal_id', $causals);
+        }
+        if ($this->filterMember != null && $this->filterMember > 0) {
+            $datas->where('member_id', $this->filterMember);
+        }
+        $datas = $datas->orderBy('date', 'ASC')
+            ->orderBy('records.created_at', 'ASC')
+            ->orderBy('records_rows.id', 'ASC')
+            ->get();
+
+        foreach ($datas as $data) {
+            $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
+            $paymentCheck = $data->payment_method->money;
+
+            if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
+                if (!$data->deleted) {
+                    $amount = $data->amount;
+                    $amount += getVatValue($amount, $data->vat_id);
+                } else {
+                    $amount = $data->amount;
+                }
+
+                if (!isset($exportTotals[$data->payment_method->name])) {
+                    $exportTotals[$data->payment_method->name]["IN"] = 0;
+                    $exportTotals[$data->payment_method->name]["OUT"] = 0;
+                }
+
+                if (!$data->deleted)
+                    $exportTotals[$data->payment_method->name][$data->type] += $amount;
+            }
+        }
+
+        return $exportTotals;
+    }
+    public function resetFilters()
+    {
+        $this->selectedPeriod = 'OGGI';
+        $this->filterCausals = [];
+        $this->filterMember = null;
+
+        $today = date("Y-m-d");
+        $this->fromDate = $today;
+        $this->toDate = $today;
+        $this->appliedFromDate = $today;
+        $this->appliedToDate = $today;
+
+        $this->emit('filters-reset');
+    }
+
+    public function applyFilters()
+    {
+        $this->isFiltering = true;
+
+        $this->setPeriodDates();
+
+        $this->appliedFromDate = $this->fromDate;
+        $this->appliedToDate = $this->toDate;
+
+        $this->render();
+
+        $this->isFiltering = false;
+
+        $this->emit('filters-applied');
+    }
+
+    private function setPeriodDates()
+    {
+        $today = now();
+
+        switch ($this->selectedPeriod) {
+            case 'OGGI':
+                $this->fromDate = $today->format('Y-m-d');
+                $this->toDate = $today->format('Y-m-d');
+                break;
+
+            case 'IERI':
+                $yesterday = $today->copy()->subDay();
+                $this->fromDate = $yesterday->format('Y-m-d');
+                $this->toDate = $yesterday->format('Y-m-d');
+                break;
+
+            case 'MESE CORRENTE':
+                $this->fromDate = $today->copy()->startOfMonth()->format('Y-m-d');
+                $this->toDate = $today->copy()->endOfMonth()->format('Y-m-d');
+                break;
+
+            case 'MESE PRECEDENTE':
+                $lastMonth = $today->copy()->subMonth();
+                $this->fromDate = $lastMonth->startOfMonth()->format('Y-m-d');
+                $this->toDate = $lastMonth->endOfMonth()->format('Y-m-d');
+                break;
+
+            case 'ULTIMO TRIMESTRE':
+                $this->fromDate = $today->copy()->subMonths(3)->format('Y-m-d');
+                $this->toDate = $today->format('Y-m-d');
+                break;
+
+            case 'ULTIMO QUADRIMESTRE':
+                $this->fromDate = $today->copy()->subMonths(4)->format('Y-m-d');
+                $this->toDate = $today->format('Y-m-d');
+                break;
+        }
+    }
+
+    public function getCausals($records, $indentation)
+    {
+        foreach ($records as $record) {
+            $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
+            if (count($record->childs))
+                $this->getCausals($record->childs, $indentation + 1);
+        }
+    }
+
+    public function getMonth($m)
+    {
+        $ret = '';
+        switch ($m) {
+            case 1:
+                $ret = 'Gennaio';
+                break;
+            case 2:
+                $ret = 'Febbraio';
+                break;
+            case 3:
+                $ret = 'Marzo';
+                break;
+            case 4:
+                $ret = 'Aprile';
+                break;
+            case 5:
+                $ret = 'Maggio';
+                break;
+            case 6:
+                $ret = 'Giugno';
+                break;
+            case 7:
+                $ret = 'Luglio';
+                break;
+            case 8:
+                $ret = 'Agosto';
+                break;
+            case 9:
+                $ret = 'Settembre';
+                break;
+            case 10:
+                $ret = 'Ottobre';
+                break;
+            case 11:
+                $ret = 'Novembre';
+                break;
+            case 12:
+                $ret = 'Dicembre';
+                break;
+            default:
+                $ret = '';
+                break;
+        }
+        return $ret;
+    }
+
+
+
+    public function render()
+    {
+        $month = 0;
+        $year = 0;
+
+        $this->records = array();
+        $this->totals = array();
+        $this->causalAmounts = array();
+
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+
+        $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
+            ->select(
+                'records.*',
+                'records_rows.id as row_id',
+                'records_rows.record_id',
+                'records_rows.causal_id',
+                'records_rows.amount',
+                'records_rows.note',
+                'records_rows.when',
+                'records_rows.vat_id',
+            )
+            ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            ->whereBetween('date', [$this->appliedFromDate, $this->appliedToDate])
+            ->where(function ($query) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($query) {
+                        $query->where('records.corrispettivo_fiscale', true)
+                            ->orWhere('records.commercial', false);
+                    });
+            })
+            ->where(function ($query) use ($exclude_from_records) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($subquery) use ($exclude_from_records) {
+                        $subquery->whereNotIn('member_id', $exclude_from_records);
+                    });
+            });
+
+        if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
+            $causals = array();
+            foreach ($this->filterCausals as $z) {
+                $causals[] = $z;
+                $childs = \App\Models\Causal::where('parent_id', $z)->get();
+                foreach ($childs as $c) {
+                    $causals[] = $c->id;
+                    $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
+                    foreach ($childsX as $cX) {
+                        $causals[] = $cX->id;
+                    }
+                }
+            }
+            $datas->whereIn('causal_id', $causals);
+        }
+        if ($this->filterMember != null && $this->filterMember > 0) {
+            $datas->where('member_id', $this->filterMember);
+        }
+        $datas = $datas->orderBy('date', 'ASC')
+            ->orderBy('records.created_at', 'ASC')
+            ->orderBy('records_rows.id', 'ASC')
+            ->get();
+
+        $groupedData = [];
+        $causalsCount = [];
+        $causalsAmounts = [];
+        $nominativi = [];
+
+        foreach ($datas as $idx => $data) {
+
+            $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
+            $paymentCheck = $data->payment_method->money;
+
+            if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
+
+                if (!$data->deleted) {
+                    $amount = $data->amount;
+                    $amount += getVatValue($amount, $data->vat_id);
+                } else {
+                    $amount = $data->amount;
+                }
+
+                $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
+                $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
+
+                $nominativo = '';
+                if ($data->type == "IN") {
+                    if ($data->member) {
+                        $nominativo = $data->member->last_name . " " . $data->member->first_name;
+                    }
+                } else {
+                    if ($data->supplier) {
+                        $nominativo = $data->supplier->name;
+                    }
+                }
+
+                $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
+
+                if (!isset($groupedData[$groupKey])) {
+                    $groupedData[$groupKey] = [
+                        'date' => $data->date,
+                        'type_label' => $typeLabel,
+                        'payment_method' => $data->payment_method->name,
+                        'transaction_type' => $data->type,
+                        'nominativo' => $nominativo,
+                        'amount' => 0,
+                        'deleted' => false,
+                        'causals' => [],
+                        'notes' => []
+                    ];
+                    $causalsCount[$groupKey] = [];
+                    $causalsAmounts[$groupKey] = []; // Initialize causal amounts for this group
+                    $nominativi[$groupKey] = $nominativo;
+                }
+
+                $groupedData[$groupKey]['amount'] += $amount;
+                $causalsCount[$groupKey][$causalCheck->getTree()] = true;
+
+                $causalName = $causalCheck->getTree();
+                if (!isset($causalsAmounts[$groupKey][$causalName])) {
+                    $causalsAmounts[$groupKey][$causalName] = 0;
+                }
+                $causalsAmounts[$groupKey][$causalName] += $amount;
+
+                if (!empty($data->note)) {
+                    $groupedData[$groupKey]['notes'][] = $data->note;
+                }
+                if ($data->deleted) {
+                    $groupedData[$groupKey]['deleted'] = true;
+                }
+            }
+        }
+
+        foreach ($groupedData as $groupKey => $group) {
+            $causalsInGroup = array_keys($causalsCount[$groupKey]);
+
+            $causalDisplay = $group['type_label'];
+
+            if (count($causalsInGroup) > 1) {
+                $causalAmountsForJs = [];
+                foreach ($causalsInGroup as $causalName) {
+                    $causalAmountsForJs[] = $causalName . ':::' . formatPrice($causalsAmounts[$groupKey][$causalName]);
+                }
+                $detailDisplay = 'Varie|' . implode('|', $causalAmountsForJs);
+            } else {
+                $detailDisplay = $causalsInGroup[0];
+            }
+
+            $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
+
+            if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
+                $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
+            }
+
+            $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
+
+            if (!isset($this->totals[$group['payment_method']])) {
+                $this->totals[$group['payment_method']]["IN"] = 0;
+                $this->totals[$group['payment_method']]["OUT"] = 0;
+            }
+
+            if (!$group['deleted'])
+                $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
+        }
+
+        return view('livewire.records_old');
+    }
+
+    private function getLabels($fromDate, $toDate)
+    {
+        $begin = new DateTime($fromDate);
+        $end = new DateTime($toDate);
+
+        $interval = DateInterval::createFromDateString('1 day');
+        $date_range = new DatePeriod($begin, $interval, $end);
+        foreach ($date_range as $date) {
+            $labels[] = $date->format('d/M');
+        }
+
+        return $labels;
+    }
+
+    private function getRecordData($type, $fromDate, $toDate)
+    {
+        $data = [];
+        $begin = new DateTime($fromDate);
+        $end = new DateTime($toDate);
+
+        $interval = DateInterval::createFromDateString('1 day');
+        $date_range = new DatePeriod($begin, $interval, $end);
+
+        foreach ($date_range as $date) {
+            if ($type == 'IN') {
+                $found = false;
+                foreach ($this->in as $in) {
+                    if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
+                        $data[] = number_format($in->total, 0, "", "");
+                        $found = true;
+                    }
+                }
+                if (!$found)
+                    $data[] = 0;
+            }
+            if ($type == 'OUT') {
+                $found = false;
+                foreach ($this->out as $out) {
+                    if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
+                        $data[] = number_format($out->total, 0, "", "");
+                        $found = true;
+                    }
+                }
+                if (!$found)
+                    $data[] = 0;
+            }
+        }
+
+        return $data;
+    }
+
+    public function openExportModal()
+    {
+        $this->exportFromDate = $this->appliedFromDate;
+        $this->exportToDate = $this->appliedToDate;
+
+        // Reset email options
+        $this->sendViaEmail = false;
+        $this->exportEmailAddress = $this->getPreferredEmail();
+        $this->updateEmailSubject();
+
+        $this->emit('show-export-modal');
+    }
+
+    public function exportWithDateRange()
+    {
+
+        Log::info('=== EXPORT START ===', [
+            'user_id' => auth()->id(),
+            'from_date' => $this->exportFromDate,
+            'to_date' => $this->exportToDate,
+            'send_via_email' => $this->sendViaEmail,
+            'memory_usage' => memory_get_usage(true),
+            'memory_peak' => memory_get_peak_usage(true),
+            'time_limit' => ini_get('max_execution_time')
+        ]);
+
+        $this->isExporting = true;
+        $this->emit('$refresh');
+        usleep(100000);
+
+        if ($this->sendViaEmail) {
+            Log::info('Export: Validating email fields');
+            $this->validate([
+                'exportEmailAddress' => 'required|email',
+                'exportEmailSubject' => 'required|string|max:255',
+            ]);
+            Log::info('Export: Email validation passed');
+        }
+
+        $this->isExporting = true;
+
+        try {
+            Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
+            $startTime = microtime(true);
+
+            // *** THIS IS THE KEY CHANGE - USE ONLY THE COMBINED METHOD ***
+            $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
+            $exportRecords = $result['records'];
+            $exportTotals = $result['totals'];
+
+            $dataGenTime = microtime(true) - $startTime;
+            Log::info('Export: COMBINED data generation completed (NO SEPARATE TOTALS CALL)', [
+                'records_count' => count($exportRecords),
+                'totals_count' => count($exportTotals),
+                'generation_time' => $dataGenTime,
+                'memory_usage' => memory_get_usage(true),
+                'memory_peak' => memory_get_peak_usage(true)
+            ]);
+
+
+            if ($this->sendViaEmail) {
+                Log::info('Export: Dispatching to background job');
+                $this->dispatchExportJob($exportRecords, $exportTotals);
+                Log::info('Export: Job dispatched successfully');
+            } else {
+                Log::info('Export: Starting direct download export');
+                $exportStartTime = microtime(true);
+
+                $result = $this->exportWithData($exportRecords, $exportTotals);
+
+                $exportTime = microtime(true) - $exportStartTime;
+                Log::info('Export: Direct export completed', [
+                    'export_time' => $exportTime,
+                    'total_time' => microtime(true) - $startTime,
+                    'memory_usage' => memory_get_usage(true),
+                    'memory_peak' => memory_get_peak_usage(true)
+                ]);
+
+                return $result;
+            }
+        } catch (\Illuminate\Validation\ValidationException $e) {
+            Log::error('Export: Validation error', [
+                'error' => $e->getMessage(),
+                'errors' => $e->errors()
+            ]);
+            $this->isExporting = false;
+            throw $e;
+        } catch (\Exception $e) {
+            Log::error('Export: General error', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'memory_usage' => memory_get_usage(true),
+                'memory_peak' => memory_get_peak_usage(true),
+                'execution_time' => microtime(true) - ($startTime ?? 0)
+            ]);
+
+            $this->isExporting = false;
+
+            if ($this->sendViaEmail) {
+                $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
+            } else {
+                session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
+            }
+        } finally {
+            Log::info('Export: Cleanup phase');
+            $this->isExporting = false;
+            $this->emit('export-complete');
+            $this->emit('hide-export-modal');
+            Log::info('=== EXPORT END ===');
+        }
+    }
+    private function getEstimatedRecordCount($fromDate, $toDate)
+    {
+        $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
+
+        $query = \App\Models\Record::join('records_rows', 'records.id', '=', 'records_rows.record_id')
+            ->whereBetween('date', [$fromDate, $toDate])
+            ->where(function ($query) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($query) {
+                        $query->where('records.corrispettivo_fiscale', true)
+                            ->orWhere('records.commercial', false);
+                    });
+            })
+            ->where(function ($query) use ($exclude_from_records) {
+                $query->where('type', 'OUT')
+                    ->orWhere(function ($subquery) use ($exclude_from_records) {
+                        $subquery->whereNotIn('member_id', $exclude_from_records);
+                    });
+            });
+
+        if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
+            $causals = array();
+            foreach ($this->filterCausals as $z) {
+                $causals[] = $z;
+                $childs = \App\Models\Causal::where('parent_id', $z)->get();
+                foreach ($childs as $c) {
+                    $causals[] = $c->id;
+                    $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
+                    foreach ($childsX as $cX) {
+                        $causals[] = $cX->id;
+                    }
+                }
+            }
+            $query->whereIn('causal_id', $causals);
+        }
+
+        if ($this->filterMember != null && $this->filterMember > 0) {
+            $query->where('member_id', $this->filterMember);
+        }
+
+        return $query->count();
+    }
+
+    private function getMemberName($memberId)
+    {
+        $member = \App\Models\Member::find($memberId);
+        return $member ? $member->last_name . ' ' . $member->first_name : 'Sconosciuto';
+    }
+
+    private function getCausalsNames($causalIds)
+    {
+        if (!is_array($causalIds)) {
+            return null;
+        }
+
+        $causals = \App\Models\Causal::whereIn('id', $causalIds)->pluck('name')->toArray();
+        return implode(', ', $causals);
+    }
+
+    public function updatedExportFromDate()
+    {
+        $this->updateEmailSubject();
+    }
+
+    public function updatedExportToDate()
+    {
+        $this->updateEmailSubject();
+    }
+
+    public function updatedSendViaEmail($value)
+    {
+        if ($value && empty($this->exportEmailAddress)) {
+            $this->exportEmailAddress = $this->getPreferredEmail();
+        }
+    }
+
+    public function resetEmailForm()
+    {
+        $this->sendViaEmail = false;
+        $this->exportEmailAddress = $this->getPreferredEmail();
+        $this->updateEmailSubject();
+    }
+
+    private function updateEmailSubject()
+    {
+        if (!empty($this->exportFromDate) && !empty($this->exportToDate)) {
+            $fromFormatted = date('d/m/Y', strtotime($this->exportFromDate));
+            $toFormatted = date('d/m/Y', strtotime($this->exportToDate));
+
+            if ($this->exportFromDate === $this->exportToDate) {
+                $this->exportEmailSubject = "Prima Nota - Export del {$fromFormatted}";
+            } else {
+                $this->exportEmailSubject = "Prima Nota - Export dal {$fromFormatted} al {$toFormatted}";
+            }
+        }
+    }
+
+
+    /**
+     * Dispatch export job to queue
+     */
+    private function dispatchExportJob($exportRecords, $exportTotals)
+    {
+        try {
+            // Prepare filter descriptions for the job
+            $filterDescriptions = [
+                'member' => $this->filterMember ? $this->getMemberName($this->filterMember) : null,
+                'causals' => $this->filterCausals ? $this->getCausalsNames($this->filterCausals) : null,
+            ];
+
+            $paymentsArray = $this->payments->map(function ($payment) {
+                return [
+                    'id' => $payment->id,
+                    'name' => $payment->name,
+                    'type' => $payment->type
+                ];
+            })->toArray();
+
+            // Dispatch job to background queue
+            ExportPrimaNota::dispatch(
+                $exportRecords,
+                $exportTotals,
+                $this->exportEmailAddress,
+                $this->exportEmailSubject,
+                [
+                    'from' => date('d/m/Y', strtotime($this->exportFromDate)),
+                    'to' => date('d/m/Y', strtotime($this->exportToDate))
+                ],
+                auth()->id(),
+                $paymentsArray,
+                $filterDescriptions
+            );
+
+            $this->emit('export-email-queued');
+            session()->flash('success', 'Export in corso! Riceverai l\'email a breve alla casella: ' . $this->exportEmailAddress);
+
+            Log::info('Export job dispatched', [
+                'user_id' => auth()->id(),
+                'email' => $this->exportEmailAddress,
+                'date_range' => [$this->exportFromDate, $this->exportToDate],
+                'total_records' => count($exportRecords)
+            ]);
+        } catch (\Exception $e) {
+            Log::error('Failed to dispatch export job', [
+                'user_id' => auth()->id(),
+                'email' => $this->exportEmailAddress,
+                'error' => $e->getMessage()
+            ]);
+
+            throw new \Exception('Errore nell\'avvio dell\'export: ' . $e->getMessage());
+        }
+    }
+
+
+    function export()
+    {
+        $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
+        $exportRecords = $result['records'];
+        $exportTotals = $result['totals'];
+
+        return $this->exportWithData($exportRecords, $exportTotals);
+    }
+
+    private function exportWithData($exportRecords, $exportTotals)
+    {
+        Log::info('exportWithData: Starting Excel generation', [
+            'records_count' => count($exportRecords),
+            'totals_count' => count($exportTotals),
+            'memory_before' => memory_get_usage(true)
+        ]);
+
+        $startTime = microtime(true);
+
+        Log::info('exportWithData: Setting memory and GC');
+        ini_set('memory_limit', '512M');
+        gc_enable();
+
+        Log::info('exportWithData: Preparing column letters');
+        $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
+
+        Log::info('exportWithData: Creating spreadsheet object');
+        $spreadsheet = new Spreadsheet();
+        $activeWorksheet = $spreadsheet->getActiveSheet();
+
+        Log::info('exportWithData: Setting basic headers');
+        $activeWorksheet->setCellValue('A1', "Data");
+        $activeWorksheet->setCellValue('B1', "Tipologia");
+        $activeWorksheet->setCellValue('C1', "Causale");
+        $activeWorksheet->setCellValue('D1', "Nominativo");
+        $activeWorksheet->setCellValue('E1', "Stato");
+        $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
+        $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
+
+        $activeWorksheet->getStyle('A1:Q1')->getFill()
+            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
+            ->getStartColor()->setARGB('FF0C6197');
+
+        $activeWorksheet->getStyle('A1:Q1')->getFont()->getColor()->setARGB('FFFFFFFF');
+
+        $idx = 0;
+        foreach ($this->payments as $p) {
+            if ($idx >= count($letters)) {
+                Log::warning('exportWithData: Reached letter limit', ['payment_index' => $idx]);
+                break;
+            }
+            Log::debug('exportWithData: Setting payment header', [
+                'payment_name' => $p->name,
+                'column_index' => $idx,
+                'column_letter' => $letters[$idx]
+            ]);
+
+            $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
+            $idx++;
+            if ($idx >= count($letters)) {
+                break;
+            }
+            $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
+            $idx++;
+        }
+
+        Log::info('exportWithData: Setting sub-headers');
+        $idx = 0;
+        $activeWorksheet->setCellValue('A2', "");
+        $activeWorksheet->setCellValue('B2', "");
+        $activeWorksheet->setCellValue('C2', "");
+        $activeWorksheet->setCellValue('D2', "");
+        $activeWorksheet->setCellValue('E2', "");
+
+        foreach ($this->payments as $p) {
+            if ($p->type == 'ALL') {
+                if ($idx >= count($letters)) {
+                    break;
+                }
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
+                $idx++;
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
+                $idx++;
+            } elseif ($p->type == 'IN') {
+                if ($idx >= count($letters)) {
+                    break;
+                }
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
+                $idx++;
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "");
+                $idx++;
+            } elseif ($p->type == 'OUT') {
+                if ($idx >= count($letters)) {
+                    break;
+                }
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "");
+                $idx++;
+                $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
+                $idx++;
+            }
+        }
+
+        Log::info('exportWithData: Applying header styles');
+        $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
+        $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
+
+        Log::info('exportWithData: Starting data row processing');
+        $count = 3;
+        $batchSize = 1000;
+        $recordsProcessed = 0;
+
+        $totalRecords = count($exportRecords);
+        Log::info('exportWithData: Processing records in batches', [
+            'total_records' => $totalRecords,
+            'batch_size' => $batchSize
+        ]);
+
+        $recordsArray = array_chunk($exportRecords, $batchSize, true);
+        Log::info('exportWithData: Created batches', ['batch_count' => count($recordsArray)]);
+
+        foreach ($recordsArray as $batchIndex => $recordsBatch) {
+            Log::info('exportWithData: Processing batch', [
+                'batch_index' => $batchIndex,
+                'batch_size' => count($recordsBatch),
+                'memory_current' => memory_get_usage(true),
+                'time_elapsed' => microtime(true) - $startTime
+            ]);
+
+            foreach ($recordsBatch as $causal => $record) {
+                if ($recordsProcessed % 250 == 0) {
+                    Log::info('exportWithData: Record processing progress', [
+                        'processed' => $recordsProcessed,
+                        'total' => $totalRecords,
+                        'current_row' => $count,
+                        'memory_usage' => memory_get_usage(true),
+                        'time_elapsed' => microtime(true) - $startTime
+                    ]);
+                }
+
+                try {
+                    $check = $causal;
+                    $parts = explode("§", $check);
+                    $d = $parts[0] ?? '';
+                    $c = $parts[1] ?? '';
+                    $j = $parts[2] ?? '';
+                    $det = $parts[3] ?? '';
+                    $deleted = $parts[4] ?? '';
+
+                    $detailParts = explode('|', $det);
+                    $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
+
+                    Log::debug('exportWithData: Setting row cells', ['row' => $count]);
+                    $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
+                    $activeWorksheet->setCellValue('B' . $count, $c);
+                    $activeWorksheet->setCellValue('C' . $count, $exportDetail);
+                    $activeWorksheet->setCellValue('D' . $count, $j);
+
+                    $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
+                    $activeWorksheet->setCellValue('E' . $count, $stato);
+
+                    if ($stato === 'ANNULLATA') {
+                        $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
+                    }
+
+                    $idx = 0;
+                    foreach ($this->payments as $p) {
+                        if ($idx >= count($letters) - 1) {
+                            break;
+                        }
+
+                        if (isset($record[$p->name])) {
+                            $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
+                            $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
+
+                            $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
+                            $idx++;
+                            $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
+                            $idx++;
+                        } else {
+                            $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                            $idx++;
+                            $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                            $idx++;
+                        }
+                    }
+
+                    $count++;
+                    $recordsProcessed++;
+
+                    if ($recordsProcessed % 500 === 0) {
+                        Log::debug('exportWithData: Garbage collection');
+                        gc_collect_cycles();
+                    }
+                } catch (\Exception $e) {
+                    Log::error('exportWithData: Error processing record row', [
+                        'row' => $count,
+                        'causal' => $causal,
+                        'error' => $e->getMessage(),
+                        'processed_so_far' => $recordsProcessed
+                    ]);
+                    throw $e;
+                }
+            }
+
+            Log::info('exportWithData: Batch completed', [
+                'batch_index' => $batchIndex,
+                'records_in_batch' => count($recordsBatch),
+                'total_processed' => $recordsProcessed
+            ]);
+
+            unset($recordsBatch);
+            gc_collect_cycles();
+        }
+
+        Log::info('exportWithData: Adding totals row');
+        $count++;
+        $idx = 0;
+
+        $activeWorksheet->setCellValue('A' . $count, 'Totale');
+        $activeWorksheet->setCellValue('B' . $count, '');
+        $activeWorksheet->setCellValue('C' . $count, '');
+        $activeWorksheet->setCellValue('D' . $count, '');
+        $activeWorksheet->setCellValue('E' . $count, '');
+
+        foreach ($this->payments as $p) {
+            if ($idx >= count($letters) - 1) {
+                break;
+            }
+
+            if (isset($exportTotals[$p->name])) {
+                if ($p->type == 'ALL') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
+                    $idx++;
+                } elseif ($p->type == 'IN') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                    $idx++;
+                } elseif ($p->type == 'OUT') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
+                    $idx++;
+                }
+            } else {
+                if ($p->type == 'ALL') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
+                    $idx++;
+                } elseif ($p->type == 'IN') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                    $idx++;
+                } elseif ($p->type == 'OUT') {
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "");
+                    $idx++;
+                    $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
+                    $idx++;
+                }
+            }
+        }
+
+        Log::info('exportWithData: Applying final styles');
+        $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
+
+        Log::info('exportWithData: Setting column dimensions');
+        $activeWorksheet->getColumnDimension('A')->setWidth(20);
+        $activeWorksheet->getColumnDimension('B')->setWidth(40);
+        $activeWorksheet->getColumnDimension('C')->setWidth(40);
+        $activeWorksheet->getColumnDimension('D')->setWidth(40);
+        $activeWorksheet->getColumnDimension('E')->setWidth(20);
+        foreach ($letters as $l) {
+            $activeWorksheet->getColumnDimension($l)->setWidth(20);
+        }
+
+        $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
+        Log::info('exportWithData: Preparing to save file', [
+            'filename' => $filename,
+            'total_processing_time' => microtime(true) - $startTime,
+            'memory_before_save' => memory_get_usage(true)
+        ]);
+
+        try {
+            $currentClient = session('currentClient', 'default');
+            $tempPath = sys_get_temp_dir() . '/' . $filename;
+
+            Log::info('exportWithData: Creating Excel writer');
+            $writer = new Xlsx($spreadsheet);
+
+            Log::info('exportWithData: Saving to temp path', ['temp_path' => $tempPath]);
+            $writerStart = microtime(true);
+            $writer->save($tempPath);
+            $writerTime = microtime(true) - $writerStart;
+
+            Log::info('exportWithData: File saved to temp', [
+                'writer_time' => $writerTime,
+                'file_size' => file_exists($tempPath) ? filesize($tempPath) : 'unknown',
+                'memory_after_save' => memory_get_usage(true)
+            ]);
+
+            unset($spreadsheet, $activeWorksheet, $writer);
+            gc_collect_cycles();
+
+            Log::info('exportWithData: Uploading to S3');
+            $disk = Storage::disk('s3');
+            $s3Path = $currentClient . '/prima_nota/' . $filename;
+
+            $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
+            if (!$disk->exists($primaNotaFolderPath)) {
+                $disk->put($primaNotaFolderPath, '');
+                Log::info("Created prima_nota folder for client: {$currentClient}");
+            }
+
+            $uploadStart = microtime(true);
+            $fileContent = file_get_contents($tempPath);
+            $uploaded = $disk->put($s3Path, $fileContent, 'private');
+            $uploadTime = microtime(true) - $uploadStart;
+
+            if (!$uploaded) {
+                throw new \Exception('Failed to upload file to Wasabi S3');
+            }
+
+            Log::info("Export completed successfully", [
+                'client' => $currentClient,
+                'path' => $s3Path,
+                'file_size' => filesize($tempPath),
+                'records_processed' => $recordsProcessed,
+                'upload_time' => $uploadTime,
+                'total_time' => microtime(true) - $startTime,
+                'memory_peak' => memory_get_peak_usage(true)
+            ]);
+
+            if (file_exists($tempPath)) {
+                unlink($tempPath);
+            }
+
+            $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
+            return redirect($downloadUrl);
+        } catch (\Exception $e) {
+            Log::error('Export S3 error - falling back to local', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString(),
+                'client' => session('currentClient', 'unknown'),
+                'filename' => $filename,
+                'records_processed' => $recordsProcessed ?? 0,
+                'time_elapsed' => microtime(true) - $startTime
+            ]);
+
+            // Fallback logic remains the same...
+            $currentClient = session('currentClient', 'default');
+            $clientFolder = storage_path('app/prima_nota/' . $currentClient);
+
+            if (!is_dir($clientFolder)) {
+                mkdir($clientFolder, 0755, true);
+                Log::info("Created local client prima_nota folder: {$clientFolder}");
+            }
+
+            $localPath = $clientFolder . '/' . $filename;
+
+            if (isset($tempPath) && file_exists($tempPath)) {
+                rename($tempPath, $localPath);
+            } else {
+                $writer = new Xlsx($spreadsheet);
+                $writer->save($localPath);
+                unset($spreadsheet, $activeWorksheet, $writer);
+            }
+
+            gc_collect_cycles();
+
+            Log::warning("Export saved locally due to S3 error", [
+                'client' => $currentClient,
+                'local_path' => $localPath,
+                'error' => $e->getMessage()
+            ]);
+
+            session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
+            return response()->download($localPath)->deleteFileAfterSend();
+        }
+    }
+
+    private function getPreferredEmail()
+    {
+        // Try multiple sources in order of preference
+        $email = auth()->user()->email ?? null;
+
+        if (empty($email)) {
+            $email = session('user_email', null);
+        }
+
+        if (empty($email)) {
+            $member = \App\Models\Member::where('user_id', auth()->id())->first();
+            $email = $member ? $member->email : null;
+        }
+
+        if (empty($email)) {
+            // Get from user input or company default
+            $email = config('mail.default_recipient', '');
+        }
+
+        return $email;
+    }
+}

+ 31 - 0
app/Http/Middleware/HstsMiddleware.php

@@ -0,0 +1,31 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Http\Request;
+
+class HstsMiddleware
+{
+    /**
+     * Handle an incoming request.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
+     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
+     */
+    public function handle(Request $request, Closure $next)
+    {
+        $response = $next($request);
+
+        // Applica l’header HSTS solo se la richiesta è HTTPS
+        if ($request->isSecure()) {
+            $response->headers->set(
+                'Strict-Transport-Security',
+                'max-age=31536000; includeSubDomains'
+            );
+        }
+
+        return $response;
+    }
+}

+ 15 - 0
app/Models/Bank.php

@@ -4,14 +4,17 @@ namespace App\Models;
 
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\SoftDeletes;
 
 class Bank extends Model
 {
     use HasFactory;
+    use SoftDeletes;
 
     protected $fillable = [
         'name',
         'enabled',
+        'visibility'
     ];
 
     public function canDelete()
@@ -19,4 +22,16 @@ class Bank extends Model
         return \App\Models\PaymentMethod::where('bank_id', $this->id)->count() == 0;
     }
 
+    public function getVisibility()
+    {
+        $ret = '';
+        if ($this->visibility == 'IN')
+            $ret = "Solo in entrata";
+        if ($this->visibility == 'OUT')
+            $ret = "Solo in uscita";
+        if ($this->visibility == 'ALL')
+            $ret = "Entrambi";
+        return $ret;
+    }
+
 }

+ 38 - 0
app/Models/Calendar.php

@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+class Calendar extends Model
+{
+    use HasFactory;
+
+    protected $fillable = [
+        'course_id',
+        'court_id',
+        'instructor_id',
+        'from',
+        'to',
+        'note',
+        'motivation_id',
+        'status',
+        'course_type_id',
+        'course_duration_id',
+        'course_frequency_id',
+        'course_level_id',
+        'manual',
+        'motivation_manual_id'
+    ];
+
+    public function course()
+    {
+        return $this->belongsTo(\App\Models\Course::class);
+    }
+
+    public function motivation()
+    {
+        return $this->belongsTo(\App\Models\Motivation::class);
+    }
+}

+ 16 - 0
app/Models/Court.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+class Court extends Model
+{
+    use HasFactory;
+
+    protected $fillable = [
+        'name',
+        'enabled'
+    ];
+}

+ 17 - 0
app/Models/Motivation.php

@@ -0,0 +1,17 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+class Motivation extends Model
+{
+    use HasFactory;
+
+    protected $fillable = [
+        'name',
+        'enabled',
+        'type'
+    ];
+}

+ 52 - 0
app/Models/Presence.php

@@ -0,0 +1,52 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+class Presence extends Model
+{
+    use HasFactory;
+
+    protected $fillable = [
+        'member_id',
+        'calendar_id',
+        'member_course_id',
+        'user_id',
+        'motivation_id',
+        'court_id',
+        'instructor_id',
+        'notes',
+    ];
+
+    public function member()
+    {
+        return $this->belongsTo(\App\Models\Member::class);
+    }
+
+    public function calendar()
+    {
+        return $this->belongsTo(\App\Models\Calendar::class);
+    }
+
+    public function motivation()
+    {
+        return $this->belongsTo(\App\Models\Motivation::class);
+    }
+
+    public function user()
+    {
+        return $this->belongsTo(\App\Models\User::class, 'user_id');
+    }
+
+    public function instructor()
+    {
+        return $this->belongsTo(\App\Models\User::class, 'instructor_id');
+    }
+
+    public function court()
+    {
+        return $this->belongsTo(\App\Models\Court::class);
+    }
+}

+ 2 - 0
app/Models/Record.php

@@ -14,6 +14,8 @@ class Record extends Model
         'supplier_id',
         // 'causal_id',
         'payment_method_id',
+        'destination_id',
+        'origin_id',
         'date',
         'data_pagamento',
         //'month',

+ 2 - 1
database/migrations/2025_06_06_153500_create_courts_table.php → database/migrations/2025_11_14_115900_create_courts_table.php

@@ -3,8 +3,9 @@
 use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
 
-return new class extends Migration
+return new class extends TenantMigration
 {
     /**
      * Run the migrations.

+ 3 - 2
database/migrations/2025_06_06_153700_create_calendars_table.php → database/migrations/2025_11_14_120000_create_calendars_table.php

@@ -3,8 +3,9 @@
 use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
 
-return new class extends Migration
+return new class extends TenantMigration
 {
     /**
      * Run the migrations.
@@ -18,7 +19,7 @@ return new class extends Migration
             $table->unsignedBigInteger('course_id')->nullable();
             $table->foreign('course_id')->nullable()->references('id')->on('courses')->onUpdate('cascade')->onDelete('cascade');
             $table->unsignedBigInteger('court_id')->nullable();
-            $table->foreign('court_id')->nullable()->references('id')->on('courtes')->onUpdate('cascade')->onDelete('cascade');
+            $table->foreign('court_id')->nullable()->references('id')->on('courts')->onUpdate('cascade')->onDelete('cascade');
             $table->unsignedBigInteger('instructor_id')->nullable();
             $table->foreign('instructor_id')->nullable()->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
             $table->datetime('date')->nullable();

+ 2 - 1
database/migrations/2025_06_06_154000_create_presences_table.php → database/migrations/2025_11_14_120100_create_presences_table.php

@@ -3,8 +3,9 @@
 use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
 
-return new class extends Migration
+return new class extends TenantMigration
 {
     /**
      * Run the migrations.

+ 34 - 0
database/migrations/2025_11_14_120101_add_field_user_id_to_presences_table.php

@@ -0,0 +1,34 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('presences', function (Blueprint $table) {
+            $table->unsignedBigInteger('user_id')->nullable();
+            $table->foreign('user_id')->nullable()->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('presences', function (Blueprint $table) {
+            $table->dropColumn('user_id');
+        });
+    }
+};

+ 35 - 0
database/migrations/2025_11_14_120102_create_motivations_table.php

@@ -0,0 +1,35 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::create('motivations', function (Blueprint $table) {
+            $table->id();
+            $table->string('name');
+            $table->integer('enabled')->default(1);
+            $table->softDeletes();
+            $table->timestamps();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::dropIfExists('motivations');
+    }
+};

+ 36 - 0
database/migrations/2025_11_14_120103_add_fields_to_calendars_table.php

@@ -0,0 +1,36 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('calendars', function (Blueprint $table) {
+            $table->unsignedBigInteger('motivation_id')->nullable();
+            $table->foreign('motivation_id')->nullable()->references('id')->on('motivations')->onUpdate('cascade')->onDelete('cascade');
+            $table->integer('status');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('calendars', function (Blueprint $table) {
+            $table->dropColumn('motivation_id');
+            $table->dropColumn('status');
+        });
+    }
+};

+ 33 - 0
database/migrations/2025_11_14_120104_add_color_to_courses_table.php

@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('courses', function (Blueprint $table) {
+            $table->string('color')->nullable();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('courses', function (Blueprint $table) {
+            $table->dropColumn('color');
+        });
+    }
+};

+ 33 - 0
database/migrations/2025_11_14_120105_add_status_to_presences_table.php

@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('presences', function (Blueprint $table) {
+            $table->integer('status');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('presences', function (Blueprint $table) {
+            $table->dropColumn('status');
+        });
+    }
+};

+ 46 - 0
database/migrations/2025_11_14_120106_add_more_fields_to_calendars_table.php

@@ -0,0 +1,46 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('calendars', function (Blueprint $table) {
+            $table->string('name')->nullable();
+            $table->unsignedBigInteger('course_type_id')->nullable();
+            $table->foreign('course_type_id')->nullable()->references('id')->on('course_types')->onUpdate('cascade')->onDelete('cascade');
+            $table->unsignedBigInteger('course_duration_id')->nullable();
+            $table->foreign('course_duration_id')->nullable()->references('id')->on('course_durations')->onUpdate('cascade')->onDelete('cascade');
+            $table->unsignedBigInteger('course_frequency_id')->nullable();
+            $table->foreign('course_frequency_id')->nullable()->references('id')->on('course_frequencies')->onUpdate('cascade')->onDelete('cascade');
+            $table->unsignedBigInteger('course_level_id')->nullable();
+            $table->foreign('course_level_id')->nullable()->references('id')->on('course_levels')->onUpdate('cascade')->onDelete('cascade');
+            
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('calendars', function (Blueprint $table) {
+            $table->dropColumn('name');
+            $table->dropColumn('course_type_id');
+            $table->dropColumn('course_duration_id');
+            $table->dropColumn('course_frequency_id');
+            $table->dropColumn('course_level_id');
+        });
+    }
+};

+ 34 - 0
database/migrations/2025_11_14_120107_add_motivation_id_to_presences_table.php

@@ -0,0 +1,34 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('presences', function (Blueprint $table) {
+            $table->unsignedBigInteger('motivation_id')->nullable();
+            $table->foreign('motivation_id')->nullable()->references('id')->on('motivations')->onUpdate('cascade')->onDelete('cascade');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('presences', function (Blueprint $table) {
+            $table->dropColumn('motivation_id');
+        });
+    }
+};

+ 33 - 0
database/migrations/2025_11_14_120108_add_type_to_motivations_table.php

@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('motivations', function (Blueprint $table) {
+            $table->string('type', 10)->nullable();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('motivations', function (Blueprint $table) {
+            $table->dropColumn('type');
+        });
+    }
+};

+ 33 - 0
database/migrations/2025_11_14_120109_add_manual_to_calendars_table.php

@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('calendars', function (Blueprint $table) {
+            $table->boolean('manual')->nullable();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('calendars', function (Blueprint $table) {
+            $table->dropColumn('manual');
+        });
+    }
+};

+ 34 - 0
database/migrations/2025_11_14_120110_add_motivation_id_to_calendars_table.php

@@ -0,0 +1,34 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+        /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('calendars', function (Blueprint $table) {
+            $table->unsignedBigInteger('motivation_manual_id')->nullable();
+            $table->foreign('motivation_manual_id')->nullable()->references('id')->on('motivations')->onUpdate('cascade')->onDelete('cascade');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('calendars', function (Blueprint $table) {
+            $table->dropColumn('motivation_manual_id');
+        });
+    }
+};

+ 39 - 0
database/migrations/2025_11_14_120111_add_fields_to_presences_table.php

@@ -0,0 +1,39 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('presences', function (Blueprint $table) {
+            $table->unsignedBigInteger('court_id')->nullable();
+            $table->foreign('court_id')->nullable()->references('id')->on('courts')->onUpdate('cascade')->onDelete('cascade');
+            $table->unsignedBigInteger('instructor_id')->nullable();
+            $table->foreign('instructor_id')->nullable()->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
+            $table->string('notes')->nullable();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('presences', function (Blueprint $table) {
+            $table->dropColumn('court_id');
+            $table->dropColumn('instructor_id');
+            $table->dropColumn('notes');
+        });
+    }
+};

+ 33 - 0
database/migrations/2025_11_17_100244_add_visibility_to_banks_table.php

@@ -0,0 +1,33 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('banks', function (Blueprint $table) {
+            $table->string('visibility')->nullable();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('banks', function (Blueprint $table) {
+            $table->dropColumn('visibility');
+        });
+    }
+};

+ 37 - 0
database/migrations/2025_11_17_102344_add_more_fields_to_records_rows_table.php

@@ -0,0 +1,37 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+use App\Database\Migrations\TenantMigration;
+
+return new class extends TenantMigration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::table('records', function (Blueprint $table) {
+            $table->unsignedBigInteger('destination_id')->nullable();
+            $table->foreign('destination_id')->nullable()->references('id')->on('banks')->onUpdate('cascade')->onDelete('cascade');
+            $table->unsignedBigInteger('origin_id')->nullable();
+            $table->foreign('origin_id')->nullable()->references('id')->on('banks')->onUpdate('cascade')->onDelete('cascade');
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::table('records', function (Blueprint $table) {
+            $table->dropColumn('destination_id');
+            $table->dropColumn('origin_id');
+        });
+    }
+};

Різницю між файлами не показано, бо вона завелика
+ 8 - 0
public/assets/js/fullcalendar.js


Різницю між файлами не показано, бо вона завелика
+ 5 - 0
public/assets/js/fullcalendar_locales.js


+ 10 - 3
resources/views/layouts/app.blade.php

@@ -174,6 +174,8 @@
                 print "Gestionale";
             if (Request::is('records'))
                 print "Prima nota";
+            if (Request::is('records_old'))
+                print "Prima nota";
             if (Request::is('course_member_one'))
                 print "Corsi";
             if (Request::is('course_member_two'))
@@ -207,7 +209,7 @@
             if (Request::is('course_types'))
                 print "Corsi - Tipologie";
             if (Request::is('banks'))
-                print "Banche";
+                print "Canali finanziari";
             if (Request::is('causals'))
                 print "Causali";
             if (Request::is('vats'))
@@ -291,12 +293,12 @@
                     </div>
                     <div class="accordion-item">
                         <h2 class="accordion-header linkMenu" id="headingTwo">
-                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="{{Request::is('in') || Request::is('out') || Request::is('receipts') || Request::is('records_in_out') || Request::is('records') ? 'true' : 'false'}}" aria-controls="collapseTwo">
+                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="{{Request::is('in') || Request::is('out') || Request::is('receipts') || Request::is('records_in_out') || Request::is('records') || Request::is('records_old') ? 'true' : 'false'}}" aria-controls="collapseTwo">
                                 <i class="fas fa-signal"></i>
                                 <span>Contabilità</span>
                             </button>
                         </h2>
-                        <div id="collapseTwo" class="accordion-collapse collapse {{Request::is('in') || Request::is('out') || Request::is('receipts') || Request::is('records_in_out') || Request::is('records') ? 'show' : ''}}" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
+                        <div id="collapseTwo" class="accordion-collapse collapse {{Request::is('in') || Request::is('out') || Request::is('receipts') || Request::is('records_in_out') || Request::is('records') || Request::is('records_old') ? 'show' : ''}}" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
                             <div class="accordion-body">
                                 <ul class="nav nav-pills flex-column align-items-center align-items-sm-start w-100" id="menu-contabilita" style="margin-top:0px;">
                                     <li class="nav-item {{Request::is('in') ? "nav-item-active" : ""}}">
@@ -328,6 +330,11 @@
                                             <span class="ms-3 d-md-inline">Prima Nota</span>
                                         </a>
                                     </li>
+                                    <li class="nav-item {{Request::is('records_old') ? "nav-item-active" : ""}}">
+                                        <a href="/records_old" class="nav-link d-flex align-items-center linkMenu">
+                                            <span class="ms-3 d-md-inline">Prima Nota (OLD)</span>
+                                        </a>
+                                    </li>
                                 </ul>
                             </div>
                         </div>

+ 58 - 0
resources/views/livewire/absence_report.blade.php

@@ -0,0 +1,58 @@
+<div class="col card--ui" id="card--dashboard">
+
+    <a class="btn--ui lightGrey" href="/presence_reports"><i class="fa-solid fa-arrow-left"></i></a><br>
+
+    <header id="title--section" style="display:none !important" class="d-flex align-items-center justify-content-between">
+        <div class="title--section_name d-flex align-items-center justify-content-between">
+            <i class="ico--ui title_section utenti me-2"></i>
+            <h2 class="primary">Assenze</h2>
+        </div>
+    </header>
+
+    <br>
+
+    <div class="row">
+        <div class="col-12 mb-3">
+            <h3 class="primary">Assenze {{$year}}/{{$year+1}}</h3>
+        </div>
+        <div class="col-12">
+            <table class="report-table">
+                <thead>
+                    <tr>
+                        <td>Cognome</td>
+                        <td>Nome</td>
+                        <td>Corso</td>
+                        <td>N. assenze</td>
+                        <td>Date</td>
+                    </tr>
+                </thead>
+                <tbody>
+                    @foreach($records as $record)
+                    <tr>
+                        <td>{{$record["last_name"]}}</td>
+                        <td>{{$record["first_name"]}}</td>
+                        <td>{{$record["course"]}}</td>
+                        <td>{{$record["total"]}}</td>
+                        <td>{{$record["date"]}}</td>
+                    </tr>
+                    @endforeach
+                </tbody>
+            </table>
+        </div>
+    </div>
+</div>
+
+@push('css')
+<link href="/css/presence_report.css" rel="stylesheet" />
+@endpush
+
+@push('scripts')
+<link href="/css/datatables.css" rel="stylesheet" />
+<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
+@endpush
+
+@push('scripts')
+<script>
+    $(document).ready(function() {});
+</script>
+@endpush

+ 12 - 0
resources/views/livewire/bank.blade.php

@@ -46,6 +46,7 @@
                 <thead>
                     <tr>
                         <th scope="col">Nome</th>
+                        <th scope="col">Visibilità</th>
                         <th scope="col">Abilitato</th>
                         <th scope="col">...</th>
                     </tr>
@@ -54,6 +55,7 @@
                     @foreach($records as $record)
                         <tr>
                             <td>{{$record->name}}</td>
+                            <td>{{$record->getVisibility()}}</td>
                             <td> <span class="tablesaw-cell-content"><span class="badge tessera-badge {{$record->enabled ? 'active' : 'suspended'}}">{{$record->enabled ? 'attivo' : 'disattivo'}}</span></span></td>
                             <td>
                                 <button type="button" class="btn" wire:click="edit({{ $record->id }})" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Modifica"><i class="fa-regular fa-pen-to-square"></i></button>
@@ -118,6 +120,16 @@
                                     @enderror
                                 </div>
                             </div>
+                            <div class="col">
+                                <div class="form--item">
+                                    <label for="inputName" class="form-label">Visibilità</label>
+                                    <select class="form-control" id="visibility" wire:model="visibility">
+                                        <option value="IN">Solo in entrata</option>
+                                        <option value="OUT">Solo in uscita</option>
+                                        <option value="ALL">Entrambi</option>
+                                    </select>
+                                </div>
+                            </div>
                             <div class="col">
                                 <div class="form--item">
                                     <label for="enabled" class="form-label">Abilitato</label>

+ 342 - 0
resources/views/livewire/calendar.blade.php

@@ -0,0 +1,342 @@
+<style>
+    {!! $css_festivities !!} {
+        background: #ffff0040 !important;
+    }
+</style>
+
+<div class="col card--ui" id="card--dashboard">
+
+
+    <section id="resume-table">
+        
+        <div class="compare--chart_wrapper d-none"></div>
+
+        <div class="row">
+            <div class="col"></div>
+            <div class="col-auto text-end mt-2">
+                <div class="form--item d-flex align-items-center form--item gap-3">
+                    <label for="inputName" class="form-label mb-0">CORSO</label>
+                    <select class="form-select form-select-lg me-1" id="name_filter" onchange="reloadCalendar()">
+                        <option value="">
+                        @foreach($names as $n)
+                            <option value="{{$n}}" {{isset($_GET["name_filter"]) && $_GET["name_filter"] == $n ? 'selected' : ''}}>{{$n}}
+                        @endforeach
+                    </select>
+                </div>
+            </div>
+            <div class="col-auto mt-2">
+                <a style="cursor:pointer" href="#" data-bs-toggle="modal" data-bs-target="#calendarNewModal" class="openNewModal addData btn--ui">
+                    {{-- <i class="fa-solid fa-plus"></i> --}}
+                    Aggiungi lezione
+                </a>
+            </div>
+        </div>
+        <br>
+        <div id='calendar'></div>
+
+    </section>
+
+    <a href="#" data-bs-toggle="modal" data-bs-target="#calendarModal" class="openModal"></a>
+
+    <div  wire:ignore.self class="modal" id="calendarModal" tabindex="-1" aria-labelledby="calendarModalLabel" aria-hidden="true">
+        <div class="modal-dialog modal-dialog-centered">
+            <div class="modal-content">
+                <div class="modal-header">
+                    <h5 class="modal-title text-primary" id="calendarModalLabel">Dettaglio</h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+                </div>
+                <div class="modal-body">
+                    <div class="row align-items-center flex-nowrap">
+                        <div class="col-auto">
+                            <label for="course_subscription_id" class="form-label text-primary">Ora inizio</label>
+                            <h3 class="time mb-0 text-primary">ORA</h3>
+                        </div>
+                        <div class="col-auto">
+                            <div style="border-left: 2px solid var(--bs-primary);height: 75px;"></div>
+                        </div>
+                        <div class="col-md-8">
+                            <label class="form-label date text-primary">Martdì aaa</label>
+                            <h3 class="title mb-0">Padel</h3>
+                        </div>
+                    </div>                    
+                    <div class="row mt-2 showDelete" style="display:none">
+                        <br>
+                        <div class="col-md-12">
+                            <label for="newMotivation" class="form-label">Motivazione</label>
+                            <select class="form-select form-select-lg me-1 " id="motivation_id">
+                                <option value="">
+                                @foreach($motivations as $m)
+                                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
+                                @endforeach
+                            </select>
+                        </div>
+                    </div>                
+                </div>
+                <div class="modal-footer mt-2 justify-content-between">
+                    <button class="btn--ui lightGrey hideDelete hideDeleteButton activeCalendarButton" onclick="showDelete()">Annulla Lezione</a>
+                    <button type="button" class="btn--ui btn-primary hideDelete activeCalendarButton" onclick="goPresence()">Presenze</button>
+                    <button type="button" class="btn--ui primary showDelete" onclick="deleteCalendar()" style="display:none">Annulla lezione</button>
+
+                    <button type="button" class="btn--ui primary revertDelete" onclick="revertCalendarDeletion()" style="display:none">Ripristina lezione</button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <!--
+    Giorno e data della lezione
+    Corso, livello, tipologia, frequenza, insegnante, campo, note
+    -->
+
+    <div  wire:ignore.self class="modal" id="calendarNewModal" tabindex="-1" aria-labelledby="calendarNewModalLabel" aria-hidden="true">
+        <div class="modal-dialog modal-dialog-centered">
+            <div class="modal-content">
+                <div class="modal-header">
+                    <h5 class="modal-title text-primary" id="calendarNewModalLabel">Dettaglio</h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+                </div>
+                <div class="modal-body">
+                    <div class="row">
+                        <div class="col-md-6">
+                            <label for="date" class="form-label">Data</label>
+                            <input class="form-control" type="date" id="date" placeholder="Data">
+                        </div>
+                        <div class="col-md-6">
+                            <label for="date" class="form-label">Nome</label>
+                            <input class="form-control js-keyupTitle" type="name" id="name" placeholder="Nome">
+                        </div>
+                    </div>                    
+                    <div class="row">
+                        <div class="col-md-6">
+                            <label for="course_subscription_id" class="form-label">Ora inizio</label>
+                            <select class="form-select" id="from">
+                                <option value="">--Seleziona--
+                                @for($c=6;$c<=23;$c++)
+                                    <option value="{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:00">{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:00
+                                    <option value="{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:30">{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:30
+                                @endfor
+                            </select>
+                        </div>
+                        <div class="col-md-6">
+                            <label for="course_subscription_id" class="form-label">Ora fine</label>
+                            <select class="form-select" id="to">
+                                <option value="">--Seleziona--
+                                @for($c=6;$c<=23;$c++)
+                                    <option value="{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:00">{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:00
+                                    <option value="{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:30">{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:30
+                                @endfor
+                            </select>
+                        </div>
+                    </div>                    
+                    <div class="row">
+                        <div class="col-md-6">
+                            <label for="course_type_id" class="form-label">Corso</label>
+                            <select class="form-select form-select-lg me-1" id="course_type_id">
+                                <option value="">
+                                @foreach($course_types as $c)
+                                    <option value="{{$c["id"]}}">{{$c["name"]}}</option>
+                                @endforeach
+                            </select>
+                        </div>
+                        <div class="col-md-6">
+                            <label for="course_duration_id" class="form-label">Darata</label>
+                            <select class="form-select form-select-lg me-1" id="course_duration_id">
+                                <option value="">
+                                @foreach($course_durations as $c)
+                                    <option value="{{$c["id"]}}">{{$c["name"]}}</option>
+                                @endforeach
+                            </select>
+                            
+                        </div>
+                    </div>    
+                    <div class="row">
+                        <div class="col-md-6">
+                            <label for="course_frequency_id" class="form-label">Frequenza</label>
+                            <select class="form-select form-select-lg me-1" id="course_frequency_id">
+                                <option value="">
+                                @foreach($course_frequencies as $c)
+                                    <option value="{{$c["id"]}}">{{$c["name"]}}</option>
+                                @endforeach
+                            </select>
+                        </div>
+                        <div class="col-md-6">
+                            <label for="course_level_id" class="form-label">Livello</label>
+                            <select class="form-select form-select-lg me-1" id="course_level_id">
+                                <option value="">
+                                @foreach($course_levels as $c)
+                                    <option value="{{$c["id"]}}">{{$c["name"]}}</option>
+                                @endforeach
+                            </select>
+                            
+                        </div>
+                    </div>  
+                    {{-- <div class="row">
+                        <div class="col-md-6">
+                            <label for="course_frequency_id" class="form-label">Campo</label>
+                            <select class="form-select form-select-lg me-1" id="court_id">
+                                <option value="">
+                                @foreach($courts as $c)
+                                    <option value="{{$c["id"]}}">{{$c["name"]}}</option>
+                                @endforeach
+                            </select>
+                        </div>
+                        <div class="col-md-6">
+                            <label for="course_level_id" class="form-label">Istruttore</label>
+                            <select class="form-select form-select-lg me-1" id="instructor_id">
+                                <option value="">
+                                @foreach($instructors as $c)
+                                    <option value="{{$c["id"]}}">{{$c["name"]}}</option>
+                                @endforeach
+                            </select>
+                            
+                        </div>
+                    </div>  
+                    <div class="row">
+                        <div class="col-md-12">
+                            <label for="note" class="form-label">Note</label>
+                            <input class="form-control" type="name" id="note" placeholder="Note">                            
+                        </div>
+                    </div> --}}
+                </div>
+                <div class="modal-footer mt-2">
+                    <button class="btn--ui lightGrey" >Annulla</a>
+                    <button type="button" class="btn--ui btn-primary" onclick="createCalendar()">Salva</button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+</div>
+
+@push('scripts')
+    
+    <script src="/assets/js/fullcalendar.js"></script>
+    <script src="/assets/js/fullcalendar_locales.js"></script>
+@endpush
+
+@push('scripts')
+    <script>
+
+        var currentCalendar = 0;
+        var params = '';
+
+        function goPresence()
+        {
+            document.location.href = '/presences' + params;
+        }
+
+        function createCalendar()
+        {                        
+            
+            console.log($("#course_type_id").val());
+            @this.set('course_type_id',$("#course_type_id").val());
+            console.log($("#course_duration_id").val());
+            @this.set('course_duration_id', $("#course_duration_id").val());
+            console.log($("#course_frequency_id").val());
+            @this.set('course_frequency_id', $("#course_frequency_id").val());
+            console.log($("#course_level_id").val());
+            @this.set('course_level_id', $("#course_level_id").val());
+            console.log($("#date").val() + " " + $("#from").val() + ":00");
+            @this.set('from', $("#date").val() + " " + $("#from").val() + ":00");
+            console.log($("#date").val() + " " + $("#to").val() + ":00");
+            @this.set('to', $("#date").val() + " " + $("#to").val() + ":00");
+            console.log($("#name").val());
+            @this.set('name', $("#name").val());
+            @this.set('note', $("#note").val());
+            @this.set('court_id', $("#court_id").val());
+            @this.set('instructor_id', $("#instructor_id").val());
+            @this.createCalendar();
+        }
+
+        document.addEventListener('DOMContentLoaded', function() {
+            var calendarEl = document.getElementById('calendar');
+
+            initialView = document.body.clientWidth < 768 ? 'timeGridDay' : 'timeGridWeek';
+            var calendar = new FullCalendar.Calendar(calendarEl, {
+                initialDate: @this.lastDate ?? null,
+                initialView: initialView,
+                slotMinTime: '06:00:00',
+                headerToolbar: {
+                    // left: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth',
+                    left: 'timeGridDay,timeGridWeek,dayGridMonth',
+                    center: 'title',
+                    right: 'prevYear,prev,next,nextYear today',
+                },
+                displayEventEnd: false,
+                dateClick: function(info) {
+                    var x = info.dateStr.split("T");
+                    $("#date").val(x[0]);
+                    var y = x[1].split("+");
+                    var z = y[0].split(":");
+                    var from = z[0] + ":" + z[1];
+                    console.log(from);
+                    $("#from").val(from);
+                    $('.openNewModal').trigger('click');
+                },
+                eventClick: function(info) {
+                    var eventDate = new Date(info.event.start); 
+                    var datestring = eventDate.getFullYear() + "-" + pad(eventDate.getMonth()+1, 2) + "-" + pad(eventDate.getDate(), 2) + " " + pad(eventDate.getHours(), 2) + ":" + pad(eventDate.getMinutes(), 2) + ":00";
+                    var title = info.event.title;
+                    $(".title").html(title);
+                    if (title.includes("annullata"))
+                    {
+                        $(".activeCalendarButton").css("display", "none");
+                        $(".revertDelete").css("display", "block");
+                    }
+                    else
+                    {
+                        $(".activeCalendarButton").css("display", "block");
+                        $(".revertDelete").css("display", "none");
+                    }
+                    $(".time").html(pad(eventDate.getHours(), 2) + ":" + pad(eventDate.getMinutes(), 2));
+                    $(".date").html(eventDate.toLocaleDateString('it-IT', { weekday: 'long' }) + " " + pad(eventDate.getDate(), 2) + " " + eventDate.toLocaleDateString('it-IT', { month: 'long' }));
+                    currentCalendar = info.event.id;
+                    params = '?calendarId=' + info.event.id;// + "&date=" + datestring; 
+                    if (info.event.id > 0)
+                        $('.openModal').trigger('click');
+                },
+                locale: 'it',
+                events: @json($records),
+            });            
+            calendar.render();
+        });
+
+        $(document).ready(function() {
+
+            
+            
+        } );
+
+        function showDelete() {
+            jQuery(".hideDelete").hide();
+            jQuery(".showDelete").show();
+        }
+
+        function pad(num, size) {
+            num = num.toString();
+            while (num.length < size) num = "0" + num;
+            return num;
+        }
+
+        function deleteCalendar()
+        {
+            var motivation = jQuery("#motivation_id").val();
+            @this.cancelCalendar(currentCalendar, motivation);            
+        }
+
+        function revertCalendarDeletion()
+        {
+            @this.revertCalendarDeletion(currentCalendar);            
+        }
+
+        function reloadCalendar()
+        {
+            document.location.href = '/calendar?name_filter=' + $("#name_filter").val();
+        }
+        
+    </script>
+@endpush
+
+@push("css")
+    <link href="/css/calendar.css" rel="stylesheet" />
+@endpush

+ 19 - 0
resources/views/livewire/course.blade.php

@@ -223,6 +223,25 @@
                                 </div>
                             @endif
 
+                            <div class="col-6 mt-2">
+                                <div class="form--item">
+                                    <label for="inputName" class="form-label">Causale</label>
+                                    <livewire:causals :type="$typeIN" :idx="0" :show_hidden=0 :causal_id="$causal_id" :wire:key="0" />
+                                    @error('causal_id')
+                                        <span style="argin-top: 0.25rem; font-size: 0.875em; color: var(--bs-form-invalid-color);">{{ $message }}</span>
+                                    @enderror
+                                </div>
+                            </div>
+                            <div class="col-6 mt-2">
+                                <div class="form--item">
+                                    <label for="inputName" class="form-label">Causale iscrizione</label>
+                                    <livewire:causals :type="$typeIN" :idx="0" :show_hidden=0 :causal_id="$sub_causal_id" :wire:key="0" :emit="$setSubscriptionCausal" />
+                                    @error('sub_causal_id')
+                                        <span style="argin-top: 0.25rem; font-size: 0.875em; color: var(--bs-form-invalid-color);">{{ $message }}</span>
+                                    @enderror
+                                </div>
+                            </div>
+
                             <div class="col-6 mt-2">
                                 <div class="form--item">
                                     <label for="inputName" class="form-label">N° partecipanti</label>

+ 243 - 0
resources/views/livewire/court.blade.php

@@ -0,0 +1,243 @@
+<div class="col card--ui" id="card--dashboard">
+    @if(!$add && !$update)
+
+        <!--<button id="open-filter" onclick="pcsh1()"></button>
+        <button id="close-filter" onclick="pcsh2()"></button>-->
+
+        <a class="btn--ui lightGrey" href="/settings?type=corsi"><i class="fa-solid fa-arrow-left"></i></a><br>
+
+        <header id="title--section" style="display:none !important"  class="d-flex align-items-center justify-content-between">
+            <div class="title--section_name d-flex align-items-center justify-content-between">
+                <i class="ico--ui title_section utenti me-2"></i>
+                <h2 class="primary">Campi</h2>
+            </div>
+
+            <div class="title--section_addButton"  wire:click="add()" style="cursor: pointer;">
+                <div class="btn--ui entrata d-flex justify-items-between">
+                    <a href="#" wire:click="add()" style="color:white">Aggiungi</a>
+                </div>
+            </div>
+
+        </header>
+        <!--
+        <section id="subheader" class="d-flex align-items-center justify-content-between">
+            <form action="" class="group--action d-flex align-items-center">
+            <select class="form-select form-select-lg me-1" aria-label=".form-select-lg example">
+                <option selected>Open this select menu</option>
+                <option value="1">One</option>
+                <option value="2">Two</option>
+                <option value="3">Three</option>
+                </select>
+                <button type="submit" class="btn--ui">applica</button>
+            </form>
+
+            <form action="" class="search--form d-flex align-items-center">
+                <div class="input-group mb-3">
+                    <input type="text" class="form-control" placeholder="Cerca utente" aria-label="cerca utent" aria-describedby="button-addon2">
+                    <button class="btn--ui" type="button" id="button-addon2"><i class="ico--ui search"></i>Cerca</button>
+                </div>
+            </form>
+        </section>
+        -->
+        <section id="resume-table">
+            <div class="compare--chart_wrapper d-none"></div>
+
+            <table class="table tablesaw tableHead tablesaw-stack" id="tablesaw-350" width="100%">
+                <thead>
+                    <tr>
+                        <th scope="col">Nome</th>
+                        <th scope="col">Abilitato</th>
+                        <th scope="col">...</th>
+                    </tr>
+                </thead>
+                <tbody id="checkall-target">
+                    @foreach($records as $record)
+                        <tr>
+                            <td>{{$record->name}}</td>
+                            <td> <span class="tablesaw-cell-content"><span class="badge tessera-badge {{$record->enabled ? 'active' : 'suspended'}}">{{$record->enabled ? 'attivo' : 'disattivo'}}</span></span></td>
+                            <td>
+                                <button type="button" class="btn" wire:click="edit({{ $record->id }})" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Modifica"><i class="fa-regular fa-pen-to-square"></i></button>
+                                <button type="button" class="btn" onclick="confirm('Sei sicuro?') || event.stopImmediatePropagation()" wire:click="delete({{ $record->id }})" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="cestina"><i class="fa-regular fa-trash-can"></i></button>
+                            </td>
+                        </tr>
+                    @endforeach
+
+                </tbody>
+            </table>
+            <!--
+            <div class="paginator d-flex justify-content-center">
+                <nav aria-label="Page navigation example">
+                    <ul class="pagination">
+                        <li class="page-item">
+                        <a class="page-link" href="#" aria-label="Previous">
+                            <span aria-hidden="true"></span>
+                        </a>
+                        </li>
+                        <li class="page-item"><a class="page-link" href="#">1</a></li>
+                        <li class="page-item"><a class="page-link" href="#">2</a></li>
+                        <li class="page-item"><a class="page-link" href="#">3</a></li>
+                        <li class="page-item"><a class="page-link" href="#">3</a></li>
+
+                        <li class="page-item"><span class="more-page">...</span></li>
+
+                        <li class="page-item">
+                        <a class="page-link" href="#" aria-label="Next">
+                            <span aria-hidden="true"></span>
+                        </a>
+                        </li>
+                    </ul>
+                    </nav>
+            </div>
+            -->
+        </section>
+
+    @else
+
+        <div class="container">
+
+            <a class="btn--ui lightGrey" href="/banks"><i class="fa-solid fa-arrow-left"></i></a><br><br>
+
+            @if (session()->has('error'))
+                <div class="alert alert-danger" role="alert">
+                    {{ session()->get('error') }}
+                </div>
+            @endif
+
+            <div class="row">
+                <div class="col">
+
+                    <form action="">
+
+                        <div class="row mb-3">
+                            <div class="col">
+                                <div class="form--item">
+                                    <label for="inputName" class="form-label">Nome</label>
+                                    <input class="form-control js-keyupTitle @error('name') is-invalid @enderror" type="text" id="name" placeholder="Nome" wire:model="name">
+                                    @error('name')
+                                        <div class="invalid-feedback">{{ $message }}</div>
+                                    @enderror
+                                </div>
+                            </div>
+                            <div class="col">
+                                <div class="form--item">
+                                    <label for="enabled" class="form-label">Abilitato</label>
+                                    <input class="form-check-input form-control" style="width:22px; height:22px;" type="checkbox" id="enabled" wire:model="enabled">
+                                </div>
+                            </div>
+                        </div>
+
+                        <!-- // inline input field -->
+
+                        <div class="form--item">
+                            <button type="button" class="btn--ui lightGrey" wire:click="cancel()">Annulla</button>
+                        @if($add)
+                            <button type="submit" class="btn--ui" wire:click.prevent="store()">Salva</button>
+                        @endif
+                        @if($update)
+                            <button type="submit" class="btn--ui" wire:click.prevent="update()">Salva</button>
+                        @endif
+                        </div>
+
+                    </form>
+                </div>
+            </div>
+        </div>
+
+    @endif
+</div>
+
+@push('scripts')
+    <link href="/css/datatables.css" rel="stylesheet" />
+    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
+    <script src="/assets/js/datatables.js"></script>
+    <script src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.dataTables.js"></script>
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
+@endpush
+
+@push('scripts')
+    <script>
+
+        $(document).ready(function() {
+            loadDataTable();
+        } );
+
+        Livewire.on('load-data-table', () => {
+            loadDataTable();
+        });
+
+        function loadDataTable(){
+            if ( $.fn.DataTable.isDataTable('#tablesaw-350') ) {
+                $('#tablesaw-350').DataTable().destroy();
+            }
+            $('#tablesaw-350').DataTable({
+                thead: {
+                'th': {'background-color': 'blue'}
+                },
+                layout: {
+                    topStart : null,
+                    topEnd : null,
+                    top1A: {
+                        buttons: [
+                            {
+                                extend: 'collection',
+                                text: 'ESPORTA',
+                                buttons: [
+                                    {
+                                    extend: 'excelHtml5',
+                                        title: 'Campi',
+                                        exportOptions: {
+                                            columns: ":not(':last')"
+                                        }
+                                    },
+                                    {
+                                        extend: 'pdfHtml5',
+                                        title: 'Campi',
+                                        exportOptions: {
+                                            columns: ":not(':last')"
+                                        }
+                                    },
+                                    {
+                                        extend: 'print',
+                                        text: 'Stampa',
+                                        title: 'Campi',
+                                        exportOptions: {
+                                            columns: ":not(':last')"
+                                        }
+                                    }
+                                ],
+                                dropup: true
+                            }
+                        ]
+                    },
+                    top1B : {
+                        pageLength: {
+                            menu: [[10, 25, 50, 100, 100000], [10, 25, 50, 100, "Tutti"]]
+                        }
+                    },
+                    top1C :'search',
+                },
+                pagingType: 'numbers',
+                "language": {
+                    "url": "/assets/js/Italian.json"
+                },
+                "fnInitComplete": function (oSettings, json) {
+                    var html = '&nbsp;<a href="#" class="addData btn--ui"><i class="fa-solid fa-plus"></i></a>';
+                    $(".dt-search").append(html);
+                }
+            });
+            $('#tablesaw-350 thead tr th').addClass('col');
+            $('#tablesaw-350 thead tr th').css("background-color", "#f6f8fa");
+
+            $(document).ready(function() {
+                $(document).on("click",".addData",function() {
+                    $(".title--section_addButton").trigger("click")
+                });
+            } );
+
+        }
+
+    </script>
+@endpush
+

+ 212 - 0
resources/views/livewire/motivation.blade.php

@@ -0,0 +1,212 @@
+<div class="col card--ui" id="card--dashboard">
+    @if(!$add && !$update)
+
+        <!--<button id="open-filter" onclick="pcsh1()"></button>
+        <button id="close-filter" onclick="pcsh2()"></button>-->
+
+        <a class="btn--ui lightGrey" href="/settings?type=corsi"><i class="fa-solid fa-arrow-left"></i></a><br>
+
+        <header id="title--section" style="display:none !important"  class="d-flex align-items-center justify-content-between">
+            <div class="title--section_name d-flex align-items-center justify-content-between">
+                <i class="ico--ui title_section utenti me-2"></i>
+                <h2 class="primary">Motivazioni</h2>
+            </div>
+
+            <div class="title--section_addButton"  wire:click="add()" style="cursor: pointer;">
+                <div class="btn--ui entrata d-flex justify-items-between">
+                    <a href="#" wire:click="add()" style="color:white">Aggiungi</a>
+                </div>
+            </div>
+
+        </header>
+        
+        <section id="resume-table">
+            <div class="compare--chart_wrapper d-none"></div>
+
+            <table class="table tablesaw tableHead tablesaw-stack" id="tablesaw-350" width="100%">
+                <thead>
+                    <tr>
+                        <th scope="col">Nome</th>
+                        <th scope="col">Tipologia</th>
+                        <th scope="col">Abilitato</th>
+                        <th scope="col">...</th>
+                    </tr>
+                </thead>
+                <tbody id="checkall-target">
+                    @foreach($records as $record)
+                        <tr>
+                            <td>{{$record->name}}</td>
+                            <td>{{$record->type == 'add' ? 'Inserimento' : 'Eliminazione'}}</td>
+                            <td> <span class="tablesaw-cell-content"><span class="badge tessera-badge {{$record->enabled ? 'active' : 'suspended'}}">{{$record->enabled ? 'attivo' : 'disattivo'}}</span></span></td>
+                            <td>
+                                <button type="button" class="btn" wire:click="edit({{ $record->id }})" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="Modifica"><i class="fa-regular fa-pen-to-square"></i></button>
+                                <button type="button" class="btn" onclick="confirm('Sei sicuro?') || event.stopImmediatePropagation()" wire:click="delete({{ $record->id }})" data-bs-toggle="popover"  data-bs-trigger="hover focus" data-bs-placement="bottom" data-bs-content="cestina"><i class="fa-regular fa-trash-can"></i></button>
+                            </td>
+                        </tr>
+                    @endforeach
+
+                </tbody>
+            </table>
+          
+        </section>
+
+    @else
+
+        <div class="container">
+
+            <a class="btn--ui lightGrey" href="/banks"><i class="fa-solid fa-arrow-left"></i></a><br><br>
+
+            @if (session()->has('error'))
+                <div class="alert alert-danger" role="alert">
+                    {{ session()->get('error') }}
+                </div>
+            @endif
+
+            <div class="row">
+                <div class="col">
+
+                    <form action="">
+
+                        <div class="row mb-3">
+                            <div class="col">
+                                <div class="form--item">
+                                    <label for="inputName" class="form-label">Nome</label>
+                                    <input class="form-control js-keyupTitle @error('name') is-invalid @enderror" type="text" id="name" placeholder="Nome" wire:model="name">
+                                    @error('name')
+                                        <div class="invalid-feedback">{{ $message }}</div>
+                                    @enderror
+                                </div>
+                            </div>
+                            <div class="col">
+                                <div class="form--item">
+                                    <label for="type" class="form-label">Tipologia</label>
+                                    <select class="form-control" wire:model="type">
+                                        <option value=""></option>
+                                        <option value="add">Inserimento</option>
+                                        <option value="del">Eliminazione</option>
+                                    </select>
+                                </div>
+                            </div>
+                            <div class="col">
+                                <div class="form--item">
+                                    <label for="enabled" class="form-label">Abilitato</label>
+                                    <input class="form-check-input form-control" style="width:22px; height:22px;" type="checkbox" id="enabled" wire:model="enabled">
+                                </div>
+                            </div>
+                        </div>
+
+                        <!-- // inline input field -->
+
+                        <div class="form--item">
+                            <button type="button" class="btn--ui lightGrey" wire:click="cancel()">Annulla</button>
+                        @if($add)
+                            <button type="submit" class="btn--ui" wire:click.prevent="store()">Salva</button>
+                        @endif
+                        @if($update)
+                            <button type="submit" class="btn--ui" wire:click.prevent="update()">Salva</button>
+                        @endif
+                        </div>
+
+                    </form>
+                </div>
+            </div>
+        </div>
+
+    @endif
+</div>
+
+@push('scripts')
+    <link href="/css/datatables.css" rel="stylesheet" />
+    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
+    <script src="/assets/js/datatables.js"></script>
+    <script src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.dataTables.js"></script>
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
+@endpush
+
+@push('scripts')
+    <script>
+
+        $(document).ready(function() {
+            loadDataTable();
+        } );
+
+        Livewire.on('load-data-table', () => {
+            loadDataTable();
+        });
+
+        function loadDataTable(){
+            if ( $.fn.DataTable.isDataTable('#tablesaw-350') ) {
+                $('#tablesaw-350').DataTable().destroy();
+            }
+            $('#tablesaw-350').DataTable({
+                thead: {
+                'th': {'background-color': 'blue'}
+                },
+                layout: {
+                    topStart : null,
+                    topEnd : null,
+                    top1A: {
+                        buttons: [
+                            {
+                                extend: 'collection',
+                                text: 'ESPORTA',
+                                buttons: [
+                                    {
+                                    extend: 'excelHtml5',
+                                        title: 'Motivazioni annullamento',
+                                        exportOptions: {
+                                            columns: ":not(':last')"
+                                        }
+                                    },
+                                    {
+                                        extend: 'pdfHtml5',
+                                        title: 'Motivazioni annullamento',
+                                        exportOptions: {
+                                            columns: ":not(':last')"
+                                        }
+                                    },
+                                    {
+                                        extend: 'print',
+                                        text: 'Stampa',
+                                        title: 'Motivazioni annullamento',
+                                        exportOptions: {
+                                            columns: ":not(':last')"
+                                        }
+                                    }
+                                ],
+                                dropup: true
+                            }
+                        ]
+                    },
+                    top1B : {
+                        pageLength: {
+                            menu: [[10, 25, 50, 100, 100000], [10, 25, 50, 100, "Tutti"]]
+                        }
+                    },
+                    top1C :'search',
+                },
+                pagingType: 'numbers',
+                "language": {
+                    "url": "/assets/js/Italian.json"
+                },
+                "fnInitComplete": function (oSettings, json) {
+                    var html = '&nbsp;<a href="#" class="addData btn--ui"><i class="fa-solid fa-plus"></i></a>';
+                    $(".dt-search").append(html);
+                }
+            });
+            $('#tablesaw-350 thead tr th').addClass('col');
+            $('#tablesaw-350 thead tr th').css("background-color", "#f6f8fa");
+
+            $(document).ready(function() {
+                $(document).on("click",".addData",function() {
+                    $(".title--section_addButton").trigger("click")
+                });
+            } );
+
+        }
+
+    </script>
+@endpush
+

+ 715 - 0
resources/views/livewire/presence.blade.php

@@ -0,0 +1,715 @@
+@php
+    $last_date = explode(" ", $this->calendar->from)[0];
+@endphp
+
+<div class="col card--ui" id="card--dashboard">
+
+    <a class="btn--ui lightGrey" href="/calendar?last_date={{$last_date}}"><i class="fa-solid fa-arrow-left"></i></a><br><br>
+
+    <div class="compare--chart_wrapper d-none"></div>
+
+    <div class="row">
+        <div class="col-sm-12">
+            <div class="row">
+                <div class="col-auto">
+                    <h3 class="text-primary">{{$calendar->course ? $calendar->course->name : $calendar->name}}</h3>
+                </div>
+                <div class="col"></div>
+                <div class="col-auto text-end">
+                    <h4>{!!$this->getDateX()!!}<br>ora inizio {{date("H:i", strtotime($calendar->from))}}</h4>
+                </div>
+            </div>
+        </div>
+
+        {{-- @if($manual)
+
+        <div class="col-md-6">
+            <label for="court_id" class="form-label">Motivazione</label>
+            <select class="form-select form-select-lg me-1 " id="motivation_manual_id">
+                <option value="">
+                    @foreach($motivations_add as $m)
+                <option value="{{$m->id}}" {{$motivation_manual_id==$m->id ? 'selected' : ''}}>{{$m->name}}</option>
+                @endforeach
+            </select>
+        </div>
+
+        @else
+        <div class="col-md-6">
+            <label for="court_id" class="form-label">Campo</label>
+            <select class="form-select form-select-lg me-1 " wire:model="court_id">
+                <option value="">
+                    @foreach($courts as $c)
+                <option value="{{$c["id"]}}">{{$c["name"]}}</option>
+                @endforeach
+            </select>
+        </div>
+        <div class="col">
+            <label for="instructor_id" class="form-label">Istruttore</label>
+            <select class="form-select form-select-lg me-1 " wire:model="instructor_id">
+                <option value="">
+                    @foreach($instructors as $i)
+                <option value="{{$i["id"]}}">{{$i["name"]}}</option>
+                @endforeach
+            </select>
+        </div>
+        <div class="col-auto mt-2">
+            <br>
+            <button type="button" class="btn--ui primary" data-bs-toggle="modal" data-bs-target="#instructorModal" style="width:50px">&nbsp;<i class="fa-solid fa-plus"></i></button>
+        </div>
+
+        <div class="col-md-12 mt-3">
+            <textarea class="form-control" id="note" placeholder="Note" wire:model="note"></textarea>
+        </div>
+        @endif --}}
+
+    </div>
+
+    <div id="resume-table" class="mt-3">
+        <div class="compare--chart_wrapper d-none"></div>
+
+        <div class="row">
+            <div class="col-md-8 col-sm-6"></div>
+            <div class="col-md-4 col-sm-6 mb-3">
+                <input type="text" class="form-control" placeholder="Cerca utente" wire:model="filter">
+            </div>
+        </div>
+    </div>
+
+    <table class="table tablesaw tableHead tablesaw-stack" id="tablesaw-350" width="100%">
+        <thead>
+            <tr>
+                <th scope="col" class="annulla-lezione" style="display: none;">Annullamento</th>
+                <th scope="col">#</th>
+                <th scope="col">Cognome</th>
+                <th scope="col">Nome</th>
+                <th scope="col">Certificato</th>
+                <th scope="col">Campo</th>
+                <th scope="col">Istruttore</th>
+                <th scope="col">Presenza</th>
+                <th scope="col">Motivazione</th>
+                <th scope="col">Note</th>
+            </tr>
+        </thead>
+        <tbody id="checkall-target">
+            @php
+                $totalPresences = 0;
+            @endphp
+            @foreach($records as $idx => $record)
+            <tr>
+                <td class="annulla-lezione" style="display: none;">
+                    @if ($record["status"] != 99)
+                    <input name="annulla_lezione" class="member chkM" type="checkbox" value="{{$record["id"]}}">
+                    @endif
+                </td>
+                <td>{{$idx + 1}}</td>
+                <td>{{$record["last_name"]}}</td>
+                <td>{{$record["first_name"]}}</td>
+                <td>
+                    <span class="tablesaw-cell-content d-flex align-items-center">
+                        @php
+                        list($status, $date) = explode("|", $record["certificate"]);
+                        @endphp
+                        @if($status == 0)
+                        <i class="ico--ui check suspended me-2"></i>Scaduto
+                        @endif
+                        @if($status == 1)
+                        <i class="ico--ui check due me-2"></i>In scadenza
+                        @endif
+                        @if($status == 2)
+                        <i class="ico--ui check active me-2"></i> Scadenza
+                        @endif
+                        @if(is_null($status) || $status == '')
+                        <i class="ico--ui check due me-2"></i> Sospeso
+                        @endif
+                        {{$date}}
+                    </span>
+                </td>
+                <td>{{$record["court"]}}</td>
+                <td>{{$record["instructor"]}}{{$record["additional_instructor"] ? ", ".$record["additional_instructor"] : ""}}</td>
+                <td>
+                    @if ($record["status"] != 99)
+                        @if ($record["presence"])
+                            @if ($record["my_presence"])
+                            @if($manual)
+                                    <a onclick="removeSingle({{$record['id']}})"><i class="fas fa-trash"></i></a>
+                                @else
+                                    <input name="presence" class="member chkM" type="checkbox" value="{{$record["id"]}}" {{$record["presence"] ? 'checked' : '' }}>
+                                    @php
+                                    if ($record['presence']) {
+                                        $totalPresences ++;
+                                    }
+                                    @endphp
+                                @endif
+                            @else
+                                <span style="color:#0C6197;font-size:25px;">&#10003;</span>
+                                @php
+                                    $totalPresences++;
+                                @endphp
+                            @endif
+                        @else
+                            <input name="presence" class="member chkM" type="checkbox" value="{{$record["id"]}}" {{$record["presence"] ? 'checked' : '' }}>
+                            @php
+                            if ($record['presence']) {
+                                $totalPresences ++;
+                            }
+                            @endphp
+                        @endif
+                    @else
+                        Annullata &nbsp;&nbsp;-&nbsp;&nbsp; <a href="#" wire:click="revert({{$record["id"]}})" style="text-decoration: underline;color: #0c6197;"><small><i class="fa-solid fa-arrow-left-rotate"></i></small> Ripristina</a>
+                    @endif
+                </td>
+                <td>
+                    {{$record["motivation"]}}
+                </td>
+                <td>{{$record["notes"]}}</td>
+            </tr>
+            @endforeach
+
+            <tr>
+                <td colspan="6"><span class="fw-bold text-uppercase">Totale presenti</span></td>
+                <td><span class="fw-bold">{{$totalPresences}}</span></td>
+                <td colspan="2"></td>
+            </tr>
+        </tbody>
+    </table>
+
+
+    @if($calendar->status == 0)
+    <div class="row">
+        <div class="col">
+            <button type="button" class="btn--ui primary btSave btAdd" data-bs-toggle="modal" data-bs-target="#userModal" onclick="addUser()">Aggiungi utente</button>
+        </div>
+    </div>
+    @endif
+    <br>
+    <br>
+    <div class="row">
+        @if($calendar->status == 0)
+        <div class="col">
+            @if(!$manual)
+            <div class="col-lg-4 col-md-7 col-sm-12 showDelete" style="display:none">
+                <label for="newMotivation" class="form-label">Motivazione</label>
+                <select class="form-select form-select-lg me-1 " id="motivation_id">
+                    <option value="">
+                        @foreach($motivations as $m)
+                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
+                    @endforeach
+                </select>
+            </div>
+            <button type="button" class="btn--ui lightGrey btSave" onclick="showHideDelete()">Annulla lezione per selezionati</button>
+            {{-- <button type="button" class="btn--ui btSave" onclick="saveAndStay()">Salva presenze</button> --}}
+
+            @endif
+        </div>
+        @if(!$manual)
+        <div class="col-auto mt-2 text-end">
+            <a href="/calendar?last_date={{$last_date}}" class="btn--ui lightGrey btSave">Chiudi</a>
+            {{-- <button type="button" class="btn--ui btSave" onclick="saveAndQuit()">Salva e chiudi</button> --}}
+            <button type="button" class="btn--ui btSave" onclick="saveAndStay()">Salva presenze</button>
+        </div>
+        <div class="col-xs-12 mt-2">
+            <div class="showDelete" style="float:left;display:none;">
+                <button type="button" class="btn--ui lightGrey btSaveDelete" onclick="hideShowDelete()">Indietro</button>
+                <button type="button" class="btn--ui btSaveDelete" onclick="cancel()">Conferma</button>
+            </div>
+        </div>
+        @endif
+        @endif
+    </div>
+
+    <div class="row mt-3">
+        @if($calendar->status == 0)
+        @if(!$manual)
+        <div class="col-md-6">
+        </div>
+        @endif
+        @else
+        LEZIONE ANNULLATA ({{$calendar->motivation ? $calendar->motivation->name : ''}})
+        @endif
+    </div>
+
+    <div wire:ignore.self class="modal modal-lg fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
+        <div class="modal-dialog">
+            <div class="modal-content">
+                <div class="modal-header">
+                    <h5 class="modal-title text-primary" id="userModalLabel">Aggiungi persone al corso</h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+                </div>
+                <div class="modal-body">
+                    <h3 class="text-primary"><input type="radio" name="chkType" value="1" checked onchange="change(1)"> Utente già registrato</h3>
+                    <div class="existUser">
+                        <div class="row mt-2 ">
+                            <div class="col-md-6">
+                                <label for="member_id" class="form-label">Aggiungere una o più persone</label>
+                                <select name="member_id" class="form-select memberClass" aria-label="Seleziona una persona" multiple>
+                                    <option value="">--Seleziona--
+                                        @foreach($members as $member)
+                                    <option value="{{$member->id}}">{{$member->last_name}} {{$member->first_name}} ({{$member->fiscal_code}})
+                                        @endforeach
+                                </select>
+                            </div>
+                            <div class="col-md-6">
+                                <label for="newMotivation" class="form-label">Motivazione</label>
+                                <select class="form-select form-select-lg me-1 @error('newMemberMotivationId') is-invalid @enderror" id="newMemberMotivationId">
+                                    <option value="">
+                                        @foreach($motivations_add as $m)
+                                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
+                                    @endforeach
+                                </select>
+                            </div>
+                        </div>
+                    </div>
+                    <br>
+                    <hr>
+                    <br>
+                    <h3 class="text-primary"><input type="radio" name="chkType" value="2" onchange="change(2)"> Inserimento nuovo utente</h3>
+                    <br>
+                    <div class="newUser">
+                        @if($newMemberFiscalCodeExist)
+                        <span style="color:red">Attenzione, utente esistente</span>
+                        @endif
+                        <div class="row ">
+                            <div class="col-md-6">
+                                <label for="newMemberFirstName" class="form-label">Nome</label>
+                                <input class="form-control @error('newMemberFirstName') is-invalid @enderror" type="text" id="newMemberFirstName" placeholder="Nome">
+                            </div>
+                            <div class="col-md-6">
+                                <label for="newMemberLastName" class="form-label">Cognome</label>
+                                <input class="form-control @error('newMemberLastName') is-invalid @enderror" type="text" id="newMemberLastName" placeholder="Cognome">
+                            </div>
+                        </div>
+                        <div class="row mt-2">
+                            <div class="col-md-6">
+                                <label for="newMemberEmail" class="form-label">Email</label>
+                                <input class="form-control @error('newMemberEmail') is-invalid @enderror" type="text" id="newMemberEmail" placeholder="Email">
+                            </div>
+                            <div class="col-md-6">
+                                <label for="newMemberFiscalCode" class="form-label">Codice fiscale</label>
+                                <input class="form-control @error('newMemberFiscalCode') is-invalid @enderror" type="text" id="newMemberFiscalCode" placeholder="Codice fiscale" maxlength="16">
+                            </div>
+                        </div>
+                        <div class="row mt-2 ">
+                            <div class="col-md-6 d-flex gap-1 pt-3">
+                                <input type="checkbox" id="newMemberToComplete" wire:model="newMemberToComplete">
+                                <label for="newMemberToComplete" class="form-label">Tesserato</label>
+                            </div>
+                            <div class="col-md-6">
+                                <label for="newMotivation" class="form-label">Motivazione</label>
+                                <select class="form-select form-select-lg me-1 @error('newMemberMotivationId') is-invalid @enderror" id="newMemberMotivationIdX">
+                                    <option value="">
+                                        @foreach($motivations_add as $m)
+                                    <option value="{{$m["id"]}}">{{$m["name"]}}</option>
+                                    @endforeach
+                                </select>
+                            </div>
+                        </div>
+                    </div>
+                </div>
+                <div class="modal-footer">
+                    <button class="btn--ui lightGrey" onclick="annulla()">annulla</a>
+                        <button type="button" class="btn--ui btn-primary" onclick="createMember()">Salva</button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <div wire:ignore.self class="modal fade" id="instructorModal" tabindex="-1" aria-labelledby="instructorModalLabel" aria-hidden="true">
+        <div class="modal-dialog">
+            <div class="modal-content">
+                <div class="modal-header">
+                    <h5 class="modal-title text-primary" id="instructorModalLabel">Inserimento nuovo istruttore</h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+                </div>
+                <div class="modal-body">
+                    <div class="row">
+                        <div class="col-md-6">
+                            <label for="userName" class="form-label">Nome</label>
+                            <input class="form-control @error('userName') is-invalid @enderror" type="text" id="userName" placeholder="Nome" wire:model="userName">
+                        </div>
+                        <div class="col-md-6">
+                            <label for="userEmail" class="form-label">Email</label>
+                            <input class="form-control @error('userEmail') is-invalid @enderror" type="text" id="userEmail" placeholder="Email" wire:model="userEmail">
+                        </div>
+                    </div>
+                </div>
+                <div class="modal-footer">
+                    <button class="btn--ui lightGrey" onclick="annulla()">annulla</a>
+                        <button type="button" class="btn--ui btn-primary" wire:click.prevent="createInstructor()">Salva</button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <div wire:ignore.self class="modal fade saved-modal" id="editPresencesModal" tabindex="-1" role="dialog" aria-labelledby="editPresencesModal" aria-hidden="true">
+        <div class="modal-dialog">
+            <div class="modal-content">
+                <div class="modal-header">
+                    <h5 class="modal-title text-primary" id="instructorModalLabel">Modifica presenza</h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+                </div>
+                <div class="modal-body">
+                    <div class="row">
+                        <div class="col-md-12">
+                            <label for="save_court_id" class="form-label">Campo</label>
+                            <select id="save_court_id" class="form-select form-select-lg me-1">
+                                <option value="0">
+                                    @foreach($courts as $c)
+                                <option value="{{$c["id"]}}">{{$c["name"]}}</option>
+                                @endforeach
+                            </select>
+                        </div>
+
+                        <div class="col">
+                            <label for="save_instructor_id" class="form-label">Istruttore aggiuntivo</label>
+                            <select id="save_instructor_id" class="form-select form-select-lg me-1">
+                                <option value="0">
+                                    @foreach($instructors as $i)
+                                <option value="{{$i["id"]}}" {{\Auth::user()->id == $i["id"] ? "disabled" : ""}}>{{$i["name"]}}</option>
+                                @endforeach
+                            </select>
+                        </div>
+                        <div class="col-auto mt-2">
+                            <br>
+                            <button type="button" class="btn--ui primary" data-bs-toggle="modal" data-bs-target="#instructorModal" style="width:50px">&nbsp;<i class="fa-solid fa-plus"></i></button>
+                        </div>
+
+                        <div class="col-md-12">
+                            <label for="save_notes" class="form-label">Note</label>
+                            <textarea class="form-control" id="save_notes"></textarea>
+                        </div>
+                    </div>
+                </div>
+                <div class="modal-footer">
+                    <button class="btn--ui lightGrey" onclick="annulla()">annulla</a>
+                        <button type="button" class="btn--ui btn-primary" onclick="save()">Salva</button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <div wire:ignore.self class="modal fade saved-modal" id="savedModal" tabindex="-1" role="dialog" aria-labelledby="savedModal" aria-hidden="true">
+        <div class="modal-dialog">
+            <div class="modal-content">
+                <div class="modal-header"></div>
+                <div class="modal-body pt-4 pb-4 text-center fw-bold">Presenze salvate con successo</div>
+            </div>
+        </div>
+    </div>
+</div>
+
+@push('scripts')
+<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
+<style>
+    table.tableHead thead {
+        /* Important */
+        position: sticky;
+        z-index: 100;
+        top: 0;
+    }
+
+    .select2-container--default .select2-selection--single {
+        background-color: #E9F0F5;
+        border: 0.0625rem solid #DFE5EB;
+        font-size: 0.75rem;
+    }
+
+    .select2-selection {
+        height: 38px !important;
+    }
+
+    .select2-selection__rendered {
+        padding-top: 3px;
+    }
+
+    .select2 {
+        width: 100% !important;
+    }
+
+    .page-link.active,
+    .active>.page-link {
+        background-color: #006099 !important;
+    }
+
+    .select2-selection--multiple {
+        overflow: hidden !important;
+        height: auto !important;
+    }
+
+    .select2-container {
+        box-sizing: border-box;
+        display: inline-block;
+        margin: 0;
+        position: relative;
+        vertical-align: middle;
+    }
+
+    .select2-container .select2-selection--single {
+        box-sizing: border-box;
+        cursor: pointer;
+        display: block;
+        height: 38px;
+        user-select: none;
+        -webkit-user-select: none;
+    }
+
+    .select2-container .select2-selection--single .select2-selection__rendered {
+        display: block;
+        padding-left: 8px;
+        padding-right: 20px;
+        overflow: hidden;
+        text-overflow: ellipsis;
+        white-space: nowrap;
+    }
+
+    /* .total.primary
+        {
+            font-size:38px !important;
+        } */
+    /* .total.primary.comp
+        {
+            font-size:32px !important;
+        } */
+</style>
+<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
+<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
+@endpush
+
+@push('scripts')
+<script>
+    var type = 1;
+
+        var showAlert = false;
+        var isSaving = false;
+
+        $(document).ready(function() {
+            
+            setTimeout(() => {
+                $('.memberClass').select2({
+                    tags: false
+                });
+                /*$('.memberClass').on('change', function (e) {
+                    var data = $('.memberClass').select2("val");
+                    @this.addMember(data);
+                });                */
+            }, 100);
+
+            $(".btAdd").click(function(){
+                showAlert = true;
+            });
+
+            $(".form-select").change(function(){
+                showAlert = true;
+            });
+
+            $(".chkM").click(function(){
+                showAlert = true;
+            });
+
+        } );
+
+        Livewire.on('reload', () => {
+            setTimeout(() => {
+                $('.memberClass').select2({
+                    tags: false
+                });
+                /*$('.memberClass').on('change', function (e) {
+                    var data = $('.memberClass').select2("val");
+                    @this.addMember(data);
+                });                */
+            }, 100);
+            $(".showDelete").hide();
+            $(".btSave").show();
+        });
+
+        window.livewire.on('saved', () => {
+            $('#userModal').modal('hide');
+            $('#deleteModal').modal('hide');
+            $('#instructorModal').modal('hide');
+            $('#editPresencesModal').modal('hide');
+        });
+
+        window.livewire.on('deleteSaved', () => {
+            $('#deleteModal').modal('hide');
+        });
+
+        window.livewire.on('setSaving', () => {
+            isSaving = true;
+            showSavedAlert();
+        });
+
+        let saved_alert_timeout;
+        function showSavedAlert() {
+            $('#savedModal').modal("show");
+            clearTimeout(saved_alert_timeout);
+            saved_alert_timeout = setTimeout(() => {
+                $('#savedModal').modal("hide");
+            }, 3000);
+        }
+
+        let stay = false;
+        function saveAndQuit()
+        {
+            stay = false;
+
+            $('#editPresencesModal').modal("show");
+        }
+
+        function saveAndStay()
+        {
+            stay = true;
+
+            $('#editPresencesModal').modal("show");
+        }
+
+        function save()
+        {   
+            let presence_ids = [];
+            $('input[name="presence"][type="checkbox"]').each(function () {
+                if ($(this).is(":checked")) 
+                {
+                    var val = $(this).val();
+                    presence_ids.push(val);
+                }
+            });
+
+            @if($manual)
+                var motivation_manual_id = $("#motivation_manual_id").val();
+                @this.set('motivation_manual_id', motivation_manual_id);
+            @endif
+
+            
+            var save_court_id = $("#save_court_id").val();
+            @this.set('save_court_id', save_court_id);
+            var save_instructor_id = $("#save_instructor_id").val();
+            @this.set('save_instructor_id', save_instructor_id);
+            var save_notes = $("#save_notes").val();
+            @this.set('save_notes', save_notes);
+
+            if (stay == true) {
+                @this.saveAndStay(presence_ids);
+            } else {
+                @this.save(presence_ids);
+            }
+            
+            $('#editPresencesModal').modal("hide");
+        }
+
+        function cancel()
+        {
+            var ids = [];
+            $('input[name="annulla_lezione"][type="checkbox"]').each(function () {
+                if ($(this).is(":checked")) 
+                {
+                    var val = $(this).val();
+                    ids.push(val);
+                }
+            });
+            var motivation_id = $("#motivation_id").val();
+            @this.cancel(ids, motivation_id);
+        }
+
+        function createMember()
+        {
+            var ids = [];
+            /*$('input[type=checkbox]').each(function () {
+                if ($(this).is(":checked")) 
+                {
+                    var val = $(this).val();
+                    ids.push(val);
+                }
+            });*/
+
+            if (type == 1)
+            {
+                var data = $('.memberClass').select2("val");
+                @this.addMember(data);
+                @this.set('newMemberMotivationId', $("#newMemberMotivationId").val());
+            }
+            else
+            {
+                @this.set('newMemberMotivationId', $("#newMemberMotivationIdX").val());
+                @this.set('newMemberFirstName', $("#newMemberFirstName").val());
+                @this.set('newMemberLastName', $("#newMemberLastName").val());
+                @this.set('newMemberEmail', $("#newMemberEmail").val());
+                @this.set('newMemberFiscalCode', $("#newMemberFiscalCode").val());
+            }
+            
+            
+            @this.createMember();
+        }
+
+        function removeSingle(id)
+        {
+            if (confirm('Sei sicuro?'))                
+                @this.removeSingle(id);
+        }
+
+        function annulla()
+        {
+            $('#userModal').modal('hide');
+            $('#deleteModal').modal('hide');
+            $('#instructorModal').modal('hide');
+            $('#editPresencesModal').modal('hide');
+        }
+
+        function togglePresenceCheckboxDisabled(disabled = false) {
+            let presence_checkboxes = document.querySelectorAll("input[name='presence'][type='checkbox']");
+            presence_checkboxes.forEach((presence_checkbox) => {
+                presence_checkbox.disabled = disabled;
+            });
+        }
+
+        function showHideDelete()
+        {
+            togglePresenceCheckboxDisabled(true);
+            $(".annulla-lezione").show();
+            $(".showDelete").show();
+            $(".btSave").hide();
+        }
+        
+        function hideShowDelete()
+        {
+            togglePresenceCheckboxDisabled(false);
+            $(".annulla-lezione").hide();
+            $(".showDelete").hide();
+            $(".btSave").show();
+        }
+
+        window.onbeforeunload = function(){
+            
+            if (showAlert && !isSaving)
+                return 'Sei sicuro';
+
+        };
+
+        function addUser()
+        {
+            $("#newMemberMotivationId").val('');
+            $("#newMemberMotivationIdX").val('');
+            $("#newMemberFirstName").val('');
+            $("#newMemberLastName").val('');
+            $("#newMemberEmail").val('');
+            $("#newMemberFiscalCode").val('');   
+            $(".existUser").show();         
+            $(".newUser").hide();
+            let radioOption = jQuery("input:radio[value=1]");
+            radioOption.prop("checked", true);
+        }
+
+        function change(val) {
+            if (val == 1) {
+                $(".existUser").css("display", "block");
+                $(".newUser").css("display", "none");
+            } else if (val == 2) {
+                $(".newUser").css("display", "block");
+                $(".existUser").css("display", "none");
+            } 
+            type = val;
+        }
+        
+</script>
+@endpush
+
+@push("css")
+<link href="/css/calendar.css" rel="stylesheet" />
+@endpush

+ 169 - 0
resources/views/livewire/presence_report.blade.php

@@ -0,0 +1,169 @@
+<div class="col card--ui" id="card--dashboard">
+
+    {{-- <a class="btn--ui lightGrey" href="/settings?type=corsi"><i class="fa-solid fa-arrow-left"></i></a><br> --}}
+
+    <header id="title--section" style="display:none !important" class="d-flex align-items-center justify-content-between">
+        <div class="title--section_name d-flex align-items-center justify-content-between">
+            <i class="ico--ui title_section utenti me-2"></i>
+            <h2 class="primary">Presenze</h2>
+        </div>
+    </header>
+
+    <br>
+
+    <div class="row">
+        <div class="col-auto d-flex gap-2">
+            <div class="datepicker--btn">
+                <a class="btn--ui btn-primary" style="cursor:pointer;" onclick="showDatePicker(this.parentElement)"><i class="far fa-calendar"></i></a></a>
+                <input type="date" wire:model='date'>
+            </div>
+            <a class="btn--ui btn-primary" style="cursor:pointer;" wire:click="today()">Oggi</a>
+        </div>
+        <div class="col d-flex justify-content-center align-items-center gap-4">
+            <a style="cursor:pointer;" wire:click="prev()">
+                <i class="fa-solid fa-chevron-left"></i>
+            </a>
+            @php
+                $date_title = \Illuminate\Support\Carbon::parse($date)->locale('it-IT')->translatedFormat("j F Y");
+            @endphp
+            <h4 class="text-uppercase m-0">{{$date_title}}</h4>
+            <a style="cursor:pointer;" wire:click="next()">
+                <i class="fa-solid fa-chevron-right"></i>
+            </a>
+        </div>
+        <div class="col-auto">
+            <a class="btn--ui btn-primary" style="cursor:pointer;" href='/absence_reports'>Alert assenze</a>
+        </div>
+    </div>
+
+    <br><br>
+
+    <div class="row justify-content-between">
+        <div class="col-lg-3 col-md-12 d-flex gap-3 align-items-center mb-3">
+            <label class="form-label fw-medium text-uppercase mb-0" for="course_id">Corso</label>
+            <select wire:model="course_name" id="course_name" class="form-select">
+                <option value=""></option>
+                @foreach($courses as $course)
+                <option value="{{$course}}">{{$course}}
+                @endforeach
+            </select>
+        </div>
+        @if(false)
+            <div class="col-auto d-flex gap-3 align-items-center mb-3">
+                <label for="from" class="form-label fw-medium text-uppercase mb-0" style="white-space:nowrap;">Ora inizio</label>
+                <select wire:model="from" class="form-select" id="from" style="width: fit-content">
+                    <option value=""></option>
+                    @for($c=6;$c<=23;$c++)
+                        <option value="{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:00:00">{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:00</option>
+                        <option value="{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:30:00">{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:30</option>
+                    @endfor
+                </select>
+            </div>
+            <div class="col-auto d-flex gap-3 align-items-center mb-3">
+                <label for="to" class="form-label fw-medium text-uppercase mb-0" style="white-space:nowrap;">Ora fine</label>
+                <select wire:model="to" class="form-select" id="to" style="width: fit-content">
+                    <option value=""></option>
+                    @for($c=6;$c<=23;$c++)
+                        <option value="{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:00:59">{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:00</option>
+                        <option value="{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:30:59">{{str_pad($c, 2, "0", STR_PAD_LEFT)}}:30</option>
+                    @endfor
+                </select>
+            </div>
+        @endif
+        <div class="col-lg-2 col-md-12 d-flex gap-3 align-items-center mb-3">
+            <label class="form-label fw-medium text-uppercase mb-0" for="court_id">Campo</label>
+            <select wire:model="court_id" id="court_id" class="form-select">
+                <option value=""></option>
+                @foreach($courts as $court)
+                <option value="{{$court->id}}">{{$court->name}}
+                @endforeach
+            </select>
+        </div>
+        <div class="col-lg-3 col-md-12 d-flex gap-3 align-items-center mb-3">
+            <label class="form-label fw-medium text-uppercase mb-0" for="instructor_id">Istruttore</label>
+            <select wire:model="instructor_id" id="instructor_id" class="form-select">
+                <option value=""></option>
+                @foreach($instructors as $instructor)
+                <option value="{{$instructor->id}}">{{$instructor->name}}
+                @endforeach
+            </select>
+        </div>
+
+        <div class="col-lg-9 col-md-12"></div>
+        <div class="col-lg-3 col-md-12 d-flex gap-3 align-items-center mt-5 mb-3">
+            <label class="form-label fw-medium text-uppercase mb-0" for="course_id">Cerca</label>
+            <input wire:model="search" type="search" class="form-control form-control-sm" id="search" />
+        </div>
+    </div>
+
+    @forelse($records as $course => $records)
+    <div class="row mb-5">
+        <div class="col-12 mb-3">
+            <h3 class="primary">{{$course}}</h3>
+        </div>
+        @foreach($records as $time => $presences)
+        <div class="col-12 mb-4">
+            <div class="row">
+                <div class="col-1 align-items-center d-flex fs-5 fw-bold justify-content-center">{{$time}}</div>
+                <div class="col-11">
+                    <table class="report-table">
+                        <thead>
+                            <tr>
+                                <td>Cognome</td>
+                                <td>Nome</td>
+                                <td>Campo</td>
+                                <td>Istruttore</td>
+                                <td>Stato</td>
+                                <td>Motivazione</td>
+                            </tr>
+                        </thead>
+                        <tbody>
+                            @foreach($presences as $presence)
+                            <tr>
+                                <td>{{$presence["last_name"]}}</td>
+                                <td>{{$presence["first_name"]}}</td>
+                                <td>{{$presence["court"]}}</td>
+                                <td>{{$presence["instructor"]}}</td>
+                                <td>{!!$presence["status"]!!}</td>
+                                <td>{{$presence["motivation"]}}</td>
+                            </tr>
+                            @endforeach
+                        </tbody>
+                    </table>
+                </div>
+            </div>
+        </div>
+        @endforeach
+    </div>
+    @empty
+    <hr>
+    <div class="row">
+        <div class="col text-center text-black-50">Nessun dato presente</div>
+    </div>
+    <hr>
+    @endforelse
+
+</div>
+
+@push('css')
+<link href="/css/presence_report.css" rel="stylesheet" />
+@endpush
+
+@push('scripts')
+<link href="/css/datatables.css" rel="stylesheet" />
+<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
+<script src="/assets/js/datatables.js"></script>
+<script src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.dataTables.js"></script>
+<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
+<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
+<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
+@endpush
+
+@push('scripts')
+<script>
+    function showDatePicker(el) {
+        let datepicker = el.querySelector("input[type='date']");
+        datepicker.showPicker();
+    }
+</script>
+@endpush

Різницю між файлами не показано, бо вона завелика
+ 726 - 170
resources/views/livewire/records.blade.php


+ 19 - 1
resources/views/livewire/records_in.blade.php

@@ -327,10 +327,11 @@
                         @else
 
                             <div class="row gx-2 mt-3">
-                                <span class="title-form d-block w-100">Metodo di pagamento</span>
+                                
 
                                 <div class="col-md-6" >
 
+                                    <span class="title-form d-block w-100">Metodo di pagamento</span>
                                     <select name="payment_method_id" class="form-select paymentClass @error('payment_method_id') is-invalid @enderror" aria-label="Seleziona un metodo di pagamento" wire:model="payment_method_id" style="width:100%"  {{$this->dataId > 0 && $deleted ? 'disabled' : ''}}>
                                         <option value="">--Seleziona--
                                         @foreach($payments as $payment)
@@ -340,6 +341,23 @@
                                     @error('payment_method_id')
                                         <div class="invalid-feedback">{{ $message }}</div>
                                     @enderror
+                                    
+                                </div>
+                            
+                                <div class="col-md-6" >
+
+                                    <span class="title-form d-block w-100">Destinazione</span>
+
+                                    <select name="destination_id" class="form-select  @error('destination_id') is-invalid @enderror" aria-label="Seleziona una destinazione" wire:model="destination_id" style="width:100%"  {{$this->dataId > 0 && $deleted ? 'disabled' : ''}}>
+                                        <option value="">--Seleziona--
+                                        @foreach($banks as $bank)
+                                            <option value="{{$bank->id}}">{{$bank->name}}
+                                        @endforeach
+                                    </select>
+                                    @error('destination_id')
+                                        <div class="invalid-feedback">{{ $message }}</div>
+                                    @enderror
+                                    
                                 </div>
                             </div>
 

+ 1229 - 0
resources/views/livewire/records_old.blade.php

@@ -0,0 +1,1229 @@
+<div class="col card--ui" id="card--dashboard">
+
+     <header id="title--section" style="display:none !important"  class="d-flex align-items-center justify-content-between">
+        <div class="title--section_name d-flex align-items-center justify-content-between">
+            <i class="ico--ui title_section utenti me-2"></i>
+            <h2 class="primary">Prima nota</h2>
+        </div>
+
+    </header>
+    <section id="subheader" class="">
+        <div class="row g-3">
+            <div class="col-md-3">
+                Utente
+                <select name="search_member_id" class="form-select filterMember" wire:model="filterMember">
+                    <option value="">--Seleziona--
+                    @foreach($members as $member)
+                        <option value="{{$member->id}}">{{$member->last_name}} {{$member->first_name}}
+                    @endforeach
+                </select>
+            </div>
+            <div class="col-md-3">
+                Causale
+                <select name="search_causal_id[]" class="form-select filterCausals me-2" multiple="multiple" wire:model="filterCausals">
+                    @foreach($causals as $causal)
+                        <option value="{{$causal["id"]}}">{!!$causal["name"]!!}
+                    @endforeach
+                </select>
+            </div>
+            <div class="col-md-3">
+                Periodo
+                <select wire:model="selectedPeriod" class="form-select" @if($isFiltering) disabled @endif style="height: 43px!important;">
+                    <option value="OGGI">Oggi</option>
+                    <option value="IERI">Ieri</option>
+                    <option value="MESE CORRENTE">Mese Corrente</option>
+                    <option value="MESE PRECEDENTE">Mese Precedente</option>
+                    <option value="ULTIMO TRIMESTRE">Ultimo Trimestre</option>
+                    <option value="ULTIMO QUADRIMESTRE">Ultimo Quadrimestre</option>
+                </select>
+            </div>
+            <div class="col-md-3">
+                <div class="prima--nota_buttons ms-auto" style="float:right; margin-top:25px;">
+                    <button class="btn--ui primary" wire:click="applyFilters" style="margin-right:5px;" @if($isFiltering) disabled @endif>
+                        @if($isFiltering)
+                            <i class="fas fa-spinner fa-spin"></i> CARICAMENTO...
+                        @else
+                            FILTRA
+                        @endif
+                    </button>
+                    <button class="btn--ui lightGrey reset reset" style="margin-left:5px;color:#10172A;" wire:click="resetFilters" @if($isFiltering) disabled @endif>RESET</button>
+                </div>
+            </div>
+        </div>
+        <div style="float:left; margin-top:10px; margin-bottom:10px;">
+            {{-- <div class="dropdown">
+            <button class="btn--ui_outline light dropdown-toggle" type="button" id="exportDropdown" data-bs-toggle="dropdown" aria-expanded="false"
+                style="color:#10172A;" @if($isFiltering) disabled @endif>
+                    ESPORTA
+                </button>
+                <ul class="dropdown-menu" aria-labelledby="exportDropdown">
+                    <li><a class="dropdown-item" href="#" wire:click="openExportModal">Excel</a></li>
+                    <li><a class="dropdown-item" href="#" id="print">Stampa</a></li>
+                </ul>
+            </div> --}}
+            <div class="dt-buttons btn-group flex-wrap">
+                <button class="btn btn-secondary buttons-excel buttons-html5" tabindex="0" type="button" wire:click="openExportModal">
+                    <span><i class="fa-solid fa-file-excel"></i></span>
+                </button>
+                {{-- <button class="btn btn-secondary buttons-excel buttons-html5" tabindex="0" type="button" wire:click="openExportModal" style="border-top-right-radius: 0 !important;border-bottom-right-radius: 0 !important;">
+                    <span><i class="fa-solid fa-file-excel"></i></span>
+                </button> --}}
+                {{-- <button class="btn btn-secondary buttons-print" tabindex="0" type="button" id="print" style="border-top-left-radius: 0 !important;border-bottom-left-radius: 0 !important;">
+                    <span><i class="fa-solid fa-print"></i></span>
+                </button> --}}
+            </div>
+        </div>
+    </section>
+
+    <section id="resume-table" class="scrollTable records-table" style="position: relative;">
+
+        @if($isFiltering)
+            <div class="loading-overlay">
+                <div class="loading-content">
+                    <i class="fas fa-spinner fa-spin fa-3x"></i>
+                    <p>Caricamento dati in corso...</p>
+                </div>
+            </div>
+        @endif
+
+        <table class="table tablesaw tableHead tablesaw-stack" id="tablesaw-350" width="100%">
+            <thead>
+                <tr>
+                    <th scope="col">Data</th>
+                    <th scope="col" style="border-left:3px solid white;">Causale</th>
+                    <th scope="col" style="border-left:3px solid white;">Dettaglio Causale</th>
+                    <th scope="col" style="border-left:3px solid white;">Stato</th>
+                    <th scope="col" style="border-left:3px solid white;">Nominativo</th>
+                    @foreach($payments as $p)
+                        <th colspan="2" scope="col" style="text-align:center; border-left:3px solid white;">{{$p->name}}</th>
+                    @endforeach
+                </tr>
+                <tr>
+                    <th scope="col"></th>
+                    <th scope="col" style="border-left:3px solid white;"></th>
+                    <th scope="col" style="border-left:3px solid white;"></th>
+                    <th scope="col" style="border-left:3px solid white;"></th>
+                    <th scope="col" style="border-left:3px solid white;"></th>
+                    @foreach($payments as $p)
+                        @if($p->type == 'ALL')
+                            <th scope="col" style="text-align:center; border-left:3px solid white;">Entrate</th>
+                            <th scope="col" style="text-align:center">Uscite</th>
+                        @elseif($p->type == 'IN')
+                            <th scope="col" style="text-align:center; border-left:3px solid white;">Entrate</th>
+                            <th scope="col" style="text-align:center;"></th>
+                        @elseif($p->type == 'OUT')
+                            <th style="border-left:3px solid white;"></th>
+                            <th scope="col" style="text-align:center;">Uscite</th>
+                        @endif
+                    @endforeach
+                </tr>
+            </thead>
+            <tbody id="checkall-target">
+                @php $count = 0; @endphp
+                @foreach($records as $causal => $record)
+                    <tr>
+                        @php
+                        $parts = explode("§", $causal);
+                        $d = $parts[0] ?? '';
+                        $c = $parts[1] ?? '';
+                        $n = $parts[2] ?? '';
+                        $det = $parts[3] ?? '';
+                        $del = $parts[4] ?? '';
+
+                        $detailParts = explode('|', $det);
+                        $isMultiple = count($detailParts) > 1;
+                        $displayDetail = $isMultiple ? 'Varie' : $det;
+                        @endphp
+                        <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{date("d/m/Y", strtotime($d))}}</td>
+                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$c}}</td>
+                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
+                            @if($isMultiple)
+                                <span class="varie-link" data-causals="{{implode('|', array_slice($detailParts, 1))}}" style="color: var(--color-blu); cursor: pointer; text-decoration: underline;">
+                                    {{$displayDetail}}
+                                </span>
+                            @else
+                                {{$displayDetail}}
+                            @endif
+                        </td>
+                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
+                            @if($del == 'DELETED')
+                                <span style='color:red'>Annullata</span>
+                            @endif
+                        </td>
+                        <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">{{$n}}</td>
+                        @foreach($payments as $p)
+                            @if(isset($record[$p->name]))
+                                <td style="text-align:right; border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
+                                    @if(isset($record[$p->name]["IN"]))
+                                        <span class="tablesaw-cell-content " style="color:green">{{formatPrice($record[$p->name]["IN"])}}</span>
+                                    @endif
+                                </td>
+                                <td style="text-align:right;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}">
+                                    @if(isset($record[$p->name]["OUT"]))
+                                        <span class="tablesaw-cell-content " style="color:red">{{formatPrice($record[$p->name]["OUT"])}}</span>
+                                    @endif
+                                </td>
+                            @else
+                                <td style="border-left:3px solid white !important;background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}"></td>
+                                <td style="background-color:{{$count % 2 == 0 ? 'white' : '#f2f4f7'}}"></td>
+                            @endif
+                        @endforeach
+                    </tr>
+                    @php $count++; @endphp
+                @endforeach
+            </tbody>
+            <tfoot>
+                <tr>
+                    <td></td>
+                    <td></td>
+                    <td></td>
+                    <td></td>
+                    <td><b>Totale</b></td>
+                    @foreach($payments as $p)
+                        @if(isset($totals[$p->name]))
+                            @if($p->type == 'ALL')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
+                            @elseif($p->type == 'IN')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>&nbsp;</b></span></td>
+
+                            @elseif($p->type == 'OUT')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>&nbsp;</b></span></td>
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
+                            @endif
+                        @else
+                            @if($p->type == 'ALL')
+
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
+                            @elseif($p->type == 'IN')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["IN"] : 0)}}</b></span></td>
+                                <td style="text-align:center"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>&nbsp;</b></span></td>
+                            @elseif($p->type == 'OUT')
+                                <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:green; font-size:18px;"><b>&nbsp;</b></span></td>
+                                <td style="text-align:center"><span class="tablesaw-cell-content primary" style="color:red; font-size:18px;"><b>{{formatPrice(isset($totals[$p->name]) ? $totals[$p->name]["OUT"] : 0)}}</b></span></td>
+
+                            @endif
+                        @endif
+                    @endforeach
+                </tr>
+                <tr style="display:none">
+                    <td></td>
+                    <td><b>Differenza</b></td>
+                    @foreach($payments as $p)
+                        @if(isset($totals[$p->name]))
+                            @php
+                            $diff = $totals[$p->name]["IN"] - $totals[$p->name]["OUT"];
+                            @endphp
+                            @if($diff < 0)
+                                <td></td>
+                            @endif
+                            <td style="text-align:right"><span class="tablesaw-cell-content primary" style="color:{{$diff > 0 ? 'green' : 'red'}}; font-size:18px;"><b>{{formatPrice($diff)}}</b></span></td>
+                            @if($diff > 0)
+                                <td></td>
+                            @endif
+                        @else
+                            <td colspan="2" style="text-align:right"><b>{{formatPrice(0)}}</b></td>
+                        @endif
+                    @endforeach
+                </tr>
+            </tfoot>
+        </table>
+        <button type="button" class="btn btn-floating btn-lg" id="btn-back-to-bottom"><i class="fas fa-arrow-down"></i></button>
+        <button type="button" class="btn btn-floating btn-lg" id="btn-back-to-top"><i class="fas fa-arrow-up"></i></button>
+    </section>
+
+    <div class="modal fade" id="causalsModal" tabindex="-1" aria-labelledby="causalsModalLabel" aria-hidden="true">
+        <div class="modal-dialog modal-lg">
+            <div class="modal-content">
+                <div class="modal-header modal-header-blu">
+                    <h5 class="modal-title" id="causalsModalLabel">
+                        <i class="me-2"></i>
+                        Dettaglio Causali
+                    </h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="CHIUDI"></button>
+                </div>
+                <div class="modal-body">
+                    <div class="row">
+                        <div class="col-12">
+                            <div class="d-flex justify-content-between align-items-center mb-3">
+                                <h6 class="mb-0">
+                                    <i class="me-2 text-primary"></i>
+                                    Causali incluse:
+                                </h6>
+                            </div>
+                            <div class="border rounded" style="max-height: 400px; overflow-y: auto;">
+                                <ul id="causalsList" class="list-group list-group-flush mb-0">
+                                    <!-- Causals will be populated here by JavaScript -->
+                                </ul>
+                            </div>
+                        </div>
+                    </div>
+                </div>
+                <div class="modal-footer" style="background-color: #FFF!important;">
+                    <button type="button" class="btn--ui lightGrey me-2" data-bs-dismiss="modal">CHIUDI</button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <div class="modal fade" id="exportModal" tabindex="-1" aria-labelledby="exportModalLabel" aria-hidden="true">
+    <div class="modal-dialog">
+        <div class="modal-content">
+            <div class="modal-header modal-header-blu">
+                <h5 class="modal-title" id="exportModalLabel">Seleziona Periodo per Export</h5>
+                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="CHIUDI"></button>
+            </div>
+            <div class="modal-body">
+                <div class="row g-3">
+                    <div class="col-md-6">
+                        <label for="exportFromDate" class="form-label">Data Inizio</label>
+                        <input type="date" class="form-control" id="exportFromDate" wire:model.defer="exportFromDate">
+                    </div>
+                    <div class="col-md-6">
+                        <label for="exportToDate" class="form-label">Data Fine</label>
+                        <input type="date" class="form-control" id="exportToDate" wire:model.defer="exportToDate">
+                    </div>
+                </div>
+
+                <div class="row mt-4">
+                    <div class="col-12">
+                        <div class="form-check export-method-check">
+                            <input class="form-check-input" type="checkbox" id="sendViaEmail" wire:model.defer="sendViaEmail">
+                            <label class="form-check-label" for="sendViaEmail">
+                                <i class="fas fa-envelope me-2"></i>Invia via Email
+                                <small class="d-block text-muted mt-1">L'export verrà elaborato in background e inviato alla tua email</small>
+                            </label>
+                        </div>
+                    </div>
+                </div>
+
+                <div class="row mt-3" style="display: none;" id="emailAddressRow">
+                    <div class="col-12">
+                        <label for="exportEmailAddress" class="form-label">
+                            <i class="fas fa-envelope me-1"></i>Indirizzo Email
+                        </label>
+                        <input type="email" class="form-control" id="exportEmailAddress"
+                               wire:model.defer="exportEmailAddress"
+                               placeholder="inserisci@email.com">
+                        <div class="invalid-feedback" id="emailValidationFeedback">
+                            Inserisci un indirizzo email valido
+                        </div>
+                        <small class="form-text text-muted">
+                            Il file Excel verrà inviato a questo indirizzo
+                        </small>
+                    </div>
+                </div>
+
+                <div class="row mt-3" style="display: none;" id="emailSubjectRow">
+                    <div class="col-12">
+                        <label for="exportEmailSubject" class="form-label">
+                            <i class="fas fa-tag me-1"></i>Oggetto Email
+                        </label>
+                        <input type="text" class="form-control" id="exportEmailSubject"
+                               wire:model.defer="exportEmailSubject"
+                               placeholder="Prima Nota - Export">
+                        <small class="form-text text-muted">
+                            Personalizza l'oggetto dell'email
+                        </small>
+                    </div>
+                </div>
+
+                <div class="row mt-3">
+                    <div class="col-12">
+                        <div class="alert alert-info d-flex align-items-start">
+                            <i class="fas fa-info-circle me-2 mt-1"></i>
+                            <div>
+                                <strong>Informazioni Export:</strong>
+                                <ul class="mb-0 mt-1">
+                                    <li>L'export includerà tutti i record nel periodo selezionato</li>
+                                    <li>Verranno applicati i filtri attualmente attivi</li>
+                                    <li id="emailProcessingInfo" style="display: none;">L'elaborazione avverrà in background, potrai continuare a usare l'applicazione</li>
+                                </ul>
+                            </div>
+                        </div>
+                    </div>
+                </div>
+            </div>
+            <div class="modal-footer" style="background-color: #FFF!important;">
+                <button type="button" class="btn--ui lightGrey me-2" data-bs-dismiss="modal">ANNULLA</button>
+                <button type="button" class="btn--ui primary" onclick="handleExportClick()" id="exportButton">
+                    <span id="loadingState" style="display: none;">
+                        <div class="spinner-border spinner-border-sm me-2" role="status">
+                            <span class="visually-hidden">Loading...</span>
+                        </div>
+                        ELABORAZIONE...
+                    </span>
+                    <span id="normalState">
+                        <i class="fas fa-download me-1"></i>
+                        ESPORTA
+                    </span>
+                </button>
+            </div>
+        </div>
+    </div>
+</div>
+
+<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 11000;">
+    <!-- Toasts will be dynamically added here -->
+</div>
+</div>
+
+@push('scripts')
+    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
+@endpush
+
+@push('scripts')
+    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
+    <style>
+        .loading-overlay {
+            position: absolute;
+            top: 0;
+            left: 0;
+            right: 0;
+            bottom: 0;
+            background-color: rgba(255, 255, 255, 0.9);
+            display: flex;
+            justify-content: center;
+            align-items: center;
+            z-index: 1000;
+            border-radius: 4px;
+        }
+
+        .loading-content {
+            text-align: center;
+            color: var(--color-blu);
+        }
+
+        .loading-content i {
+            margin-bottom: 15px;
+            color: var(--color-blu);
+        }
+
+        .loading-content p {
+            margin: 0;
+            font-size: 16px;
+            font-weight: 500;
+            color: #10172A;
+        }
+
+        .modal {
+            z-index: 9999 !important;
+        }
+
+        .modal-backdrop {
+            z-index: 9998 !important;
+            background-color: rgba(0, 0, 0, 0.6) !important;
+        }
+
+        .modal-content {
+            border-radius: 8px;
+            border: none;
+            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
+            z-index: 10000 !important;
+        }
+
+        .modal-header {
+            color: white;
+            border-bottom: none;
+            border-radius: 8px 8px 0 0;
+        }
+
+        .modal-header .btn-close {
+            filter: invert(1);
+        }
+
+        .modal-title {
+            font-weight: 600;
+        }
+
+        .varie-link:hover {
+            color: #084c6b !important;
+            text-decoration: underline !important;
+        }
+
+        #btn-back-to-top {
+            background-color: var(--color-blu);
+            color: white;
+            position: fixed;
+            display: none;
+        }
+
+        #btn-back-to-bottom {
+            background-color: var(--color-blu);
+            color: white;
+            position: fixed;
+            z-index: 9999;
+            display: none;
+        }
+
+        button[disabled] {
+            opacity: 0.7;
+            cursor: not-allowed;
+        }
+
+        .btn--ui .fa-spinner {
+            margin-right: 5px;
+        }
+
+        .scrollTable {
+            margin-left: 0px;
+            margin-right: 0px;
+            padding: 15px;
+            overflow-x: auto;
+            overflow-y: auto;
+            white-space: nowrap;
+            border: 1px solid #ddd;
+        }
+
+        ::-webkit-scrollbar-thumb {
+            background: #e4e4e4;
+            border-radius: 10px;
+        }
+
+        table thead {
+            position: sticky;
+            z-index: 100;
+            top: 0;
+        }
+
+        .select2-container--default .select2-selection--single {
+            background-color: #E9F0F5;
+            border: 0.0625rem solid #DFE5EB;
+            font-size: 0.75rem;
+            height: 38px !important;
+        }
+
+        .select2-selection__rendered {
+            padding-top: 3px;
+        }
+
+        .select2 {
+            width: 100% !important;
+        }
+
+        .select2-selection--multiple {
+            overflow: hidden !important;
+            height: auto !important;
+        }
+
+        .select2-container {
+            box-sizing: border-box;
+            display: inline-block;
+            margin: 0;
+            position: relative;
+            vertical-align: middle;
+            z-index: 999 !important;
+        }
+
+        .select2-dropdown {
+            z-index: 999 !important;
+        }
+
+        .select2-container .select2-selection--single {
+            box-sizing: border-box;
+            cursor: pointer;
+            display: block;
+            height: 38px;
+            user-select: none;
+            -webkit-user-select: none;
+        }
+
+        .select2-container .select2-selection--single .select2-selection__rendered {
+            display: block;
+            padding-left: 8px;
+            padding-right: 20px;
+            overflow: hidden;
+            text-overflow: ellipsis;
+            white-space: nowrap;
+        }
+
+        button#exportDropdown.btn--ui_outline.light {
+            font-weight: normal !important;
+        }
+
+        .btn--ui_outline.light.dropdown-toggle:active,
+        .btn--ui_outline.light.dropdown-toggle:focus,
+        .btn--ui_outline.light.dropdown-toggle.show {
+            background-color: transparent !important;
+            color: #10172A !important;
+            box-shadow: none !important;
+        }
+
+        .btn--ui_outline.light.dropdown-toggle:hover {
+            background-color: transparent !important;
+            color: #10172A !important;
+        }
+
+        .form-select {
+            height: 38px !important;
+        }
+
+        .form-control {
+            height: 43px !important;
+        }
+
+        #exportModal .modal-body {
+            padding: 1.5rem;
+        }
+
+        #exportModal .form-label {
+            font-weight: 600;
+            color: #10172A;
+            margin-bottom: 0.5rem;
+        }
+
+        #exportModal .text-muted {
+            font-size: 0.875rem;
+        }
+
+        .btn--ui[disabled] .fa-spinner {
+            margin-right: 0.5rem;
+        }
+
+        body.modal-open {
+            overflow: hidden;
+        }
+
+        .modal-dialog {
+            z-index: 10001 !important;
+            margin: 1.75rem auto;
+        }
+
+        .list-group-item {
+            border-left: none;
+            border-right: none;
+            border-top: 1px solid #dee2e6;
+            padding: 12px 15px;
+        }
+
+        .list-group-item:first-child {
+            border-top: none;
+        }
+
+        .list-group-item:last-child {
+            border-bottom: none;
+        }
+
+        @media (max-width: 768px) {
+            .col-md-2, .col-md-3, .col-md-4 {
+                margin-bottom: 10px;
+            }
+
+            .prima--nota_buttons {
+                float: none !important;
+                margin-top: 10px !important;
+                text-align: center;
+            }
+        }
+
+        .export-method-check {
+            padding: 16px 16px 16px 50px;
+            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
+            border-radius: 8px;
+            border: 2px solid #e9ecef;
+            transition: all 0.3s ease;
+            cursor: pointer;
+            position: relative;
+        }
+
+        .export-method-check:hover {
+            border-color: var(--color-blu);
+            background: linear-gradient(135deg, #e8f4f8 0%, #d1ecf1 100%);
+        }
+
+        .export-method-check .form-check-input {
+            position: absolute;
+            left: 16px;
+            top: 50%;
+            transform: translateY(-50%);
+            margin: 0;
+            width: 20px;
+            height: 20px;
+            background-color: #fff;
+            border: 2px solid #dee2e6;
+            border-radius: 4px;
+            cursor: pointer;
+        }
+
+        .export-method-check .form-check-input:checked {
+            background-color: var(--color-blu);
+            border-color: var(--color-blu);
+        }
+
+        .export-method-check .form-check-input:checked ~ .form-check-label {
+            color: var(--color-blu);
+            font-weight: 600;
+        }
+
+        .export-method-check .form-check-label {
+            font-weight: 500;
+            color: #495057;
+            cursor: pointer;
+            margin-left: 0;
+            display: block;
+        }
+
+        .form-check-input:focus {
+            border-color: var(--color-blu);
+            outline: 0;
+            box-shadow: 0 0 0 0.2rem rgba(12, 97, 151, 0.25);
+        }
+        #emailAddressRow.show, #emailSubjectRow.show {
+            display: block !important;
+            animation: slideDown 0.3s ease-out;
+        }
+
+        @keyframes slideDown {
+            from {
+                opacity: 0;
+                transform: translateY(-10px);
+            }
+            to {
+                opacity: 1;
+                transform: translateY(0);
+            }
+        }
+
+        .invalid-feedback {
+            display: none;
+        }
+
+        .is-invalid ~ .invalid-feedback {
+            display: block;
+        }
+
+        .alert-info {
+            background-color: rgba(12, 97, 151, 0.1);
+            border-color: rgba(12, 97, 151, 0.2);
+            color: var(--color-blu);
+        }
+
+        .spinner-border-sm {
+            width: 1rem;
+            height: 1rem;
+        }
+
+        .toast {
+            min-width: 300px;
+        }
+
+        .toast-body {
+            font-weight: 500;
+        }
+
+        .btn--ui:disabled {
+            opacity: 0.7;
+            cursor: not-allowed;
+        }
+
+        .list-group-item {
+            border-left: none;
+            border-right: none;
+            border-top: 1px solid #dee2e6;
+            padding: 12px 15px;
+        }
+
+        .list-group-item:first-child {
+            border-top: none;
+        }
+
+        .list-group-item:last-child {
+            border-bottom: none;
+        }
+
+        /* Enhanced styles for the causal modal with amounts */
+        .list-group-item.d-flex {
+            display: flex !important;
+            justify-content: space-between !important;
+            align-items: center !important;
+        }
+
+        .list-group-item .badge {
+            font-size: 0.875rem;
+            font-weight: 600;
+        }
+
+        .list-group-item:hover {
+            background-color: rgba(12, 97, 151, 0.05);
+            transition: background-color 0.2s ease;
+        }
+
+        #causalsModal .modal-body {
+            padding: 1rem 0;
+        }
+
+    </style>
+    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
+    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
+    <script src="/assets/js/aCollapTable.js"></script>
+@endpush
+
+@push('scripts')
+    <script>
+        function closeSelect2Dropdowns() {
+            $('.filterCausals').each(function() {
+                if ($(this).hasClass('select2-hidden-accessible')) {
+                    $(this).select2('close');
+                }
+            });
+            $('.filterMember').each(function() {
+                if ($(this).hasClass('select2-hidden-accessible')) {
+                    $(this).select2('close');
+                }
+            });
+        }
+
+        function load() {
+            $(document).ready(function(){
+                $(document).on("keypress", $('.filterCausals'), function (e) {
+                    setTimeout(() => {
+                        $(".select2-results__option").each(function(){
+                            var txt = $(this).html();
+                            var count = (txt.match(/-/g) || []).length;
+                            $(this).addClass('paddingLeftSelect' + count);
+                        });
+                    }, 100);
+                });
+
+                if (!$('.filterCausals').hasClass('select2-hidden-accessible')) {
+                    $('.filterCausals').select2({
+                        "language": {"noResults": function(){return "Nessun risultato";}},
+                        "dropdownParent": $('body'),
+                        "width": "100%"
+                    });
+                }
+
+                $('.filterCausals').off('change.customHandler').on('change.customHandler', function (e) {
+                    var data = $('.filterCausals').select2("val");
+                    @this.set('filterCausals', data);
+                });
+
+                $('.filterCausals').off('select2:open.customHandler').on('select2:open.customHandler', function (e) {
+                    if ($('#causalsModal').hasClass('show')) {
+                        $('#causalsModal').modal('hide');
+                    }
+
+                    setTimeout(() => {
+                        $(".select2-results__option").each(function(){
+                            var txt = $(this).html();
+                            var count = (txt.match(/-/g) || []).length;
+                            $(this).addClass('paddingLeftSelect' + count);
+                        });
+                    }, 100);
+                });
+
+                if (!$('.filterMember').hasClass('select2-hidden-accessible')) {
+                    $('.filterMember').select2({
+                        "language": {"noResults": function(){return "Nessun risultato";}},
+                        "dropdownParent": $('body'),
+                        "width": "100%"
+                    });
+                }
+
+                $('.filterMember').off('change.customHandler').on('change.customHandler', function (e) {
+                    var data = $('.filterMember').select2("val");
+                    @this.set('filterMember', data);
+                });
+
+                $('.filterMember').off('select2:open.customHandler').on('select2:open.customHandler', function (e) {
+                    if ($('#causalsModal').hasClass('show')) {
+                        $('#causalsModal').modal('hide');
+                    }
+                });
+            });
+        }
+
+        function printData() {
+            var divToPrint = document.getElementById("tablesaw-350");
+            newWin = window.open("");
+            var htmlToPrint = '' +
+                '<style type="text/css">' +
+                'table {' +
+                'border-collapse:collapse;' +
+                'border:1px solid #000;' +
+                '}' +
+                'table th, table td, table tr {' +
+                'border:1px solid #000;' +
+                'padding:0.5em;' +
+                '}' +
+                '</style>';
+            htmlToPrint += divToPrint.outerHTML;
+            newWin.document.write(htmlToPrint);
+            newWin.document.close();
+            newWin.print();
+            newWin.close();
+        }
+
+        function scrollFunction() {
+            const element = document.getElementById('resume-table');
+            const mybuttonBottom = document.getElementById("btn-back-to-bottom");
+            const mybutton = document.getElementById("btn-back-to-top");
+
+            if (element.scrollTop > 20) {
+                mybutton.style.display = "block";
+                mybuttonBottom.style.display = "block";
+            } else {
+                mybutton.style.display = "none";
+                mybuttonBottom.style.display = "none";
+            }
+        }
+
+        function backToTop() {
+            $('#resume-table').scrollTop(0);
+        }
+
+        function backToBottom() {
+            $('#resume-table').scrollTop($('#resume-table')[0].scrollHeight);
+        }
+
+        $(document).ready(function() {
+            load();
+
+            document.querySelector("#print")?.addEventListener("click", function(){
+                printData();
+            });
+
+            const element = document.getElementById('resume-table');
+            element.onscroll = scrollFunction;
+
+            const mybuttonBottom = document.getElementById("btn-back-to-bottom");
+            const mybutton = document.getElementById("btn-back-to-top");
+
+            mybutton.addEventListener("click", backToTop);
+            mybuttonBottom.addEventListener("click", backToBottom);
+
+            $(document).on('click', '.varie-link', function(e) {
+                e.preventDefault();
+                e.stopPropagation();
+
+                closeSelect2Dropdowns();
+
+                const causalsData = $(this).data('causals');
+
+                if (causalsData) {
+                    const causals = causalsData.split('|');
+
+                    $('#causalsList').empty();
+
+                    causals.forEach(function(causal) {
+                        if (causal.trim()) {
+                            if (causal.includes(':::')) {
+                                const parts = causal.split(':::');
+                                const causalName = parts[0].trim();
+                                const amount = parts[1].trim();
+
+                                $('#causalsList').append(
+                                    '<li class="list-group-item d-flex justify-content-between align-items-center">' +
+                                    '<div>' +
+                                    '<i class="fas fa-tags me-2" style="color: var(--color-blu);"></i>' +
+                                    causalName +
+                                    '</div>' +
+                                    '<span class="badge bg-primary rounded-pill" style="background-color: var(--color-blu) !important;">' +
+                                    amount +
+                                    '</span>' +
+                                    '</li>'
+                                );
+                            } else {
+                                $('#causalsList').append(
+                                    '<li class="list-group-item">' +
+                                    '<i class="fas fa-tags me-2" style="color: var(--color-blu);"></i>' +
+                                    causal.trim() +
+                                    '</li>'
+                                );
+                            }
+                        }
+                    });
+
+                    $('#causalsModal').modal('show');
+
+                    $('#causalsModal').on('shown.bs.modal', function () {
+                        $(this).find('.btn-close').focus();
+                    });
+                }
+            });
+        });
+        Livewire.on('load-table', () => {
+            load();
+        });
+
+        Livewire.on('load-select', () => {
+            load();
+        });
+
+        Livewire.on('filters-reset', () => {
+            $('.filterMember').val('').trigger('change');
+            $('.filterCausals').val('').trigger('change');
+            load();
+        });
+
+        Livewire.on('show-export-modal', () => {
+            $('#exportModal').modal('show');
+        });
+
+        Livewire.on('hide-export-modal', () => {
+            $('#exportModal').modal('hide');
+        });
+
+        function showToast(type, message, duration = 5000) {
+            const toastContainer = document.querySelector('.toast-container');
+            if (!toastContainer) {
+                console.error('Toast container not found');
+                return;
+            }
+
+            const toastId = 'toast-' + Date.now();
+
+            const toastColors = {
+                success: 'bg-success',
+                error: 'bg-danger',
+                warning: 'bg-warning',
+                info: 'bg-info'
+            };
+
+            const toastIcons = {
+                success: 'fa-check-circle',
+                error: 'fa-exclamation-circle',
+                warning: 'fa-exclamation-triangle',
+                info: 'fa-info-circle'
+            };
+
+            const toast = document.createElement('div');
+            toast.id = toastId;
+            toast.className = `toast align-items-center text-white ${toastColors[type]} border-0`;
+            toast.setAttribute('role', 'alert');
+            toast.innerHTML = `
+                <div class="d-flex">
+                    <div class="toast-body">
+                        <i class="fas ${toastIcons[type]} me-2"></i>
+                        ${message}
+                    </div>
+                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
+                </div>
+            `;
+
+            toastContainer.appendChild(toast);
+
+            if (typeof bootstrap !== 'undefined') {
+                const bsToast = new bootstrap.Toast(toast, { delay: duration });
+                bsToast.show();
+
+                toast.addEventListener('hidden.bs.toast', function() {
+                    if (toastContainer.contains(toast)) {
+                        toastContainer.removeChild(toast);
+                    }
+                });
+
+                return bsToast;
+            } else {
+                toast.style.display = 'block';
+                setTimeout(() => {
+                    if (toastContainer.contains(toast)) {
+                        toastContainer.removeChild(toast);
+                    }
+                }, duration);
+            }
+        }
+
+        document.addEventListener('DOMContentLoaded', function() {
+            const sendViaEmailCheckbox = document.getElementById('sendViaEmail');
+            const emailAddressRow = document.getElementById('emailAddressRow');
+            const emailSubjectRow = document.getElementById('emailSubjectRow');
+            const emailProcessingInfo = document.getElementById('emailProcessingInfo');
+            const exportIcon = document.getElementById('exportIcon');
+            const exportButtonText = document.getElementById('exportButtonText');
+            const emailInput = document.getElementById('exportEmailAddress');
+
+            function toggleEmailFields() {
+                if (sendViaEmailCheckbox && sendViaEmailCheckbox.checked) {
+                    if (emailAddressRow) {
+                        emailAddressRow.style.display = 'block';
+                        emailAddressRow.classList.add('show');
+                    }
+                    if (emailSubjectRow) {
+                        emailSubjectRow.style.display = 'block';
+                        emailSubjectRow.classList.add('show');
+                    }
+                    if (emailProcessingInfo) {
+                        emailProcessingInfo.style.display = 'list-item';
+                    }
+
+                    if (exportIcon) exportIcon.className = 'fas fa-paper-plane me-1';
+                    if (exportButtonText) exportButtonText.textContent = 'INVIA EMAIL';
+                } else {
+                    if (emailAddressRow) {
+                        emailAddressRow.style.display = 'none';
+                        emailAddressRow.classList.remove('show');
+                    }
+                    if (emailSubjectRow) {
+                        emailSubjectRow.style.display = 'none';
+                        emailSubjectRow.classList.remove('show');
+                    }
+                    if (emailProcessingInfo) {
+                        emailProcessingInfo.style.display = 'none';
+                    }
+
+                    if (exportIcon) exportIcon.className = 'fas fa-download me-1';
+                    if (exportButtonText) exportButtonText.textContent = 'ESPORTA';
+                }
+            }
+
+            function validateEmail(email) {
+                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+                return emailRegex.test(email);
+            }
+
+            if (sendViaEmailCheckbox) {
+                sendViaEmailCheckbox.addEventListener('change', toggleEmailFields);
+            }
+
+            if (emailInput) {
+                emailInput.addEventListener('blur', function() {
+                    if (sendViaEmailCheckbox && sendViaEmailCheckbox.checked && this.value) {
+                        if (validateEmail(this.value)) {
+                            this.classList.remove('is-invalid');
+                            this.classList.add('is-valid');
+                        } else {
+                            this.classList.remove('is-valid');
+                            this.classList.add('is-invalid');
+                        }
+                    }
+                });
+
+                emailInput.addEventListener('input', function() {
+                    this.classList.remove('is-invalid', 'is-valid');
+                });
+            }
+
+            if (typeof $ !== 'undefined') {
+                $('#exportModal').on('shown.bs.modal', function() {
+                    toggleEmailFields();
+                });
+            }
+        });
+
+        document.addEventListener('livewire:load', function () {
+            console.log('Livewire loaded, setting up export event listeners');
+
+            Livewire.on('export-email-queued', function() {
+                console.log('Export email queued event received');
+                showToast('info',
+                    '<strong>Export avviato!</strong><br>' +
+                    'L\'elaborazione è in corso in background. Riceverai l\'email a breve.',
+                    8000
+                );
+            });
+
+            Livewire.on('export-email-sent', function() {
+                console.log('Export email sent event received');
+                showToast('success',
+                    '<strong>Email inviata!</strong><br>' +
+                    'L\'export è stato completato e inviato alla tua email.',
+                    6000
+                );
+            });
+
+            Livewire.on('export-email-error', function(message) {
+                console.log('Export email error event received:', message);
+                showToast('error',
+                    '<strong>Errore nell\'export:</strong><br>' +
+                    (message || 'Si è verificato un errore durante l\'elaborazione.'),
+                    10000
+                );
+            });
+
+            Livewire.on('show-export-modal', function() {
+                console.log('Show export modal event received');
+                if (typeof $ !== 'undefined') {
+                    $('#exportModal').modal('show');
+                }
+            });
+
+            Livewire.on('hide-export-modal', function() {
+                console.log('Hide export modal event received');
+                if (typeof $ !== 'undefined') {
+                    $('#exportModal').modal('hide');
+                }
+            });
+        });
+
+        if (typeof Livewire !== 'undefined') {
+            document.addEventListener('livewire:initialized', function () {
+                console.log('Livewire initialized, setting up export event listeners');
+
+                Livewire.on('export-email-queued', function() {
+                    showToast('info',
+                        '<strong>Export avviato!</strong><br>' +
+                        'L\'elaborazione è in corso in background. Riceverai l\'email a breve.',
+                        8000
+                    );
+                });
+
+                Livewire.on('export-email-sent', function() {
+                    showToast('success',
+                        '<strong>Email inviata!</strong><br>' +
+                        'L\'export è stato completato e inviato alla tua email.',
+                        6000
+                    );
+                });
+
+                Livewire.on('export-email-error', function(message) {
+                    showToast('error',
+                        '<strong>Errore nell\'export:</strong><br>' +
+                        (message || 'Si è verificato un errore durante l\'elaborazione.'),
+                        10000
+                    );
+                });
+
+                Livewire.on('show-export-modal', function() {
+                    if (typeof $ !== 'undefined') {
+                        $('#exportModal').modal('show');
+                    }
+                });
+
+                Livewire.on('hide-export-modal', function() {
+                    if (typeof $ !== 'undefined') {
+                        $('#exportModal').modal('hide');
+                    }
+                });
+            });
+        }
+
+        window.addEventListener('load', function() {
+            if (typeof showToast === 'function') {
+                console.log('showToast function is available globally');
+            } else {
+                console.error('showToast function is not available globally');
+            }
+        });
+
+
+        function handleExportClick() {
+            showExportLoading();
+
+            @this.call('exportWithDateRange');
+        }
+
+        function showExportLoading() {
+            document.getElementById('normalState').style.display = 'none';
+            document.getElementById('loadingState').style.display = 'inline-flex';
+            document.getElementById('exportButton').disabled = true;
+        }
+
+        function hideExportLoading() {
+            document.getElementById('normalState').style.display = 'inline-flex';
+            document.getElementById('loadingState').style.display = 'none';
+            document.getElementById('exportButton').disabled = false;
+        }
+
+        // Listen for when export is complete
+        Livewire.on('export-complete', function() {
+            hideExportLoading();
+        });
+
+        Livewire.on('hide-export-modal', function() {
+            hideExportLoading();
+        });
+    </script>
+@endpush

+ 29 - 12
resources/views/livewire/records_out.blade.php

@@ -262,20 +262,37 @@
                         </div>
 
                         <div class="row gx-2 mt-5">
-                            <span class="title-form d-block w-100">Metodo di pagamento</span>
-
-                            <div class="col-md-6">
-                                <select name="payment_method_id" class="form-select paymentClass @error('payment_method_id') is-invalid @enderror" aria-label="Seleziona un metodo di pagamento" wire:model="payment_method_id">
-                                    <option value="">--Seleziona--
-                                    @foreach($payments as $payment)
-                                        <option value="{{$payment->id}}">{{$payment->name}}
-                                    @endforeach
-                                </select>
-                                @error('payment_method_id')
-                                    <div class="invalid-feedback">{{ $message }}</div>
-                                @enderror
+                            <div class="col-6">
+                                <span class="title-form d-block w-100">Metodo di pagamento</span>
+                                <div class="col-md-12">
+                                    <span class="title-form d-block w-100">Metodo di pagamento</span>
+                                    <select name="payment_method_id" class="form-select paymentClass @error('payment_method_id') is-invalid @enderror" aria-label="Seleziona un metodo di pagamento" wire:model="payment_method_id">
+                                        <option value="">--Seleziona--
+                                        @foreach($payments as $payment)
+                                            <option value="{{$payment->id}}">{{$payment->name}}
+                                        @endforeach
+                                    </select>
+                                    @error('payment_method_id')
+                                        <div class="invalid-feedback">{{ $message }}</div>
+                                    @enderror
+                                </div>
+                            </div>
+                            <div class="col-6">
+                                <span class="title-form d-block w-100">Origine</span>
+                                <div class="col-md-12">
+                                    <select name="origin_id" class="form-select" aria-label="Seleziona un origine" wire:model="origin_id">
+                                        <option value="">--Seleziona--
+                                        @foreach($banks as $bank)
+                                            <option value="{{$bank->id}}">{{$bank->name}}
+                                        @endforeach
+                                    </select>
+                                    @error('origin_id')
+                                        <div class="invalid-feedback">{{ $message }}</div>
+                                    @enderror
+                                </div>
                             </div>
                         </div>
+                            
                         <div class="row gx-2 mt-5">
                             <span class="title-form d-block w-100">
                                 Allegato

+ 1 - 1
resources/views/livewire/settings.blade.php

@@ -96,7 +96,7 @@
             <div id="contabilita">
                 <a href="/banks">
                     <div class="row">
-                        <div class="col-md-11 p-2"><h5>Banche</h5></div>
+                        <div class="col-md-11 p-2"><h5>Canali finanziari</h5></div>
                         <div class="col-md-1 p-2"><i class="fa-solid fa-chevron-right"></i></div>
                     </div>
                 </a>

+ 5 - 0
routes/web.php

@@ -114,6 +114,7 @@ Route::group(['middleware' => 'tenant'], function () {
     Route::get('/suppliers', \App\Http\Livewire\Supplier::class);
     Route::get('/sponsors', \App\Http\Livewire\Sponsor::class);
     Route::get('/records', \App\Http\Livewire\Record::class);
+    Route::get('/records_old', \App\Http\Livewire\RecordOld::class);
     Route::get('/reminders', \App\Http\Livewire\Reminder::class);
     Route::get('/in', \App\Http\Livewire\RecordIN::class);
     Route::get('/out', \App\Http\Livewire\RecordOUT::class);
@@ -126,6 +127,10 @@ Route::group(['middleware' => 'tenant'], function () {
     Route::get('/sms_comunications', \App\Http\Livewire\SmsComunications::class);
     Route::get('/mail_comunications', \App\Http\Livewire\EmailComunications::class);
 
+    Route::get('/calendar', \App\Http\Livewire\Calendar::class);
+    Route::get('/presences', \App\Http\Livewire\Presence::class);
+    Route::get('/presence_reports', \App\Http\Livewire\PresenceReport::class);
+    Route::get('/absence_reports', \App\Http\Livewire\AbsenceReport::class);
 
     Route::get('/receipt/{id}', function ($id) {
         $receipt = \App\Models\Receipt::findOrFail($id);

Деякі файли не було показано, через те що забагато файлів було змінено