<?php

namespace App\Filament\Pages;

use App\Models\Task;
use Filament\Pages\Page;
use Morilog\Jalali\CalendarUtils;
use Morilog\Jalali\Jalalian;

class TaskCalendar extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-calendar-days';
    protected static ?string $navigationGroup = 'تسک‌ها و یادآوری‌ها';
    protected static ?string $navigationLabel = 'تقویم تسک‌ها';
    protected static ?string $title = 'تقویم ماهانه‌ی تسک‌ها';
    protected static ?int $navigationSort = 2;

    protected static string $view = 'filament.pages.task-calendar';

    public int $year;
    public int $month;

    public static function canAccess(): bool
    {
        return auth()->user()?->can('access_task_calendar') ?? false;
    }

    public static function shouldRegisterNavigation(): bool
    {
        return static::canAccess();
    }

    public function mount(): void
    {
        $now = Jalalian::now();
        $this->year = $now->getYear();
        $this->month = $now->getMonth();
    }

    public function prevMonth(): void
    {
        if ($this->month <= 1) {
            $this->month = 12;
            $this->year--;
        } else {
            $this->month--;
        }
    }

    public function nextMonth(): void
    {
        if ($this->month >= 12) {
            $this->month = 1;
            $this->year++;
        } else {
            $this->month++;
        }
    }

    public function getCalendarProperty(): array
    {
        $daysInMonth = $this->month <= 6 ? 31 : ($this->month <= 11 ? 30 : (CalendarUtils::isLeapJalaliYear($this->year) ? 30 : 29));

        $firstDay = Jalalian::fromFormat('Y/n/j', "{$this->year}/{$this->month}/1")->toCarbon()->startOfDay();
        $leading = ($firstDay->dayOfWeek + 1) % 7; // شنبه = ۰

        // بازه‌ی میلادی این ماه شمسی
        $start = $firstDay->copy();
        $end = $firstDay->copy()->addDays($daysInMonth);

        $tasks = Task::query()->forUser(auth()->user())
            ->whereNotNull('due_date')
            ->whereBetween('due_date', [$start, $end])
            ->get()
            ->groupBy(fn (Task $t) => Jalalian::fromCarbon($t->due_date)->format('j'));

        return [
            'daysInMonth' => $daysInMonth,
            'leading' => $leading,
            'tasks' => $tasks,
            'monthName' => Jalalian::fromFormat('Y/n/j', "{$this->year}/{$this->month}/1")->format('F'),
        ];
    }
}
