<?php

namespace Modules\Lpj\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use Modules\Lpj\Models\KJPP;
use Modules\Location\Models\City;
use Illuminate\Support\Facades\DB;
use Modules\Lpj\Models\Permohonan;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Location\Models\Village;
use Modules\Lpj\Models\JenisLaporan;
use Modules\Location\Models\District;
use Modules\Location\Models\Province;
use Modules\Lpj\Models\PenawaranTender;
use Modules\Lpj\Models\StatusPermohonan;
use Modules\Lpj\Models\TujuanPenilaianKJPP;
use Modules\Lpj\Models\PenawaranDetailTender;
use Modules\Lpj\Exports\PenawaranTenderExport;
use Modules\Lpj\Http\Requests\TenderPenawaranRequest;
use Modules\Lpj\Jobs\SendPenawaranKJPPTenderJob;
use Modules\Lpj\Jobs\SendPenawaranTenderJob;
use Modules\Lpj\Models\PenawaranEmailTenderLog;

class TenderController extends Controller
{
    public $user;

    /**
     * Display a listing of the resource.
     */
    public function penawaran_index()
    {
        return view('lpj::penawaran/index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function penawaran_create($noreg)
    {
        $penawaranExists = PenawaranTender::where('nomor_registrasi', '=', $noreg)->exists();

        // Jika nomor_registrasi sudah ada, kembalikan respon 403 Forbidden
        if ($penawaranExists) {
            return redirect()->route('tender.penawaran.editPenawaran', ['noreg' => $noreg])
                ->with('error', 'Penawaran dengan nomor registrasi ini sudah ada, Anda akan diarahkan ke halaman edit.');
        }

        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

        $status = StatusPermohonan::all();
        $tujuan_penilaian_kjpp = TujuanPenilaianKJPP::all();
        $jenis_laporan = JenisLaporan::all();

        $kjpp = KJPP::all();

        return view('lpj::penawaran/create', compact('status', 'tujuan_penilaian_kjpp', 'jenis_laporan', 'kjpp', 'noreg', 'permohonan'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function penawaran_store(TenderPenawaranRequest $request, $noreg)
    {
        $validated = $request->validated();

        DB::beginTransaction();

        try {
            $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

            // Add created_by/updated_by from the authenticated user
            $userId = Auth::user()->id;

            $validated['nomor_registrasi'] = $permohonan->nomor_registrasi;

            $validated['status'] = $request->input('status') ?? 'tender';
            $validated['updated_by'] = $userId; // Updating the record
            $validated['end_date'] = $request->input('end_date') . ' 17:00:00';
            // dd($validated['end_date']);
            $permohonan->update($validated);

            // Adding created_by for the new PenawaranTender record
            $validated['created_by'] = $userId;
            $penawaranId = PenawaranTender::create($validated);

            $kjpps = $request->input('kjpp', []);

            foreach ($kjpps as $kjpp) {
                PenawaranDetailTender::create([
                    'penawaran_id' => $penawaranId->id,
                    'kjpp_rekanan_id' => $kjpp,
                    'created_by' => $userId, // Set created_by for details
                    'updated_by' => $userId
                ]);
            }

            // Commit the transaction
            DB::commit();

            return redirect()
                ->route('tender.penawaran.index')
                ->with('success', 'Data Penawaran created successfully');
        } catch (Exception $e) {
            DB::rollBack();

            return redirect()
                ->route('tender.penawaran.createPenawaran', $noreg)
                ->with('error', 'Validation failed: ' . $e);
        }
    }

    /**
     * Show the specified resource.
     */
    public function penawaran_show($noreg)
    {
        $penawaran = null;
        $kjpps = null;
        $tujuan_penilaian_kjpp = null;
        $jenis_laporan = null;

        $penawaranExists = PenawaranTender::where('nomor_registrasi', $noreg)->exists();

        $penawaran1 = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();

        if (!$penawaran1) {
            return redirect()->route('tender.penawaran.createPenawaran', ['noreg' => $noreg])->with('error', 'Penawaran dengan nomor registrasi ini belum dibuat. Silahkan isi terlebih dahulu!');
        }

        if ($penawaran1->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        // dd($penawaran1->id);
        if ($penawaran1) {
            $penawaran = $penawaran1;
            $detail_penawaran = PenawaranDetailTender::where('penawaran_id', '=', $penawaran1->id)->where('status', '=', 1)->pluck('kjpp_rekanan_id')->toArray();
            $kjpps = KJPP::whereIn('id', $detail_penawaran)->get();
            $tujuan_penilaian_kjpp = TujuanPenilaianKJPP::where('id', $penawaran->tujuan_penilaian_kjpp_id)->get();
            $jenis_laporan = JenisLaporan::where('id', $penawaran->jenis_laporan_id)->get();
        } else {
            $penawaran2 = Permohonan::where('nomor_registrasi', '=', $noreg)->first();
            $penawaran = $penawaran2;
        }

        // dd($kjpps);

        return view('lpj::penawaran.show', compact('noreg', 'penawaran', 'kjpps', 'tujuan_penilaian_kjpp', 'jenis_laporan', 'penawaranExists'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function penawaran_edit($noreg)
    {
        // Find the specific penawaran by its ID
        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();

        if (!$penawaran) {
            return redirect()->route('tender.penawaran.createPenawaran', ['noreg' => $noreg])->with('error', 'Penawaran dengan nomor registrasi ini belum dibuat. Silahkan isi terlebih dahulu!');
        }

        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();


        if ($penawaran->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        $status = StatusPermohonan::all();
        $tujuan_penilaian_kjpp = TujuanPenilaianKJPP::all();
        $jenis_laporan = JenisLaporan::all();

        $detail_penawaran = PenawaranDetailTender::where('penawaran_id', '=', $penawaran->id)->where('status', '=', 1)->pluck('kjpp_rekanan_id')->toArray();
        $kjpps = KJPP::whereIn('id', $detail_penawaran)->pluck('id')->toArray();

        $kjpp = KJPP::all();

        // dd($penawaran);

        return view('lpj::penawaran.edit', compact('status', 'tujuan_penilaian_kjpp', 'jenis_laporan', 'kjpp', 'penawaran', 'noreg', 'kjpps', 'permohonan'));
    }


    /**
     * Update the specified resource in storage.
     */
    public function penawaran_update(TenderPenawaranRequest $request, $noreg)
    {
        $validated = $request->validated();

        DB::beginTransaction();

        try {
            // Ambil data penawaran berdasarkan nomor registrasi
            $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();
            $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

            // Ambil ID user yang sedang login
            $userId = Auth::user()->id;

            // Jangan ubah created_by untuk data yang sudah ada
            $validated['nomor_registrasi'] = $penawaran->nomor_registrasi;
            $validated['status'] = $request->input('status') ?? 'tender';
            $validated['created_by'] = $userId;
            $validated['updated_by'] = $userId; // Hanya update 'updated_by'
            $validated['end_date'] = $request->input('end_date') . ' 17:00:00';
            // dd($validated['end_date']);

            // Update data penawaran dan permohonan
            $penawaran->update($validated);
            $permohonan->update($validated);

            $kjpps = $request->input('kjpp', []);

            // Ubah status KJPP lama menjadi 0 jika tidak ada dalam request
            foreach ($penawaran->penawaranKjpp as $kjpp) {
                if (!in_array($kjpp->kjpp_rekanan_id, $kjpps)) {
                    // Ubah status KJPP lama menjadi 0
                    $kjpp->status = 0;
                    $kjpp->created_by = $userId;
                    $kjpp->updated_by = $userId; // Set updated_by
                    $kjpp->save();
                }
            }

            // Tangani penambahan atau perubahan KJPP baru
            foreach ($kjpps as $kjpp) {
                $existingDetail = PenawaranDetailTender::where('penawaran_id', $penawaran->id)
                    ->where('kjpp_rekanan_id', $kjpp)
                    ->first();

                // dd($existingDetail);

                if ($existingDetail) {
                    // Jika KJPP sudah ada, pastikan statusnya aktif (1)
                    if ($existingDetail->status == 0) {
                        $existingDetail->status = 1;
                        $existingDetail->created_by = $userId;
                        $existingDetail->updated_by = $userId; // Set updated_by
                        $existingDetail->save();
                    }
                } else {
                    // Buat data baru jika tidak ada dalam database
                    PenawaranDetailTender::create([
                        'penawaran_id' => $penawaran->id,
                        'kjpp_rekanan_id' => $kjpp,
                        'status' => 1, // Default status untuk KJPP baru adalah 1
                        'created_by' => $userId, // Set created_by untuk data baru
                        'updated_by' => $userId, // Set updated_by juga
                    ]);
                }
            }

            // Commit transaksi
            DB::commit();

            return redirect()
                ->route('tender.penawaran.ulang.index')
                ->with('success', 'Data Penawaran updated successfully');
        } catch (Exception $e) {
            // Rollback jika ada kesalahan
            DB::rollBack();

            return redirect()
                ->route('tender.penawaran.createPenawaran', $noreg)
                ->with('error', 'Validation failed: ' . $e->getMessage());
        }
    }


    /**
     * Tampilkan Surat Tender
     */
    public function showSuratTender($noreg)
    {
        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();
        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

        // Kalau tidak ketemu nomor registrasi dengan tabel penawaran
        if (!$penawaran) {
            return redirect()->route('tender.penawaran.createPenawaran', ['noreg' => $noreg])
                ->with('error', 'Anda Belum Membuat Penawaran. Silahkan isi terlebih dahulu!');
        }

        if ($penawaran->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        // Kalau tidak ada dokumen jaminan maka di arahkan ke halaman dokumen jaminan
        if ($permohonan->documents->isEmpty()) {
            return redirect()->route('debitur.jaminan.create', ['id' => $permohonan->debiture->id])
                ->with('error', 'Anda Belum Membuat Dokumen Jaminan. Silahkan isi terlebih dahulu!');
        }

        foreach ($permohonan->documents as $document) {
            $village_permohonan = $document->village_code;
            $district_permohonan = $document->district_code;
            $city_permohonan = $document->city_code;
            $province_permohonan = $document->province_code;
        }

        $villages = Village::where('code', $village_permohonan)->get();
        $districts = District::where('code', $district_permohonan)->get();
        $cities = City::where('code', $city_permohonan)->get();
        $provinces = Province::where('code', $province_permohonan)->get();

        date_default_timezone_set('Asia/Jakarta');

        $now = date('Y-m-d H:i:s');
        // Jika batas tanggal penawaran sudah lewat
        if ($penawaran->end_date < $now) {
            return redirect()->route('tender.penawaran.editPenawaran', ['noreg' => $noreg])
                ->with('error', 'Sudah Kadaluarsa. Silahkan perpanjang tanggal penawaran terlebih dahulu!');
        }

        return view('lpj::penawaran.surat_tender', compact('penawaran', 'noreg', 'permohonan', 'villages', 'districts', 'cities', 'provinces'));
    }

    public function suratTenderKJPP($noreg, $id)
    {
        $kjpp = KJPP::find($id);
        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();
        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();

        if (!$penawaran) {
            return redirect()->route('tender.penawaran.createPenawaran', ['noreg' => $penawaran->nomor_registrasi])
                ->with('error', 'Anda Belum Membuat Penawaran. Silahkan isi terlebih dahulu!');
        }

        if ($penawaran->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        // Kalau tidak ada dokumen jaminan maka di arahkan ke halaman dokumen jaminan
        if ($permohonan->documents->isEmpty()) {
            return redirect()->route('debitur.jaminan.create', ['id' => $permohonan->debiture->id])
                ->with('error', 'Anda Belum Membuat Dokumen Jaminan. Silahkan isi terlebih dahulu!');
        }

        foreach ($permohonan->documents as $document) {
            $village_permohonan = $document->village_code;
            $district_permohonan = $document->district_code;
            $city_permohonan = $document->city_code;
            $province_permohonan = $document->province_code;
        }

        $villages = Village::where('code', $village_permohonan)->get();
        $districts = District::where('code', $district_permohonan)->get();
        $cities = City::where('code', $city_permohonan)->get();
        $provinces = Province::where('code', $province_permohonan)->get();

        date_default_timezone_set('Asia/Jakarta');

        $now = date('Y-m-d H:i:s');
        // Jika batas tanggal penawaran sudah lewat
        if ($penawaran->end_date < $now) {
            return redirect()->route('tender.penawaran.editPenawaran', ['noreg' => $noreg])
                ->with('error', 'Sudah Kadaluarsa. Silahkan perpanjang tanggal penawaran terlebih dahulu!');
        }

        $detail_penawaran = PenawaranDetailTender::with('kjpp')->where('kjpp_rekanan_id', '=', $kjpp->id)->get();

        foreach ($detail_penawaran as $detail) {
            $detail_penawaran_1 = $detail->kjpp;
        }

        return view('lpj::penawaran.surat_tender_kjpp', compact('penawaran', 'noreg', 'permohonan', 'villages', 'districts', 'cities', 'provinces', 'detail_penawaran_1', 'id'));
    }

    public function datatablesPenawaran(Request $request)
    {
        if (is_null($this->user) || !$this->user->can('penawaran.view')) {
            //abort(403, 'Sorry! You are not allowed to view users.');
        }

        // Retrieve data from the database
        $query = Permohonan::query()->where('status', '=', 'registered')->where('jenis_penilaian_id', '=', 2);

        // Apply search filter if provided
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('nomor_registrasi', 'LIKE', '%' . $search . '%');
                $q->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('tujuanPenilaian', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhere('status', 'LIKE', '%' . $search . '%');
            });
        }

        // Apply sorting if provided
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

        // Get the total count of records
        $totalRecords = $query->count();

        // Apply pagination if provided
        if ($request->has('page') && $request->has('size')) {
            $page   = $request->get('page');
            $size   = $request->get('size');
            $offset = ($page - 1) * $size; // Calculate the offset

            $query->skip($offset)->take($size);
        }

        // Get the filtered count of records
        $filteredRecords = $query->count();

        // Get the data for the current page
        $data = $query->with(['user', 'debiture', 'branch', 'tujuanPenilaian'])->get();

        // Calculate the page count
        $pageCount = ceil($totalRecords / $request->get('size'));

        // Calculate the current page number
        $currentPage = 0 + 1;

        // Return the response data as a JSON object
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $currentPage,
            'totalCount'      => $totalRecords,
            'data'            => $data,
        ]);
    }

    public function exportPenawaran()
    {
        return Excel::download(new PenawaranTenderExport, 'penawarantender.xlsx');
    }

    // penawaran ulang
    public function penawaran_ulang_index()
    {
        return view('lpj::penawaran_ulang/index');
    }

    public function datatablesPenawaranUlang(Request $request)
    {
        if (is_null($this->user) || !$this->user->can('penawaran_ulang.view')) {
            //abort(403, 'Sorry! You are not allowed to view users.');
        }

        // Retrieve data from the database
        $query = Permohonan::query()->where('status', '=', 'tender')->where('jenis_penilaian_id', '=', 2);

        // Apply search filter if provided
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('nomor_registrasi', 'LIKE', '%' . $search . '%');
                $q->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('tujuanPenilaian', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhere('status', 'LIKE', '%' . $search . '%');
            });
        }

        // Apply sorting if provided
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

        // Get the total count of records
        $totalRecords = $query->count();

        // Apply pagination if provided
        if ($request->has('page') && $request->has('size')) {
            $page   = $request->get('page');
            $size   = $request->get('size');
            $offset = ($page - 1) * $size; // Calculate the offset

            $query->skip($offset)->take($size);
        }

        // Get the filtered count of records
        $filteredRecords = $query->count();

        // Get the data for the current page
        $data = $query->with(['user', 'debiture', 'branch', 'tujuanPenilaian'])->get();

        // Calculate the page count
        $pageCount = ceil($totalRecords / $request->get('size'));

        // Calculate the current page number
        $currentPage = 0 + 1;

        // Return the response data as a JSON object
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $currentPage,
            'totalCount'      => $totalRecords,
            'data'            => $data,
        ]);
    }

    // Tambahkan method untuk API di controller
    public function checkPenawaranExistence($nomor_registrasi)
    {
        // Cek apakah nomor_registrasi ada dalam tabel penawaran
        $exists = PenawaranTender::where('nomor_registrasi', $nomor_registrasi)->exists();

        // Kembalikan hasil pengecekan sebagai JSON
        return response()->json(['exists' => $exists]);
    }

    public function downloadSuratTender($noreg)
    {
        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();
        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

        if ($penawaran->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        foreach ($permohonan->documents as $document) {
            $village_permohonan = $document->village_code;
            $district_permohonan = $document->district_code;
            $city_permohonan = $document->city_code;
            $province_permohonan = $document->province_code;
        }

        $villages = Village::where('code', $village_permohonan)->get();
        $districts = District::where('code', $district_permohonan)->get();
        $cities = City::where('code', $city_permohonan)->get();
        $provinces = Province::where('code', $province_permohonan)->get();

        $pdf = app('dompdf.wrapper'); // create an instance of the PDF class
        $pdf->loadView('lpj::penawaran.surat_tender_download', compact('penawaran', 'permohonan', 'villages', 'districts', 'cities', 'provinces'));

        return $pdf->download('surat_tender' . time() . '.pdf');
    }

    public function downloadSuratTenderKJPP($noreg, $id)
    {
        $kjpp = KJPP::find($id);
        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();
        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

        if ($penawaran->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        foreach ($permohonan->documents as $document) {
            $village_permohonan = $document->village_code;
            $district_permohonan = $document->district_code;
            $city_permohonan = $document->city_code;
            $province_permohonan = $document->province_code;
        }

        $villages = Village::where('code', $village_permohonan)->get();
        $districts = District::where('code', $district_permohonan)->get();
        $cities = City::where('code', $city_permohonan)->get();
        $provinces = Province::where('code', $province_permohonan)->get();

        $detail_penawaran = PenawaranDetailTender::with('kjpp')->where('kjpp_rekanan_id', '=', $kjpp->id)->get();

        foreach ($detail_penawaran as $detail) {
            $detail_penawaran_1 = $detail->kjpp;
        }

        $pdf = app('dompdf.wrapper'); // create an instance of the PDF class
        $pdf->loadView('lpj::penawaran.surat_tender_kjpp_download', compact('penawaran', 'permohonan', 'villages', 'districts', 'cities', 'provinces', 'detail_penawaran_1'));

        return $pdf->download('surat_tender_kjpp' . time() . '.pdf');
    }

    // Kirim Email
    public function showKirimEmail($noreg)
    {
        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();
        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

        if (!$penawaran) {
            return redirect()->route('tender.penawaran.createPenawaran', ['noreg' => $noreg])
                ->with('error', 'Anda Belum Membuat Penawaran. Silahkan isi terlebih dahulu!');
        }

        if ($penawaran->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        if ($permohonan->documents->isEmpty()) {
            return redirect()->route('debitur.jaminan.create', ['id' => $permohonan->debiture->id])
                ->with('error', 'Anda Belum Membuat Dokumen Jaminan. Silahkan isi terlebih dahulu!');
        }

        return view('lpj::penawaran.showKirimEmail', compact('penawaran', 'permohonan', 'noreg'));
    }

    public function dataTablesShowKirimSurat(Request $request, $noreg)
    {
        if (is_null($this->user) || !$this->user->can('penawaran.view')) {
            // abort(403, 'Sorry! You are not allowed to view users.');
        }

        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();

        // Retrieve data from the database
        $query = PenawaranDetailTender::query()->where('penawaran_id', '=', $penawaran->id)->with(['kjpp', 'penawaran', 'penawaran.emailTenderLog']);

        // dd($query);

        // Apply sorting if provided
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order = $request->get('sortOrder');
            $column = $request->get('sortField');

            // Handle sorting for related table columns
            if ($column === 'nama_kjpp') {
                // Join with the KJPP table and sort by the name column
                $query->join('kjpp', 'detail_penawaran.kjpp_rekanan_id', '=', 'kjpp.id')
                    ->orderBy('kjpp.name', $order)
                    ->select('detail_penawaran.*'); // Select only the main table columns to avoid conflicts
            } else if ($column === 'nomor_kjpp') {
                $query->join('kjpp', 'detail_penawaran.kjpp_rekanan_id', '=', 'kjpp.id')
                    ->orderBy('kjpp.code', $order)
                    ->select('detail_penawaran.*');
            } else {
                // Sort by columns in the main table
                $query->orderBy($column, $order);
            }
        }

        // Get the data for the current page
        $data = $query->get();

        // add column "No"
        $i = 0;
        $j = 1;
        foreach ($data as $obj) {

            // tanggal_permohonan
            $data[$i]->numbernya = $j;
            $i++;
            $j++;
        }

        // Return the response data as a JSON object
        return response()->json([
            'draw'            => $request->get('draw'),
            'data'            => $data,
        ]);
    }

    public function kirimEmailAll($noreg)
    {
        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();
        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

        if (!$penawaran) {
            return redirect()->route('tender.penawaran.createPenawaran', ['noreg' => $noreg])
                ->with('error', 'Anda Belum Membuat Penawaran. Silahkan isi terlebih dahulu!');
        }

        if ($penawaran->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        if ($permohonan->documents->isEmpty()) {
            return redirect()->route('debitur.jaminan.create', ['id' => $permohonan->debiture->id])
                ->with('error', 'Anda Belum Membuat Dokumen Jaminan. Silahkan isi terlebih dahulu!');
        }

        $detail_penawaran = PenawaranDetailTender::where('penawaran_id', '=', $penawaran->id)->get();


        foreach ($detail_penawaran as $detail) {
            $this->kirimEmailKJPP($noreg, $detail->kjpp_rekanan_id);
        }

        $detail_penawaran = PenawaranDetailTender::where('penawaran_id', '=', $penawaran->id)
            ->where('status', '=', 1)
            ->pluck('kjpp_rekanan_id')
            ->toArray();


        $kjpps = KJPP::whereIn('id', $detail_penawaran)
            ->get()
            ->map(function ($item) {
                $emails = collect(explode(',', $item->email_kantor))->filter()->unique();

                // Parse JSON string jika ada dan tidak kosong
                if (!empty($item->detail_email_kantor) && $item->detail_email_kantor !== '[]') {
                    $detail_emails = json_decode($item->detail_email_kantor, true);
                    if (is_array($detail_emails)) {
                        foreach ($detail_emails as $detail) {
                            if (is_array($detail) && isset($detail['email_kantor'])) {
                                $emails->push($detail['email_kantor']);
                            } elseif (is_string($detail)) {
                                $emails->push($detail);
                            }
                        }
                    }
                }

                return [
                    'kjpp' => $item,
                    'emails' => array_filter($emails->unique()->values()->all())
                ];
            });


        foreach ($permohonan->documents as $document) {
            $village_permohonan = $document->village_code;
            $district_permohonan = $document->district_code;
            $city_permohonan = $document->city_code;
            $province_permohonan = $document->province_code;
        }

        $villages = Village::where('code', $village_permohonan)->get();
        $districts = District::where('code', $district_permohonan)->get();
        $cities = City::where('code', $city_permohonan)->get();
        $provinces = Province::where('code', $province_permohonan)->get();
        $user = auth::user();

        $subject = 'Send Penawaran Email';

        $body_pdf = view('lpj::penawaran.kirimEmail', [
            'penawaran' => $penawaran,
            'permohonan' => $permohonan,
            'kjpps' => $kjpps->pluck('emails')->flatten()->toArray(),
            'villages' => $villages,
            'districts' => $districts,
            'cities' => $cities,
            'provinces' => $provinces,
            'user' => $user,
        ])->render();

        // Dispatch job untuk mengirim email
        // SendPenawaranTenderJob::dispatch(
        //     $kjpps->pluck('emails')->flatten()->toArray(),
        //     $penawaran,
        //     $permohonan,
        //     $villages,
        //     $districts,
        //     $cities,
        //     $provinces,
        //     $user
        // );

        try {
            // Proses log email untuk setiap KJPP
            foreach ($kjpps as $kjppData) {
                foreach ($kjppData['emails'] as $email) {
                    // Cek log yang sudah ada
                    $log = PenawaranEmailTenderLog::where('penawaran_id', $penawaran->id)
                        ->where('to_email', $email)
                        ->where('status', 'failed')
                        ->first();

                    $log1 = PenawaranEmailTenderLog::where('penawaran_id', $penawaran->id)
                        ->where('to_email', $email)
                        ->where('status', 'success')
                        ->first();

                    if ($log) {
                        // Update log failed menjadi success
                        $log->update([
                            'penawaran_id' => $penawaran->id,
                            'kjpp' => $kjppData['kjpp']->code . ' | ' . $kjppData['kjpp']->name,
                            'to_email' => $email,
                            'subject' => $subject,
                            'body_pdf' => $body_pdf,
                            'status' => 'success',
                            'error_message' => null,
                            'updated_at' => now(),
                        ]);
                    } else if ($log1) {
                        // Update timestamp jika sudah success
                        $log1->update([
                            'penawaran_id' => $penawaran->id,
                            'kjpp' => $kjppData['kjpp']->code . ' | ' . $kjppData['kjpp']->name,
                            'to_email' => $email,
                            'subject' => $subject,
                            'body_pdf' => $body_pdf,
                            'updated_at' => now(),
                        ]);
                    } else {
                        // Buat log baru
                        PenawaranEmailTenderLog::create([
                            'penawaran_id' => $penawaran->id,
                            'kjpp' => $kjppData['kjpp']->code . ' | ' . $kjppData['kjpp']->name,
                            'to_email' => $email,
                            'subject' => $subject,
                            'body_pdf' => $body_pdf,
                            'status' => 'success',
                            'error_message' => null,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }
                }
            }

            return redirect()->back()
                ->with('success', 'Email Penawaran Berhasil Terkirim!');
        } catch (\Exception $e) {
            // Log email gagal untuk setiap KJPP
            foreach ($kjpps as $kjppData) {
                foreach ($kjppData['emails'] as $email) {
                    $log = PenawaranEmailTenderLog::where('penawaran_id', $penawaran->id)
                        ->where('to_email', $email)
                        ->where('status', 'success')
                        ->first();

                    $log1 = PenawaranEmailTenderLog::where('penawaran_id', $penawaran->id)
                        ->where('to_email', $email)
                        ->where('status', 'failed')
                        ->first();

                    if ($log) {
                        // Update log success menjadi failed
                        $log->update([
                            'penawaran_id' => $penawaran->id,
                            'kjpp' => $kjppData['kjpp']->code . ' | ' . $kjppData['kjpp']->name,
                            'to_email' => $email,
                            'subject' => $subject,
                            'body_pdf' => $body_pdf,
                            'status' => 'failed',
                            'error_message' => $e->getMessage(),
                            'updated_at' => now(),
                        ]);
                    } else if ($log1) {
                        // Update error message jika sudah failed
                        $log1->update([
                            'penawaran_id' => $penawaran->id,
                            'kjpp' => $kjppData['kjpp']->code . ' | ' . $kjppData['kjpp']->name,
                            'to_email' => $email,
                            'subject' => $subject,
                            'body_pdf' => $body_pdf,
                            'error_message' => $e->getMessage(),
                            'updated_at' => now(),
                        ]);
                    } else {
                        // Buat log baru dengan status failed
                        PenawaranEmailTenderLog::create([
                            'penawaran_id' => $penawaran->id,
                            'kjpp' => $kjppData['kjpp']->code . ' | ' . $kjppData['kjpp']->name,
                            'to_email' => $email,
                            'subject' => $subject,
                            'body_pdf' => $body_pdf,
                            'status' => 'failed',
                            'error_message' => $e->getMessage(),
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }
                }
            }

            return redirect()->back()
                ->with('error', 'Email Penawaran Gagal Terkirim!');
        }
    }

    public function kirimEmailKJPP($noreg, $id)
    {
        $penawaran = PenawaranTender::where('nomor_registrasi', '=', $noreg)->first();
        $permohonan = Permohonan::where('nomor_registrasi', '=', $noreg)->first();

        if (!$penawaran) {
            return redirect()->route('tender.penawaran.createPenawaran', ['noreg' => $noreg])
                ->with('error', 'Anda Belum Membuat Penawaran. Silahkan isi terlebih dahulu!');
        }

        if ($penawaran->status != 'tender') {
            return redirect()->route('otorisasitender.penawaran.index')->with('error', 'Penawaran dengan nomor registrasi ini sudah masuk Otorisasi Tender tidak bisa masuk penawaran lagi!');
        }

        if ($permohonan->documents->isEmpty()) {
            return redirect()->route('debitur.jaminan.create', ['id' => $permohonan->debiture->id])
                ->with('error', 'Anda Belum Membuat Dokumen Jaminan. Silahkan isi terlebih dahulu!');
        }

        $detail_penawaran = PenawaranDetailTender::with('kjpp')->where('kjpp_rekanan_id', '=', $id)->pluck('kjpp_rekanan_id')->toArray();
        $kjpps = KJPP::whereIn('id', $detail_penawaran)
                     ->get()
                     ->map(function ($item) {
                         $emails = collect(explode(',', $item->email_kantor))->filter()->unique();

                         // Parse JSON string jika ada dan tidak kosong
                         if (!empty($item->detail_email_kantor) && $item->detail_email_kantor !== '[]') {
                             $detail_emails = json_decode($item->detail_email_kantor, true);
                             if (is_array($detail_emails)) {
                                 foreach ($detail_emails as $detail) {
                                     if (is_array($detail) && isset($detail['email_kantor'])) {
                                         $emails->add($detail['email_kantor']);
                                     } elseif (is_string($detail)) {
                                         $emails->add($detail);
                                     }
                                 }
                             }
                         }

                         return array_filter(array_values(iterator_to_array($emails)));
                     })
                     ->flatten()
                     ->unique()
                     ->values()
                     ->toArray();

        $dp1 = PenawaranDetailTender::with('kjpp')->where('kjpp_rekanan_id', '=', $id)->first();

        foreach ($permohonan->documents as $document) {
            $village_permohonan = $document->village_code;
            $district_permohonan = $document->district_code;
            $city_permohonan = $document->city_code;
            $province_permohonan = $document->province_code;
        }

        $villages = Village::where('code', $village_permohonan)->get();
        $districts = District::where('code', $district_permohonan)->get();
        $cities = City::where('code', $city_permohonan)->get();
        $provinces = Province::where('code', $province_permohonan)->get();
        $user = auth()->user();

        $subject = 'Send Penawaran Email';

        $body_pdf = view('lpj::penawaran.kirimEmailKJPP', [
            'dp1' => $dp1,
            'penawaran' => $penawaran,
            'permohonan' => $permohonan,
            'kjpps' => $kjpps,
            'villages' => $villages,
            'districts' => $districts,
            'cities' => $cities,
            'provinces' => $provinces,
            'user' => $user,
        ])->render();

        SendPenawaranKJPPTenderJob::dispatch(
            $kjpps,
            $dp1,
            $penawaran,
            $permohonan,
            $villages,
            $districts,
            $cities,
            $provinces,
            $user
        );

        try {
            // Proses log email
            foreach ($kjpps as $email) {
                // Cek apakah sudah ada log dengan status 'failed' untuk email ini
                $log = PenawaranEmailTenderLog::where('penawaran_id', $penawaran->id)
                    ->where('to_email', $email)
                    ->where('status', 'failed')
                    ->first();

                $log1 = PenawaranEmailTenderLog::where('penawaran_id', $penawaran->id)
                    ->where('to_email', $email)
                    ->where('status', 'success')
                    ->first();

                if ($log) {
                    // Jika log ditemukan dan statusnya 'failed', update status menjadi 'success'
                    $log->update([
                        'penawaran_id' => $penawaran->id,
                        'kjpp' => $dp1->kjpp->code . ' | ' . $dp1->kjpp->name,
                        'to_email' => $email,
                        'subject' => $subject,
                        'body_pdf' => $body_pdf,
                        'status' => 'success',
                        'error_message' => null, // Reset error_message saat status diubah menjadi success
                        'updated_at' => now(),
                    ]);
                } else if ($log1) {
                    // Jika log ditemukan dan statusnya 'success' biarkan saja
                    $log1->update([
                        'penawaran_id' => $penawaran->id,
                        'kjpp' => $dp1->kjpp->code . ' | ' . $dp1->kjpp->name,
                        'to_email' => $email,
                        'subject' => $subject,
                        'body_pdf' => $body_pdf,
                        'updated_at' => now(),
                    ]);
                } else {
                    // Jika tidak ada log gagal, buat log baru dengan status 'success'
                    PenawaranEmailTenderLog::create([
                        'penawaran_id' => $penawaran->id,
                        'kjpp' => $dp1->kjpp->code . ' | ' . $dp1->kjpp->name,
                        'to_email' => $email,
                        'subject' => $subject,
                        'body_pdf' => $body_pdf,
                        'status' => 'success',
                        'error_message' => null, // Tidak ada error message
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }

            return redirect()->back()->with('success', 'Email Penawaran Berhasil Terkirim!');
        } catch (\Exception $e) {
            // Log email gagal
            foreach ($kjpps as $email) {
                $log = PenawaranEmailTenderLog::where('penawaran_id', $penawaran->id)
                    ->where('to_email', $email)
                    ->where('status', 'success')
                    ->first();

                $log1 = PenawaranEmailTenderLog::where('penawaran_id', $penawaran->id)
                    ->where('to_email', $email)
                    ->where('status', 'failed')
                    ->first();

                if ($log) {
                    // Jika log ditemukan dan statusnya 'success', update status menjadi 'failed'
                    $log->update([
                        'penawaran_id' => $penawaran->id,
                        'kjpp' => $dp1->kjpp->code . ' | ' . $dp1->kjpp->name,
                        'to_email' => $email,
                        'subject' => $subject,
                        'body_pdf' => $body_pdf,
                        'status' => 'failed',
                        'error_message' => $e->getMessage(),
                        'updated_at' => now(),
                    ]);
                } else if ($log1) {
                    // Jika log ditemukan dan statusnya 'failed' biarkan saja
                    $log1->update([
                        'penawaran_id' => $penawaran->id,
                        'kjpp' => $dp1->kjpp->code . ' | ' . $dp1->kjpp->name,
                        'to_email' => $email,
                        'subject' => $subject,
                        'body_pdf' => $body_pdf,
                        'error_message' => $e->getMessage(),
                        'updated_at' => now(),
                    ]);
                } else {
                    PenawaranEmailTenderLog::create([
                        'penawaran_id' => $penawaran->id,
                        'kjpp' => $dp1->kjpp->code . ' | ' . $dp1->kjpp->name,
                        'to_email' => $email,
                        'subject' => $subject,
                        'body_pdf' => $body_pdf,
                        'status' => 'failed',
                        'error_message' => $e->getMessage(),
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }

            return redirect()->back()->with('error', 'Email Penawaran Gagal Terkirim!');
        }
    }
}
