|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Livewire; |
| 4 | + |
| 5 | +use Livewire\Component; |
| 6 | +use App\Models\Attendance; |
| 7 | +use Illuminate\Support\Facades\Auth; |
| 8 | +use Carbon\Carbon; |
| 9 | + |
| 10 | +class AttendanceCalendar extends Component |
| 11 | +{ |
| 12 | + public $month; |
| 13 | + public $year; |
| 14 | + public $daysInMonth = []; |
| 15 | + |
| 16 | + public function mount() |
| 17 | + { |
| 18 | + $this->month = Carbon::now()->month; |
| 19 | + $this->year = Carbon::now()->year; |
| 20 | + $this->generateCalendar(); |
| 21 | + } |
| 22 | + |
| 23 | + public function generateCalendar() |
| 24 | + { |
| 25 | + $date = Carbon::createFromDate($this->year, $this->month, 1); |
| 26 | + $daysInMonthCount = $date->daysInMonth; |
| 27 | + |
| 28 | + $attendances = Attendance::where('user_id', Auth::id()) |
| 29 | + ->whereMonth('date', $this->month) |
| 30 | + ->whereYear('date', $this->year) |
| 31 | + ->get() |
| 32 | + ->keyBy('date'); |
| 33 | + |
| 34 | + $this->daysInMonth = []; |
| 35 | + |
| 36 | + // Padding awal (agar hari pertama sesuai dengan nama hari) |
| 37 | + $firstDayOfWeek = $date->dayOfWeek; // 0 (Sun) to 6 (Sat) |
| 38 | + for ($i = 0; $i < $firstDayOfWeek; $i++) { |
| 39 | + $this->daysInMonth[] = null; |
| 40 | + } |
| 41 | + |
| 42 | + for ($day = 1; $day <= $daysInMonthCount; $day++) { |
| 43 | + $currentDate = Carbon::createFromDate($this->year, $this->month, $day)->format('Y-m-d'); |
| 44 | + $this->daysInMonth[] = [ |
| 45 | + 'day' => $day, |
| 46 | + 'attendance' => $attendances->get($currentDate) |
| 47 | + ]; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public function prevMonth() |
| 52 | + { |
| 53 | + $date = Carbon::createFromDate($this->year, $this->month, 1)->subMonth(); |
| 54 | + $this->month = $date->month; |
| 55 | + $this->year = $date->year; |
| 56 | + $this->generateCalendar(); |
| 57 | + } |
| 58 | + |
| 59 | + public function nextMonth() |
| 60 | + { |
| 61 | + $date = Carbon::createFromDate($this->year, $this->month, 1)->addMonth(); |
| 62 | + $this->month = $date->month; |
| 63 | + $this->year = $date->year; |
| 64 | + $this->generateCalendar(); |
| 65 | + } |
| 66 | + |
| 67 | + public function render() |
| 68 | + { |
| 69 | + return view('livewire.attendance-calendar')->layout('components.layouts.app'); |
| 70 | + } |
| 71 | +} |
0 commit comments