<?php

namespace App\Filament\Resources;

use App\Filament\Resources\InputIjazahResource\Pages;
use App\Filament\Resources\InputIjazahResource\RelationManagers;
use App\Models\Fakultas;
use App\Models\InputIjazah;
use App\Models\ProgramStudi;
use App\Models\TahunAkademik;
use Carbon\Carbon;
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;


class InputIjazahResource extends Resource
{
    protected static ?string $model = InputIjazah::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationLabel = 'Input Ijazah';
    protected static ?string $navigationGroup = 'Upload Data';
    protected static ?int $navigationSort = 61;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('nim_mhs')
                    ->required()
                    ->label('Nomor Induk Mahasiswa')
                    //->numeric()
                    ->type('numer')
                    ->integer()
                    ->placeholder('Masukkan hanya nomor')
                    ->maxLength(8),
                Forms\Components\TextInput::make('nama_mhs')
                    ->required()
                    ->label('Nama Mahasiswa')
                    ->maxLength(50)
                    ->placeholder('Masukan Nama Mahasiswa'),
                Forms\Components\Select::make('fakultas_id')
                    ->options(Fakultas::all()->pluck('fakultas', 'id'))
                    ->label('Fakultas')
                    ->placeholder('Pilih Fakultas')
                    ->reactive()
                    ->required(),
                Forms\Components\Select::make('program_studi_id')
                    ->label('Program Studi')
                    ->options(function (callable $get) {
                        // Ambil ID Fakultas yang dipilih
                        $fakultasId = $get('fakultas_id');
                    
                        // Jika tidak ada Fakultas yang dipilih, kembalikan array kosong
                        if (!$fakultasId) {
                            return [];
                        }
                    
                        // Ambil Prodi yang sesuai dengan Fakultas yang dipilih
                        return ProgramStudi::where('fakultas_id', $fakultasId)->pluck('program_studi', 'id');
                    })
                    ->placeholder('Pilih Program Studi')
                    ->reactive() // Aktifkan mode reaktif
                    ->disabled(fn (callable $get) => !$get('fakultas_id')) // Nonaktifkan jika Fakultas belum dipilih
                    //->options(ProgramStudi::all()->pluck('program_studi', 'id'))
                    ->required(),
                    //->required(fn (callable $get) => $get('klaster_ajuan') === 'mahasiswa'), // Wajib jika pilihan "mahasiswa"
                    //->visible(fn (callable $get) => $get('klaster_ajuan') === 'mahasiswa'), // Hanya tampil jika jenis ajuan 'mahasiswa',
                Forms\Components\Select::make('tahun_akademik_id')
                    ->options(TahunAkademik::all()->pluck('tahun_akademik', 'id'))
                    ->label('Tahun Akademik')
                    ->placeholder('Pilih Tahun Akademik')
                    ->reactive()
                    ->required(),
                Forms\Components\TextInput::make('skyudi')
                    ->required()
                    ->label('SK Yudisium')
                    ->placeholder('Masukan No SK Yudisium')
                    ->maxLength(50),
                Forms\Components\DatePicker::make('tglyudi')
                    ->required()
                    //->format('d/m/Y') // Ubah format sesuai kebutuhan,
                    ->native(false)
                    ->displayFormat('d/m/Y')
                    ->label('Tanggal Yudisium')
                    ->placeholder('Masukan Tanggal Yudisium')
                    ->closeOnDateSelection(),
                Forms\Components\TextInput::make('no_ijazah')
                    ->required()
                    ->label('Penomoran Ijazah Nasional')
                    ->type('numer')
                    //->integer(21)
                    ->placeholder('Masukkan hanya nomor')
                    ->maxLength(21),
                Forms\Components\DatePicker::make('tglijazah')
                    ->required()
                    //->format('d/m/Y') // Ubah format sesuai kebutuhan,
                    ->native(false)
                    ->displayFormat('d/m/Y')
                    ->label('Tanggal Ijazah')
                    ->placeholder('Masukan Tanggal Ijazah')
                    ->closeOnDateSelection(),
                Forms\Components\FileUpload::make('upload_ijazah')
                    ->required()
                    ->label('Upload Ijazah')
                    ->openable()
                    ->directory('uploads\ijazah')
                    ->disk('public')
                    ->reorderable()
                    ->acceptedFileTypes(['application/pdf'])
                    ->maxSize(10240)
                    ->downloadable()
                    ->panelLayout('grid')
                    ->visibility('public')
                    ->preserveFilenames()
                    ->helperText('Accepts .pdf or image files up to 10MB only.')
                    ->nullable(),
                Forms\Components\FileUpload::make('upload_transkip')
                    ->required()
                    ->label('Upload Transkip')
                    ->openable()
                    ->directory('uploads\transkip')
                    ->disk('public')
                    ->reorderable()
                    ->acceptedFileTypes(['application/pdf'])
                    ->maxSize(10240)
                    ->downloadable()
                    ->panelLayout('grid')
                    ->visibility('public')
                    ->preserveFilenames()
                    ->helperText('Accepts .pdf or image files up to 10MB only.')
                    ->nullable(),

            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('nim_mhs')
                    ->numeric()
                    ->label('NIM')
                    ->formatStateUsing(function ($state) {
                        return str_replace(',', '', $state); // Hapus koma dari tampilan
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('nama_mhs')
                    ->searchable()
                    ->sortable()
                    ->label('Nama Mahasiswa'),
                Tables\Columns\TextColumn::make('fakultas.fakultas')
                    ->numeric()
                    ->label('Fakultas')
                    ->sortable(),
                Tables\Columns\TextColumn::make('programStudi.program_studi')
                    ->numeric()
                    ->searchable()
                    ->label('Program Studi')
                    ->sortable(),
                Tables\Columns\TextColumn::make('tahunAkademik.tahun_akademik')
                    ->numeric()
                    ->label('Tahun Akademik')
                    ->formatStateUsing(function ($state) {
                        return str_replace(',', '', $state); // Hapus koma dari tampilan
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('skyudi')
                    ->searchable()
                    ->label('SK Yudisium'),
                Tables\Columns\TextColumn::make('tglyudi')
                    ->date()
                    ->label('Tanggal Yudisium')
                    ->formatStateUsing(function ($record) {
                        // Mengubah format tanggal menjadi 'd F Y' (contoh: 26 November 2024)
                        return Carbon::parse($record->tanggal)->format('d F Y');
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('no_ijazah')
                    ->numeric()
                    ->label('Nomor Ijazah')
                    ->formatStateUsing(function ($state) {
                        return str_replace(',', '', $state); // Hapus koma dari tampilan
                    })
                    ->sortable(),
                Tables\Columns\TextColumn::make('tglijazah')
                    ->date()
                    ->label('Tanggal Ijazah')
                    ->formatStateUsing(function ($record) {
                        // Mengubah format tanggal menjadi 'd F Y' (contoh: 26 November 2024)
                        return Carbon::parse($record->tanggal)->format('d F Y');
                    })
                    ->sortable(),
                //Tables\Columns\ImageColumn::make('upload_ijazah')
                //    ->searchable()
                //   ->label('Ijazah'),
                Tables\Columns\TextColumn::make('upload_ijazah')
                    ->label('Ijazah')
                    ->formatStateUsing(function ($record) {
                        // Cek apakah file ada
                        if (!empty($record->upload_ijazah)) {
                            $fileUrl = asset('storage/' . $record->upload_ijazah);
                
                            // Tombol untuk melihat dan mendownload file
                            return '
                                <a href="' . $fileUrl . '" target="_blank" class="inline-flex items-center px-2 py-1 bg-green-500 btn-text-black rounded btn-hover mr-2">
                                    <i class="fas fa-eye mr-1"></i> View
                                </a>
                                    <a href="' . $fileUrl . '" download class="inline-flex items-center px-2 py-1 bg-blue-500 btn-text-black rounded btn-hover">
                                <i class="fas fa-download mr-1"></i> Download
                                    </a>';
                        } else {
                            return '<span class="text-red-500">Ijazah Tidak Ada</span>';
                        }
                    })
                    ->html(), // Aktifkan HTML untuk menampilkan tombol
                Tables\Columns\TextColumn::make('upload_transkip')
                    ->label('Transkip')
                    ->formatStateUsing(function ($record) {
                        // Cek apakah file ada
                        if (!empty($record->upload_traskip)) {
                            $fileUrl = asset('storage/' . $record->upload_transkip);
                
                            // Tombol untuk melihat dan mendownload file
                            return '
                                <a href="' . $fileUrl . '" target="_blank" class="inline-flex items-center px-2 py-1 bg-green-500 btn-text-black rounded btn-hover mr-2">
                                    <i class="fas fa-eye mr-1"></i> View
                                </a>
                                    <a href="' . $fileUrl . '" download class="inline-flex items-center px-2 py-1 bg-blue-500 btn-text-black rounded btn-hover">
                                <i class="fas fa-download mr-1"></i> Download
                                    </a>';
                        } else {
                            return '<span class="text-red-500">Transkip Tidak Ada</span>';
                        }
                    })
                ->html(), // Aktifkan HTML untuk menampilkan tombol
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ]);
    }

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

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

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
