<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SemakanLaporanResource\Pages;
use App\Filament\Resources\SemakanLaporanResource\RelationManagers;
use App\Models\DokumenRujukan;
use App\Models\InstitusiJabatan;
use App\Models\JenisLaporan;
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\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\Select;
use Filament\Tables\Actions\Action;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Blade;
use Filament\Forms\Components\DatePicker;
use Maatwebsite\Excel\Facades\Excel;
use ZipArchive;
use Illuminate\Support\Facades\Response;
use App\Models\SenaraiJPKA;
use Illuminate\Support\Facades\Auth;

use App\Models\JenisDokumen;
use App\Models\Sesi;
use App\Models\Tugasan;
use App\Models\Pengguna;
use App\Models\Institusi;
use App\Models\Jabatan;
use App\Exports\ExcelSenaraiPenggunaExport;
use App\Exports\ExcelSenaraiTugasExport;

use NumConvert;

class SemakanLaporanResource extends Resource
{
    protected static ?string $model = JenisLaporan::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

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

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

    protected static ?string $navigationGroup = 'LAPORAN';

    protected static ?string $slug = 'semakanlaporan';

    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 = JenisLaporan::query()
            ->with(['jenisdokumen'])
            ->whereBetween('no', [1, 5]);

        if ($jenis_pengguna == 1) {
            // If user is not admin, filter jenis laporan based on user's role

        } elseif ($jenis_pengguna == 2) {
            $tugasQuery->whereNot('no', 5);
        } elseif ($jenis_pengguna == 3) {
            $tugasQuery->whereIn('no', [1, 3]);
        } elseif ($jenis_pengguna == 4) {
            $tugasQuery->whereNot('no', 4);
        }

        ini_set("memory_limit", "-1");
        set_time_limit(0);
        return $table
            ->query($tugasQuery)
            ->columns([
                Tables\Columns\TextColumn::make('index')->label('No')->rowIndex(),
                Tables\Columns\TextColumn::make('nama')->label('NAMA'),
                Tables\Columns\TextColumn::make('jenisdokumen.nama')->label('DOKUMEN'),
                TextColumn::make('nama')->label('NAMA')->searchable(),
                TextColumn::make('jenisdokumen.nama')->label('DOKUMEN')->searchable()
            ])
            ->defaultSort('nama')
            ->deferLoading()
            ->striped()
            ->filters([
                //
            ])
            ->actions([
                Action::make('muat_turun')
                    ->label('MUAT TURUN')
                    ->icon('heroicon-o-arrow-down-tray')
                    ->form(function ($record) {
                        $formFields = [];

                        // Assuming $record->no is used to determine the form fields dynamically
                        switch ($record->no) {
                            case 1:
                                $formFields[] = Select::make('institusi')
                                    ->label('Institusi')
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan')->where('aktif', 1);

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        if ($user->jenis_pengguna == 2 || $user->jenis_pengguna == 3) {
                                            $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        } elseif ($user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->institusi->no => $institusi_jabatan->institusi->nama];
                                        });
                                    }) // Assuming Sesi is a model
                                    ->searchable()
                                    ->rules('required');
                                $formFields[] = Select::make('jabatan')
                                    ->label('Jabatan')
                                    ->searchable()
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan');

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        // if ($user->jenis_pengguna == 2) {
                                        //     $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        // } else

                                        if ($user->jenis_pengguna == 2 || $user->jenis_pengguna == 3 || $user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->jabatan->no => $institusi_jabatan->jabatan->nama];
                                        });
                                    }); // Assuming Sesi is a model
                                break;
                            case 2:
                                $formFields[] = Select::make('institusi')
                                    ->label('Institusi')
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan');

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        if ($user->jenis_pengguna == 2) {
                                            $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        } elseif ($user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->institusi->no => $institusi_jabatan->institusi->nama];
                                        });
                                    }) // Assuming Sesi is a mode
                                    ->searchable()
                                    ->rules('required');
                                $formFields[] = Select::make('jabatan')
                                    ->label('Jabatan')
                                    ->searchable()
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan');

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        if ($user->jenis_pengguna == 2) {
                                            $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        } elseif ($user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->jabatan->no => $institusi_jabatan->jabatan->nama];
                                        });
                                    }); // Assuming Sesi is a model
                                $formFields[] = Select::make('sesi')
                                    ->label('Sesi')
                                    ->options(Sesi::pluck('nama', 'no')) // Assuming Sesi is a mode
                                    ->searchable()
                                    ->rules('required');
                                break;
                            case 3:
                                $formFields[] = Select::make('institusi')
                                    ->label('Institusi')
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan');

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        if ($user->jenis_pengguna == 2 || $user->jenis_pengguna == 3) {
                                            $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        } elseif ($user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->institusi->no => $institusi_jabatan->institusi->nama];
                                        });
                                    }) // Assuming Sesi is a model
                                    ->searchable()
                                    ->rules('required');
                                $formFields[] = Select::make('jabatan')
                                    ->label('Jabatan')
                                    ->searchable()
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan')->where('aktif', 1);

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        // if ($user->jenis_pengguna == 2) {
                                        //     $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        // } else

                                        if ($user->jenis_pengguna == 2 || $user->jenis_pengguna == 3 || $user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->jabatan->no => $institusi_jabatan->jabatan->nama];
                                        });
                                    }); // Assuming Sesi is a model
                                $formFields[] = Select::make('sesi')
                                    ->label('Sesi')
                                    ->options(Sesi::pluck('nama', 'no')) // Assuming Sesi is a model
                                    ->searchable()
                                    ->rules('required');
                                break;
                            case 4:
                                $formFields[] = Select::make('dokumen_rujukan')
                                    ->label('Dokumen Rujukan')
                                    ->options(DokumenRujukan::where('jenis_dokumen_rujukan', '4')->pluck('nama', 'no')) // Assuming Sesi is a mode
                                    ->searchable()
                                    ->rules('required');
                                $formFields[] = Select::make('institusi')
                                    ->label('Institusi')
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan');

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        if ($user->jenis_pengguna == 2) {
                                            $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        } elseif ($user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->institusi->no => $institusi_jabatan->institusi->nama];
                                        });
                                    }) // Assuming Sesi is a model
                                    ->searchable()
                                    ->rules('required');
                                $formFields[] = Select::make('jabatan')
                                    ->label('Jabatan')
                                    ->searchable()
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan');

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        if ($user->jenis_pengguna == 2) {
                                            $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        } elseif ($user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->jabatan->no => $institusi_jabatan->jabatan->nama];
                                        });
                                    }); // Assuming Sesi is a model
                                $formFields[] = DatePicker::make('tarikh_lantikan')->label('Tarikh Lantikan')->rules('required')->native(false);
                                $formFields[] = Select::make('sesi')
                                    ->label('Sesi')
                                    ->options(Sesi::pluck('nama', 'no')) // Assuming Sesi is a model
                                    ->searchable()
                                    ->rules('required');
                                break;
                            case 5:
                                $formFields[] = Select::make('dokumen_rujukan')
                                    ->label('Dokumen Rujukan')
                                    ->options(DokumenRujukan::where('jenis_dokumen_rujukan', '5')->pluck('nama', 'no')) // Assuming Sesi is a mode
                                    ->searchable()
                                    ->rules('required');
                                $formFields[] = DatePicker::make('tarikh_lantikan')->label('Tarikh Lantikan')->rules('required')->native(false);
                                $formFields[] = Select::make('institusi')
                                    ->label('Institusi')
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan');

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        if ($user->jenis_pengguna == 2) {
                                            $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        } elseif ($user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->institusi->no => $institusi_jabatan->institusi->nama];
                                        });
                                    }) // Assuming Sesi is a mode
                                    ->searchable()
                                    ->rules('required');
                                $formFields[] = Select::make('jabatan')
                                    ->label('Jabatan')
                                    ->searchable()
                                    ->options(function () {
                                        // Eager load related models
                                        $institusi_jabatan_query = InstitusiJabatan::with('institusi', 'jabatan');

                                        // Get the current user's institusi_jabatan
                                        $user = Auth::user();


                                        // Apply conditions based on jenis_pengguna
                                        if ($user->jenis_pengguna == 2) {
                                            $institusi_jabatan_query->where('no', $user->no_institusi_jabatan);
                                        } elseif ($user->jenis_pengguna == 4) {
                                            $institusi_jabatan_individu = InstitusiJabatan::where('no', $user->no_institusi_jabatan)->first();
                                            $institusi = $institusi_jabatan_individu->no_institusi;
                                            $institusi_jabatan_query->whereHas('institusi', function ($query) use ($institusi) {
                                                $query->where('no', $institusi)->orderBy('nama');
                                            });
                                        }

                                        // Execute the query and order the results
                                        $institusi_jabatan = $institusi_jabatan_query->get();

                                        // Manipulate data to format as needed for select dropdown
                                        return $institusi_jabatan->mapWithKeys(function ($institusi_jabatan) {
                                            return [$institusi_jabatan->jabatan->no => $institusi_jabatan->jabatan->nama];
                                        });
                                    }); // Assuming Sesi is a model
                                break;
                            // Add more cases as needed

                            default:
                                // Default behavior if $record->no doesn't match any case
                                break;
                        }

                        return $formFields;
                    })
                    ->action(function (array $data, JenisLaporan $record) {
                        // Assuming you need to associate authorId with the record

                        if ($record['no_jenis_dokumen'] == 1) {

                            if ($record['no'] == 5) {
                                $tarikh_surat = date('d/m/Y', strtotime($data['tarikh_lantikan']));
                            } else {
                                if (empty ($data['jabatan'])) {

                                    $tugas = Tugasan::where('tugas.aktif', 1)->where('institusi_jabatan.no_institusi', $data['institusi'])->where('tugas.sesi', $data['sesi'])->where('users.aktif', 1)->orderBy('users.nama', 'asc')->leftJoin('users', 'users.email', '=', 'tugas.email')->select('users.nama as nama_pengguna')->leftJoin('institusi_jabatan', 'institusi_jabatan.no', '=', 'users.no_institusi_jabatan')->leftJoin('jabatan', 'jabatan.no', '=', 'institusi_jabatan.no_jabatan')->leftJoin('tugas_sampingan', 'tugas_sampingan.no', '=', 'tugas.no_tugas_sampingan')->leftJoin('unit_tugas_sampingan', 'unit_tugas_sampingan.no', '=', 'tugas.no_unit_tugas_sampingan')->leftJoin('status', 'status.no', '=', 'tugas.no_status')->leftJoin('peringkat', 'peringkat.no', '=', 'tugas.peringkat')->leftJoin('gred', 'gred.no', '=', 'users.gred')->leftJoin('sesi', 'sesi.no', '=', 'tugas.sesi')->select('users.nama as nama_pengguna', 'jabatan.nama as nama_jabatan', 'tugas_sampingan.nama as nama_tugas_sampingan', 'unit_tugas_sampingan.nama as nama_unit_tugasan_sampingan', 'status.nama as nama_status', 'tugas.aktif as tugas_aktif', 'tugas.tarikh_lantikan as tarikh_lantikan', 'tugas.no as no', 'tugas.catatan as catatan', 'peringkat.nama as nama_peringkat', 'gred.nama as nama_gred', 'tugas.peringkat as tugas_peringkat', 'users.email')->get();

                                } else {

                                    $tugas = Tugasan::where('tugas.aktif', 1)->where('institusi_jabatan.no_institusi', $data['institusi'])->where('institusi_jabatan.no_jabatan', $data['jabatan'])->where('tugas.sesi', $data['sesi'])->where('users.aktif', 1)->orderBy('users.nama', 'asc')->leftJoin('users', 'users.email', '=', 'tugas.email')->select('users.nama as nama_pengguna')->leftJoin('institusi_jabatan', 'institusi_jabatan.no', '=', 'users.no_institusi_jabatan')->leftJoin('jabatan', 'jabatan.no', '=', 'institusi_jabatan.no_jabatan')->leftJoin('tugas_sampingan', 'tugas_sampingan.no', '=', 'tugas.no_tugas_sampingan')->leftJoin('unit_tugas_sampingan', 'unit_tugas_sampingan.no', '=', 'tugas.no_unit_tugas_sampingan')->leftJoin('status', 'status.no', '=', 'tugas.no_status')->leftJoin('peringkat', 'peringkat.no', '=', 'tugas.peringkat')->leftJoin('gred', 'gred.no', '=', 'users.gred')->leftJoin('sesi', 'sesi.no', '=', 'tugas.sesi')->select('users.nama as nama_pengguna', 'jabatan.nama as nama_jabatan', 'tugas_sampingan.nama as nama_tugas_sampingan', 'unit_tugas_sampingan.nama as nama_unit_tugasan_sampingan', 'status.nama as nama_status', 'tugas.aktif as tugas_aktif', 'tugas.tarikh_lantikan as tarikh_lantikan', 'tugas.no as no', 'tugas.catatan as catatan', 'peringkat.nama as nama_peringkat', 'gred.nama as nama_gred', 'tugas.peringkat as tugas_peringkat', 'users.email')->get();

                                }

                                $mappedResults = $tugas->map(function ($result) {
                                    return [
                                        'nama_pengguna' => $result->nama_pengguna,
                                        'nama_jabatan' => $result->nama_jabatan,
                                        'nama_tugas_sampingan' => $result->nama_tugas_sampingan,
                                        'nama_unit_tugasan_sampingan' => $result->nama_unit_tugasan_sampingan,
                                        'nama_status' => $result->nama_status,
                                        'tugas_aktif' => $result->tugas_aktif,
                                        'tarikh_lantikan' => $result->tarikh_lantikan,
                                        'no' => $result->no,
                                        'catatan' => $result->catatan,
                                        'nama_peringkat' => $result->nama_peringkat,
                                        'nama_gred' => $result->nama_gred,
                                        'tugas_peringkat' => $result->tugas_peringkat,
                                        'email' => $result->email,
                                    ];
                                });

                                $groupedResults = $mappedResults->groupBy('nama_pengguna');
                            }

                            if ($record['no'] == 2) {

                                return response()->streamDownload(function () use ($record, $data, $groupedResults) {

                                    $institusi = Institusi::all()->where('no', $data['institusi'])->first();

                                    echo Pdf::loadHtml(
                                        Blade::render('pdf-tugas-sampingan', ['record' => $record, 'tugas' => $groupedResults, 'institusi' => $institusi])
                                    )->setPaper('A4', 'landscape')->stream();
                                }, 'TUGAS_SAMPINGAN' . date('Y-m-d H:i:s') . '.pdf');

                            } elseif ($record['no'] == 4) {

                                return response()->streamDownload(function () use ($record, $data, $groupedResults) {

                                    $dokumen_rujukan = $data['dokumen_rujukan'];
                                    $institusi = $data['institusi'];
                                    $jabatan = $data['jabatan'];
                                    $tarikh_lantikan = $data['tarikh_lantikan'];
                                    $sesi = $data['sesi'];

                                    $dokumen_rujukan = DokumenRujukan::with('pengguna')->where('no', $dokumen_rujukan)->first();
                                    //$no_dokumen_rujukan = $no_dokumen_rujukan->no_dokumen;

                                    $sqlSenaraiSesiDokumen = Sesi::where('no', $sesi)->select('sesi.semester as semester_sesi', 'sesi.sesi_mula as sesi_mula', 'sesi.sesi_tamat as sesi_tamat')->first();

                                    $semester = NumConvert::roman(intval($sqlSenaraiSesiDokumen->semester_sesi)) . ' ' . $sqlSenaraiSesiDokumen->sesi_mula . '/' . $sqlSenaraiSesiDokumen->sesi_tamat;

                                    if (empty ($data['jabatan'])) {
                                        $institusi = InstitusiJabatan::with('institusi')
                                            ->where('no_institusi', $institusi)
                                            ->first();
                                    } else {
                                        $institusi = InstitusiJabatan::with('institusi')
                                            ->where('no_institusi', $institusi)
                                            ->where('no_jabatan', $jabatan)
                                            ->first();
                                    }

                                    echo Pdf::loadHtml(
                                        Blade::render('pdf-surat-lantikan', ['record' => $record, 'tugas' => $groupedResults, 'institusi' => $institusi, 'dokumen_rujukan' => $dokumen_rujukan, 'tarikh_surat' => $tarikh_lantikan, 'semester' => $semester])
                                    )->setPaper('A4')->stream();
                                }, 'SURAT_LANTIKAN' . date('Y-m-d H:i:s') . '.pdf');

                            } elseif ($record['no'] == 5) {

                                $dokumen_rujukan = $data['dokumen_rujukan'];

                                $data = SenaraiJPKA::where('senarai_jpka.aktif', 1)->leftJoin('users', 'users.email', '=', 'senarai_jpka.email')->leftJoin('jawatan', 'jawatan.no', '=', 'senarai_jpka.no_jawatan')->select('users.nama as nama_pengguna', 'jawatan.nama as nama_jawatan', 'jawatan.no as no_jawatan')->where('senarai_jpka.no_dokumen_rujukan', $dokumen_rujukan)->orderBy('senarai_jpka.kedudukan', 'asc')->get();

                                $tandatangan = DokumenRujukan::with('pengguna')->where('no', $dokumen_rujukan)->first();

                                $dokumen_rujukan_edaran = DokumenRujukan::where('dokumen_rujukan.aktif', 1)->where('dokumen_rujukan.no', $dokumen_rujukan)->first();

                                // Render both Blade views into a single view
                                $html1 = view('pdf-surat-jpka', compact('data', 'dokumen_rujukan_edaran', 'tarikh_surat', 'tandatangan'))->render();
                                $html2 = view('pdf-surat-edaran', compact('data', 'dokumen_rujukan_edaran', 'tarikh_surat'))->render();

                                // Load the PDF views with combined data
                                $pdf1 = PDF::loadHTML($html1)->setPaper('A4', 'portrait');
                                $pdf2 = PDF::loadHTML($html2)->setPaper('A4', 'portrait');

                                // Temporary directory to store the PDFs
                                $tempDir = sys_get_temp_dir();

                                // Save PDFs to temporary files
                                $pdf1Path = $tempDir . '/SURAT_EDARAN_' . date('Y-m-d') . '.pdf';
                                $pdf2Path = $tempDir . '/SENARAI_NAMA_' . date('Y-m-d') . '.pdf';
                                $pdf1->save($pdf1Path);
                                $pdf2->save($pdf2Path);

                                // Create a zip archive
                                $zip = new ZipArchive;
                                $zipFileName = 'SURAT_EDARAN_' . date('Y-m-d') . '.zip';
                                $zipFilePath = $tempDir . '/' . $zipFileName;
                                if ($zip->open($zipFilePath, ZipArchive::CREATE) === TRUE) {
                                    $zip->addFile($pdf1Path, 'SURAT_EDARAN_' . date('Y-m-d') . '.pdf');
                                    $zip->addFile($pdf2Path, 'SENARAI_NAMA_' . date('Y-m-d') . '.pdf');
                                    $zip->close();

                                    // Prepare response to download zip file
                                    $headers = [
                                        'Content-Type' => 'application/octet-stream',
                                    ];

                                    return Response::download($zipFilePath, $zipFileName, $headers)->deleteFileAfterSend(true);
                                } else {
                                    // Handle error opening zip archive
                                    return response()->json(['error' => 'Failed to create ZIP archive'], 500);
                                }


                            }

                        } else {
                            //Excel

                            if ($record['no'] == 1) {

                                $institusi = $data['institusi'];
                                $jabatan = $data['jabatan'];

                                return Excel::download(new ExcelSenaraiPenggunaExport($institusi, $jabatan), 'SENARAI_PENGGUNA_' . now() . '.xlsx');

                            } elseif ($record['no'] == 3) {

                                $institusi = $data['institusi'];
                                $jabatan = $data['jabatan'];
                                $sesi = $data['sesi'];

                                return Excel::download(new ExcelSenaraiTugasExport($institusi, $jabatan, $sesi), 'SENARAI_PENGGUNA_' . now() . '.xlsx');
                            }

                        }

                        // $record->nama = $record['no_jenis_dokumen'];
                        // $record->no_jenis_dokumen = 1;
                        // $record->aktif = 1; // Assuming 'authorId' is passed in the form data
                        // $record->save();
                    }),
            ])

            ->bulkActions([
                //
            ]);
    }

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

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

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

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