<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SemakanTugasanResource\Pages;
use App\Filament\Resources\SemakanTugasanResource\RelationManagers;
use App\Models\Tugasan;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\IconColumn;
use Illuminate\Support\Facades\Auth;
use Filament\Tables\Filters\SelectFilter;
use Illuminate\Contracts\Pagination\Paginator;

class SemakanTugasanResource extends Resource
{
    protected static ?string $model = Tugasan::class;

    protected static ?string $navigationIcon = 'heroicon-s-document-text';

    protected static ?string $pluralModelLabel = 'SEMAKAN TUGAS';

    protected static ?string $navigationLabel = 'SEMAKAN TUGAS';

    protected static ?string $navigationGroup = 'TUGASAN';

    protected static ?string $slug = 'semakantugasan';

    public static function form(Form $form): Form
    {
        return $form->schema([
            //
        ]);
    }

    public static function table(Table $table): Table
    {
        $jenis_pengguna = auth()->user()->roles()->value('id');
        $email = Auth::user()->email;
        $no_institusi_jabatan = Auth::user()->no_institusi_jabatan;

        // Adjust the query based on the user's role
        $tugasQuery = Tugasan::query()
            ->with(['pengguna', 'senaraisesi', 'tugasSampingan', 'unitTugasSampingan', 'senaraiPeringkat', 'status'])
            ->where('tugas.email', $email)->where('aktif',1);

        return $table
            ->query($tugasQuery)
            ->columns([
                // Tables\Columns\TextColumn::make('pengguna.nama')->label('Nama'),
                Tables\Columns\TextColumn::make('index')->label('NO')->rowIndex(),
                Tables\Columns\TextColumn::make('tugasSampingan.nama')->label('TUGAS SAMPINGAN'),
                Tables\Columns\TextColumn::make('unitTugasSampingan.nama')->label('UNIT TUGAS SAMPINGAN'),
                Tables\Columns\TextColumn::make('senaraiPeringkat.nama')->label('PERINGKAT'),
                Tables\Columns\TextColumn::make('senaraisesi.nama')->label('SESI'),
                // Tables\Columns\TextColumn::make('status.nama')->label('Status'),
                // Tables\Columns\TextColumn::make('pengguna.senaraigred.nama')->label('Gred'),
                // Tables\Columns\TextColumn::make('pengguna.institusiJabatan.institusi.nama')->label('Institusi'),
                // Tables\Columns\TextColumn::make('pengguna.institusiJabatan.jabatan.nama')->label('Jabatan'),
                Tables\Columns\TextColumn::make('tarikh_lantikan')->label('TARIKH LANTIKAN'),
                // Tables\Columns\TextColumn::make('catatan')->label('CATATAN'),
                IconColumn::make('aktif')
                    ->label('PENGAKTIFAN')
                    ->boolean()
                    ->visible(function () use ($jenis_pengguna) {
                        return in_array($jenis_pengguna, ['1']);
                    }),
                // TextColumn::make('pengguna.nama')->label('Nama')->searchable(),
                TextColumn::make('tugasSampingan.nama')->label('TUGAS SAMPINGAN')->searchable(),
                TextColumn::make('unitTugasSampingan.nama')
                    ->label('UNIT TUGAS SAMPINGAN')
                    ->searchable()
                    ->visible(function () use ($jenis_pengguna) {
                        return in_array($jenis_pengguna, ['1']);
                    }),
                TextColumn::make('senaraiPeringkat.nama')->label('PERINGKAT')->searchable(),
                TextColumn::make('senaraisesi.nama')->label('SESI')->searchable(),
                // TextColumn::make('pengguna.senaraigred.nama')->label('Gred')->searchable(),
                // TextColumn::make('pengguna.institusiJabatan.institusi.nama')->label('Institusi')->searchable(),
                // TextColumn::make('pengguna.institusiJabatan.jabatan.nama')->label('Jabatan')->searchable(),
                TextColumn::make('tarikh_lantikan')->label('TARIKH LANTIKAN')->searchable(),
                // TextColumn::make('catatan')->label('Catatan')->searchable()
            ])
            ->defaultSort(fn($query) => $query->orderBy('sesi', 'desc')->orderBy('peringkat', 'desc'))
            ->deferLoading()
            ->striped()
            ->filters([SelectFilter::make('sesi')->relationship('senaraiSesi', 'nama')->searchable()->preload(), SelectFilter::make('peringkat')->relationship('senaraiPeringkat', 'nama')->searchable()->preload()])
            ->actions([
                //
            ])
            ->bulkActions([
                //
            ]);
    }

    public static function getRelations(): array
    {
        return [
                //
            ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListSemakanTugasans::route('/'),
            // 'create' => Pages\CreateSemakanTugasan::route('/create'),
            // 'edit' => Pages\EditSemakanTugasan::route('/{record}/edit'),
        ];
    }

    public static function canCreate(): bool
    {
        return false;
    }

    // public static function canViewAny(): bool
    // {
    //     $userId = auth()->user()->jenis_pengguna;
    //     return in_array($userId, [1, 2, 3, 4]);
    // }

    public static function canViewAny(): bool
    {
        // dd(auth()->user()->roles());
        return auth()
            ->user()
            ->hasAnyRole(['Super Admin', 'Penyelaras','Pengguna','Pengurusan']);
    }

    protected function paginateTableQuery(Builder $query): Paginator
    {
        return $query->fastPaginate($this->getTableRecordsPerPage());
    }

    public static function getNavigationBadge(): ?string
    {
        $user = Auth::user();

        if (!$user) {
            return null;
        }

        // Check the user's role and adjust the count query accordingly
        if (in_array($user->jenis_pengguna, [1, 2, 3, 4])) {
            // For role 3, filter by the user's email or institution
            return static::getModel()::where('email', $user->email)->where('aktif',1)->count();
        } else {
            // For role 4, filter by institution/jabatan

        }

        // Default to no badge for other roles
        return null;
    }
}
