<?php

namespace Modules\Lpj\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Exception;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Modules\Lpj\Http\Requests\ProsesPenawaranRequest;
use Modules\Lpj\Models\JenisLaporan;
use Modules\Lpj\Models\KJPP;
use Modules\Lpj\Models\PenawaranDetailTender;
use Modules\Lpj\Models\PenawaranDetailTenderLog;
use Modules\Lpj\Models\PenawaranTender;

use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Models\StatusPermohonan;
use Modules\Lpj\Models\TujuanPenilaian;
use Modules\Lpj\Models\TujuanPenilaianKJPP;

class ProsesPenawaranController extends Controller
{
    public $user;

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

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

        // Retrieve data from the database
        // $query = PenawaranTender::query()->whereIn('status', ['tender', 'proposal-tender'])->withCount('penawarandetails');

        // penawaran need union with permohonan
        $query = PenawaranTender::query()->whereIn('penawaran.status', ['tender', 'proposal-tender'])
                    ->select('penawaran.id',
                             'penawaran.nomor_registrasi',
                             'penawaran.code as penawaran_code',
                             'penawaran.start_date',
                             'penawaran.end_date',
                             'penawaran.status as statusnya',
                             'debitures.name as debitures_name',
                             'permohonan.tanggal_permohonan',
                             'users.name as user_pemohon',
                             'branches.name as branches_name',
                             'tujuan_penilaian.name as tujuan_penilaian_name',
                             'tujuan_penilaian_kjpp.name as tujuan_penilaian_kjpp_name'
                             )
                    ->withCount('penawarandetails')
                    ->leftJoin('permohonan', 'permohonan.nomor_registrasi', '=', 'penawaran.nomor_registrasi')
                    ->leftJoin('users', 'users.id', '=', 'permohonan.user_id')
                    ->leftJoin('branches', 'branches.id', '=', 'permohonan.branch_id')
                    ->leftJoin('tujuan_penilaian', 'tujuan_penilaian.id','=','permohonan.tujuan_penilaian_id')
                    ->leftJoin('debitures', 'debitures.id', '=', 'permohonan.debiture_id')
                    ->leftJoin('tujuan_penilaian_kjpp', 'tujuan_penilaian_kjpp.id', '=', 'penawaran.tujuan_penilaian_kjpp_id');

        $permohonanQuery = Permohonan::whereIn('permohonan.status', ['registered'])->where('permohonan.jenis_penilaian_id', '=', 2)
                    ->select('permohonan.id',
                            'permohonan.nomor_registrasi',
                             DB::raw('"" as penawaran_code'),
                             DB::raw('"" as start_date'),
                             DB::raw('"" as end_date'),
                             'permohonan.status as statusnya',
                            'debitures.name as debitures_name',
                            'permohonan.tanggal_permohonan',
                            'users.name as user_pemohon',
                            'branches.name as branches_name',
                            'tujuan_penilaian.name as tujuan_penilaian_name',
                            DB::raw('"" as tujuan_penilaian_kjpp_name'),
                            DB::raw('"-" as penawarandetails_count'))
                    ->leftJoin('users', 'users.id', '=', 'permohonan.user_id')
                    ->leftJoin('branches', 'branches.id', '=', 'permohonan.branch_id')
                    ->leftJoin('debitures', 'debitures.id', '=', 'permohonan.debiture_id')
                    ->leftJoin('tujuan_penilaian', 'tujuan_penilaian.id','=','permohonan.tujuan_penilaian_id');
        $query->union($permohonanQuery);
        // penawaran need union with permohonan

        // 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('penawaran.nomor_registrasi', 'LIKE', '%' . $search . '%');
                //$q->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%');
                //$q->orWhereRelation('tujuanPenilaianKJPP', '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(['tujuanPenilaianKjpp','permohonan','permohonan.debiture'])->get();
        $data = $query->get();

        // format date
        $i = 0;
        foreach ($data as $obj) {

            // tanggal_permohonan
            if ($obj->tanggal_permohonan) {
                $data[$i]->tanggal_permohonan = Carbon::parse($obj->tanggal_permohonan)->format('d M Y');
            }

            // date_range
            $data[$i]->date_range = "-";
            if ($obj->start_date && $obj->end_date)
            {
                $data[$i]->date_range = Carbon::parse($obj->start_date)->format('d M Y') . ' - ' .
                                        Carbon::parse($obj->end_date)->format('d M Y');
            }

            $i++;
        }
        // format date

        // 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 edit($id)
    {
        // $id => penawaran.id
        return view('lpj::prosespenawaran.edit', compact('id'));
    }

    public function setData(Request $request): JsonResponse
    {
        $data = array();
        $penawaran = array();
        $penawrandetails = array();

        if (request()->ajax()) {
            $id = $request->id;
            $penawaran = PenawaranTender::with('permohonan.debiture')->find($id);
            $penawrandetails = PenawaranDetailTender::where('penawaran_id','=',$id)
                                ->leftJoin('kjpp', 'kjpp.id', '=', 'detail_penawaran.kjpp_rekanan_id')
                                ->select('detail_penawaran.*', 'kjpp.code AS kjpp_code', 'kjpp.name AS kjpp_name')
                                ->where('detail_penawaran.status','=',1)
                                ->get();

            if ($penawaran) {
                $i=0;
                foreach($penawrandetails as $obj)
                {
                    if($obj->dokumen_persetujuan && Storage::disk('public')->exists($obj->dokumen_persetujuan))
                    {
                        $penawrandetails_path = Storage::url($obj->dokumen_persetujuan);
                        $penawrandetails[$i]['dokumen_persetujuan']=$penawrandetails_path;
                    }
                    $i++;
                }
                DB::enableQueryLog();
                $kjpps = KJPP::whereNotIn('id', function($query) use ($id) {
                                $query->select('kjpp_rekanan_id')
                                    ->from('detail_penawaran')
                                    ->where('penawaran_id', '=', $id)
                                    ->where('status','=',1); // status=1 (masih aktif)
                            })
                            ->select('id', 'name', 'code')  // Pilih beberapa kolom sekaligus
                            ->get();
                $sql=DB::getQueryLog();
                $data['sql'] = $sql;
                $data['kjpps'] = $kjpps;
                $data['penawaran'] = $penawaran;
                $data['penawrandetails'] = $penawrandetails;
                $data['status'] = 'success';
                $data['message'] ['message_success'] = array("data successfully found");
            } else {
                $data['penawaran'] = null;
                $data['penawrandetails'] = null;
                $data['status'] = 'error';
                $data['message'] ['message_data'] = array("data not found");
            }
        } else {
            $data['status'] = 'error';
            $data['message'] ['message_ajax'] = array("no ajax request");
        }

        return response()->json($data);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id): JsonResponse
    {
        // $id => detail_penawaran.id
        // init
        $data = array();
        $dataPenawaranDetail = array();
        if (request()->ajax()) {

            $penawarandetail = PenawaranDetailTender::find($id);
            // cek masa aktif penawaran
            $checkActiveDateRange = checkActiveDateRangePenawaran($penawarandetail->penawaran_id);
            // cek status (penawaran.status = tender)
            $penawaran = PenawaranTender::find($penawarandetail->penawaran_id);
            if($checkActiveDateRange && ('tender'==$penawaran->status))
            {
                try {

                    $dataPenawaranDetail = ['updated_by' => Auth::id(),
                                'updated_at' => now(),
                                'no_proposal' => $request->no_proposal,
                                'tgl_proposal' => $request->tgl_proposal,
                                'biaya_penawaran' => str_replace(".","",$request->biaya_penawaran)
                            ];

                    if ($request->hasFile('dokumen_persetujuan'))
                    {
                        $file_tmp = $request->file('dokumen_persetujuan');
                        $folderPath = 'uploads/penawaran/';
                        if ($file_tmp->isValid())
                        {
                            $myFile=$file_tmp->getClientOriginalName(); // nama file with extension
                            $file_name = pathinfo($myFile, PATHINFO_FILENAME); // nama file without extension

                            $extension = $file_tmp->getClientOriginalExtension();
                            // kjppID_penawaranID_namaFile_userID_time
                            $newFileName = $request->kjpp_rekanan_id.'_'.$id.'_'.$file_name.'_'.Auth::user()->id."_".time() .'.'. $extension;
                            Storage::disk('public')->put($folderPath.'/'.$newFileName,file_get_contents($file_tmp));

                            $newFileNameWithPath = $folderPath . $newFileName;
                            $dataPenawaranDetail['attachment'] = $myFile;
                            $dataPenawaranDetail['dokumen_persetujuan'] = $newFileNameWithPath;
                        }
                        else
                        {
                            $data['status'] = 'error';
                            $data['message'] ['check_file_jenis'] = array("Silahkan upload file pdf");
                        }
                    }

                    $penawarandetail = PenawaranDetailTender::findOrFail($id);
                    $penawarandetail->update($dataPenawaranDetail);

                    $data['detailpenawaran_id'] = $id;
                    $data['status'] = 'success';
                    $data['message'] ['message_success'] = array('Proses Penawarn KJPP successfully');
                } catch (Exception $e) {

                    $data['status'] = 'error';
                    $data['message'] ['message_error_try_catch'] = array('Proses Penawarn KJPP failed.');
                }
            }
            else
            {
                $data['status'] = 'error';
                $data['message']['active_date_range'] = array("Penawaran sudah di tutup");
            }

        } else {
            $data['status'] = 'error';
            $data['message'] ['message_ajax'] = array("no ajax request");
        }

        return response()->json($data);
    }

    public function rulesEditnya($request, $id)
    {
        $validateIt = [
            // 'name' diambil dari definisi parameter yang di kirim pada POST Data
            'biaya_penawaran' => 'required',
            'dokumen_persetujuan' => 'required|file|mimes:pdf'
        ];

        $messageIt = [
            'biaya_penawaran.required' => 'Silahkan isi Biaya Penawaran',
            'dokumen_persetujuan.required' => 'Silahkan isi dokumen',
            'dokumen_persetujuan.file' => 'Silahkan isi file',
            'dokumen_persetujuan.mimes' => 'Silahkan upload pdf'
        ];

        $validator = Validator::make($request->all(), $validateIt, $messageIt);

        $data['fails'] = $validator->fails();
        $data['errors'] = $validator->errors();

        return $data;
    }

    /**
     * Update the specified resource in storage.
     */
    public function updateAll(Request $request, $id): JsonResponse
    {
        //  $id = penawaran.id
         // init
         $data = array();
         $dataPermohonan = array();
         $dataPenawaran = array();

         // cek masa aktif penawaran
        $checkActiveDateRange = checkActiveDateRangePenawaran($id);
        // cek status (penawaran.status = tender)
        $penawaran = PenawaranTender::find($id);
        if($checkActiveDateRange && ('tender'==$penawaran->status))
         {

             $checkKelengkapanDetailKJPP = checkKelengkapanDetailKJPP($id);
             if($checkKelengkapanDetailKJPP)
             {
                 DB::beginTransaction();
                 try {
                     $_updatestatus = ['status' => 'proposal-tender',
                         'updated_by' => Auth::id(),
                         'updated_at' => now()
                     ];

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

                     $penawaran->update($_updatestatus);
                     $permohonan->update($_updatestatus);

                     DB::commit();

                     $data['message'] ['message_success'] = array('Sukses melakukan Proses Penawaran');
                     $data['status'] = 'success';

                 } catch (Exception $e) {
                     DB::rollBack();
                     // dd($e);
                     $data['message'] ['message_error_try_catch'] = array("Gagal melakukan Proses Penawaran");
                     $data['status'] = 'error';
                 }

             }
             else
             {
                 $data['message'] ['cek_kelengkapan_data'] = array("Silahkan lengkapi data KJPP");
                 $data['status'] = 'error';
             }

         }
         else
         {
             $data['message'] ['active_date_range'] = array("Penawaran sudah di tutup");
             $data['status'] = 'error';
         }

         return response()->json($data);
    }

    public function updateKJPPStatus(Request $request, $id): JsonResponse
    {
        // $id => detail_penawaran.id
        // init
        $data = array();
        $dataDetailPenawaran = array();

        $detailpenawaran = PenawaranDetailTender::find($id);
        // cek masa aktif penawaran
        $checkActiveDateRange = checkActiveDateRangePenawaran($detailpenawaran->penawaran_id);
        // cek status (penawaran.status = tender)
        $penawaran = PenawaranTender::find($detailpenawaran->penawaran_id);
        if($checkActiveDateRange && ('tender'==$penawaran->status))
        {
            try {

                // $data['id']=$id;

                $dataDetailPenawaran = ['status' => '0',
                    'updated_by' => Auth::id(),
                    'updated_at' => now()
                ];

                $detailpenawaran->update($dataDetailPenawaran);

                $data['status'] = 'success';
                $data['message'] ['message_success'] = array('Sukses delete Penawaran KJPP '.$request->kjppName);
            } catch (Exception $e) {

                $data['status'] = 'error';
                $data['message'] ['message_error'] = array("Gagal delete Penawaran KJPP ".$request->kjppName);
            }
        }
        else
        {
            $data['status'] = 'error';
            $data['message']['message_error'] = array("Penawaran sudah di tutup");
        }

        return response()->json($data);
    }

    public function show($id)
    {
        $prosespenawaran  = PenawaranTender::find($id);
        $permohonan = "";
        if($prosespenawaran){
            $permohonan = Permohonan::where('nomor_registrasi',$prosespenawaran->nomor_registrasi)->first();
        }
        return view('lpj::prosespenawaran.show', compact('id', 'prosespenawaran','permohonan'));
    }

    public function updateDraft(Request $request, $id): JsonResponse
    {
        // $id = penawaran.id
        // init
        $data = array();
        $dataPenawaranDetail = array();
        $failed = 0;

        // cek masa aktif penawaran
        $checkActiveDateRange = checkActiveDateRangePenawaran($id);
        // cek status (penawaran.status = tender)
        $penawaran = PenawaranTender::find($id);
        if($checkActiveDateRange && ('tender'==$penawaran->status))
        {
            DB::beginTransaction();
            try
            {
                // update detail_penawaran
                $detail_penawaran_ids = $request->input('prosespenawaran_penawarandetail_id', []);
                $no_proposals = $request->input('prosespenawaran_no_proposal', []);
                $tgl_proposals = $request->input('prosespenawaran_tgl_proposal', []);
                $biaya_penawarans = $request->input('prosespenawaran_biayaPenawaran', []);
                $dokumen_penawarans = $request->file('prosespenawaran_dokumenPersetujuan');

                $tot_kjpp = sizeof($detail_penawaran_ids);
                if($tot_kjpp>0)
                {
                    // loop
                    for($i=0;$i<$tot_kjpp;$i++)
                    {
                        $detail_penawaran_id= $detail_penawaran_ids[$i];
                        $dataPenawaranDetail  = [
                            'no_proposal' => $no_proposals[$i],
                            'tgl_proposal' => $tgl_proposals[$i],
                            'biaya_penawaran' => str_replace(".","",$biaya_penawarans[$i]), // 'biaya_penawaran' => str_replace(".","",$request->biaya_penawaran)
                            'updated_by' => Auth::id(),
                            'updated_at' => now(),
                        ];

                        $penawarandetail = PenawaranDetailTender::find($detail_penawaran_id);
                        if ($dokumen_penawarans)
                        {
                            if (is_array($dokumen_penawarans) && array_key_exists($i, $dokumen_penawarans))
                            {
                                $file_tmp = $dokumen_penawarans[$i];
                                if($file_tmp->isValid())
                                {
                                    $folderPath = 'uploads/penawaran/';

                                    $myFile=$file_tmp->getClientOriginalName(); // nama file with extension
                                    $file_name = pathinfo($myFile, PATHINFO_FILENAME); // nama file without extension

                                    $extension = $file_tmp->getClientOriginalExtension();
                                    // kjppID_penawaranID_namaFile_userID_time
                                    $newFileName = $penawarandetail->kjpp_rekanan_id.'_'.$penawarandetail->penawaran_id.'_'.$file_name.'_'.Auth::user()->id."_".time() .'.'. $extension;
                                    Storage::disk('public')->put($folderPath.'/'.$newFileName,file_get_contents($file_tmp));

                                    $newFileNameWithPath = $folderPath . $newFileName;
                                    $dataPenawaranDetail['attachment'] = $myFile;
                                    $dataPenawaranDetail['dokumen_persetujuan'] = $newFileNameWithPath;
                                }

                            }

                        }

                        $checkStatus = $penawarandetail->update($dataPenawaranDetail);
                        if(!$checkStatus)
                            $failed++;
                    }

                    if($failed>0)
                    {
                        DB::rollBack();
                        $data['status'] = 'error';
                        $data['message'] ['message_error'] = array('Proses Draft Penawaran KJPP failed');
                    }
                    else
                    {
                        DB::commit();
                        $data['status'] = 'success';
                        $data['message'] ['message_success'] = array('Proses Draft Penawaran KJPP successfully');
                    }

                }
                else
                {
                    $data['status'] = 'error';
                    $data['message'] ['message_error'] = array('Data inti tidak ada.');
                }

            }
            catch (Exception $e)
            {
                // dd($e);
                DB::rollBack();
                $data['status'] = 'error';
                $data['message'] ['message_error_try_catch'] = array('Proses Draft Penawaran KJPP failed.');
            }
        }
        else
        {
            $data['status'] = 'error';
            $data['message']['active_date_range'] = array("Penawaran sudah di tutup");
        }

        return response()->json($data);
    }

    public function store(Request $request): JsonResponse
    {
        // init
        $data = array();
        // $data['request']=$request->all();
        $dataPenawaranDetail = array();
        // cek masa aktif penawaran
        $checkActiveDateRange = checkActiveDateRangePenawaran($request->penawaran_id);
        // cek status (penawaran.status = tender)
        $penawaran = PenawaranTender::find($request->penawaran_id);
        if($checkActiveDateRange && ('tender'==$penawaran->status))
        {
            try
            {
                $dataPenawaranDetail  = [
                    'penawaran_id' => $request->penawaran_id,
                    'kjpp_rekanan_id' => $request->kjpp_id,
                    'created_by' => Auth::id(),
                    'created_at' => Carbon::now()
                ];

                PenawaranDetailTender::create($dataPenawaranDetail);

                $data['status'] = 'success';
                $data['message'] ['message_success'] = array('Proses Tambah KJPP successfully');
            }
            catch (Exception $e)
            {
                // dd($e);
                $data['status'] = 'error';
                $data['message'] ['message_error_try_catch'] = array('Proses Tambah KJPP failed.');
            }
        }
        else
        {
            $data['status'] = 'error';
            $data['message']['active_date_range'] = array("Penawaran sudah di tutup");
        }

        return response()->json($data);
    }

    public function editulang($id)
    {
        // id ==> penawaran.id
        return view('lpj::prosespenawaran.editulang', compact('id'));
    }

    public function setDataUlang(Request $request): JsonResponse
    {
        $data = array();
        $penawaran = array();
        $penawrandetails = array();

        if (request()->ajax()) {
            $id = $request->id;
            $penawaran = PenawaranTender::with('permohonan.debiture')->where('status','=','proposal-tender')->find($id);

            if ($penawaran) {
                $penawrandetails = PenawaranDetailTender::where('penawaran_id','=',$id)
                                ->leftJoin('kjpp', 'kjpp.id', '=', 'detail_penawaran.kjpp_rekanan_id')
                                ->select('detail_penawaran.*', 'kjpp.code AS kjpp_code', 'kjpp.name AS kjpp_name')
                                ->where('detail_penawaran.status','=',1)
                                ->get();

                $i=0;
                foreach($penawrandetails as $obj)
                {
                    if($obj->dokumen_persetujuan && Storage::disk('public')->exists($obj->dokumen_persetujuan))
                    {
                        $penawrandetails_path = Storage::url($obj->dokumen_persetujuan);
                        $penawrandetails[$i]['dokumen_persetujuan']=$penawrandetails_path;
                    }
                    $i++;
                }

                $penawaranString = "";
                if($penawaran->status)
                {
                    $penawaranString = convertSlug($penawaran->status);
                    $penawaran->status = $penawaranString;
                }

                $kjpps = KJPP::whereNotIn('id', function($query) use ($id) {
                            $query->select('kjpp_rekanan_id')
                                ->from('detail_penawaran')
                                ->where('penawaran_id', '=', $id)
                                ->where('status','=',1); // status=1 (masih aktif)
                        })
                        ->select('id', 'name', 'code')  // Pilih beberapa kolom sekaligus
                        ->get();

                $data['kjpps'] = $kjpps;
                $data['penawaran'] = $penawaran;
                $data['penawrandetails'] = $penawrandetails;
                $data['status'] = 'success';
                $data['message']['message_success'] = array("data successfully found");
            } else {
                $data['status'] = 'error';
                $data['penawaran'] = null;
                $data['penawrandetails'] = null;
                $data['message']['message_data'] = array("data not found");
            }
        } else {
            $data['status'] = 'error';
            $data['message']['message_ajax'] = array("no ajax request");
        }

        return response()->json($data);
    }

    public function updateKJPPStatusUlang(Request $request, $id): JsonResponse
    {
        // message menggunakan SweetAlert2
        // init
        $data = array();
        $dataDetailPenawaran = array();
        // cek masa aktif penawaran
        $detailpenawaran  = PenawaranDetailTender::find($id);
        $checkActiveDateRange = checkActiveDateRangePenawaran($detailpenawaran->penawaran_id);
        // cek masa aktif penawaran

        // cek apakah blm di approve (penawaran.status = proposal-tender)
        $penawaran = PenawaranTender::find($detailpenawaran->penawaran_id);
        // cek apakah blm di approve (penawaran.status = proposal-tender)
        if($checkActiveDateRange && ('proposal-tender'==$penawaran->status))
        {
            try {

                $data['id']=$id;

                $dataDetailPenawaran = ['status' => '0',
                    'updated_by' => Auth::id(),
                    'updated_at' => now()
                ];

                $detailpenawaran->update($dataDetailPenawaran);

                $data['status'] = 'success';
                $data['message'] ['message_success'] = array('Sukses delete Penawaran KJPP '.$request->kjppName);
            } catch (Exception $e) {

                $data['status'] = 'error';
                $data['message'] ['message_error_try_catch'] = array("Gagal delete Penawaran KJPP ".$request->kjppName);
                // $data['message']['message_error'] = array("Gagal delete Penawaran KJPP ".$request->kjppName);
            }
        }
        else
        {
            $data['status'] = 'error';
            $data['message']['active_date_range'] = array("Penawaran sudah di tutup");
            // $data['message']['message_error'] = array("Penawaran sudah di tutup");
        }

        return response()->json($data);
    }

    public function updateulang(Request $request, $id): JsonResponse
    {
        // id ==> detail_penawaran.id
        // init
        $data = array();
        $dataDetailPenawaranLog = array();
        $dataDetailPenawaran = array();
        $pleaseCommit= true;
        if (request()->ajax()) {

            $validator = ProsesPenawaranController::rulesEditUlangnya($request, $id);

            if ($validator['fails']) {
                $data['message'] = $validator['errors'];
                $data['status'] = 'error';
            }
            else
            {
                // cek masa aktif penawaran
                $detailpenawaran  = PenawaranDetailTender::find($id);
                $checkActiveDateRange = checkActiveDateRangePenawaran($detailpenawaran->penawaran_id);
                // cek masa aktif penawaran

                // cek apakah blm di approve (penawaran.status = proposal-tender)
                $penawaran = PenawaranTender::find($detailpenawaran->penawaran_id);
                // cek apakah blm di approve (penawaran.status = proposal-tender)
                if($checkActiveDateRange && ('proposal-tender'==$penawaran->status))
                {
                    DB::beginTransaction();
                    try {

                        $dataDetailPenawaranLog = [
                            'detail_penawaran_id' =>$detailpenawaran->id,
                            'kjpp_rekanan_id'     =>$detailpenawaran->kjpp_rekanan_id,
                            'penawaran_id'        =>$detailpenawaran->penawaran_id,
                            'biaya_penawaran'     =>$detailpenawaran->biaya_penawaran,
                            'no_proposal'         =>$detailpenawaran->no_proposal,
                            'tgl_proposal'        =>$detailpenawaran->tgl_proposal,
                            'attachment'          =>$detailpenawaran->attachment,
                            'dokumen_persetujuan' =>$detailpenawaran->dokumen_persetujuan,
                            'status'              =>$detailpenawaran->status,
                            'authorized_status'   =>$detailpenawaran->authorized_status,
                            'authorized_at'       =>$detailpenawaran->authorized_at,
                            'authorized_at'       =>$detailpenawaran->authorized_at,
                            'created_at'          =>$detailpenawaran->created_at,
                            'updated_at'          =>$detailpenawaran->updated_at,
                            'deleted_at'          =>$detailpenawaran->deleted_at,
                            'created_by'          =>$detailpenawaran->created_by,
                            'updated_by'          =>$detailpenawaran->updated_by,
                            'deleted_by'          =>$detailpenawaran->deleted_by

                        ];

                        PenawaranDetailTenderLog::create($dataDetailPenawaranLog);

                        $biaya_penawaran="";
                        if($request->biaya_penawaran)
                            $biaya_penawaran= str_replace(".","",$request->biaya_penawaran);
                        $dataDetailPenawaran = ['updated_by' => Auth::id(),
                                                'updated_at' => now(),
                                                'no_proposal' => $request->no_proposal,
                                                'tgl_proposal' => $request->tgl_proposal,
                                                'biaya_penawaran' => $biaya_penawaran
                                            ];

                        if ($request->hasFile('dokumen_persetujuan'))
                        {
                            $file_tmp = $request->file('dokumen_persetujuan');
                            $folderPath = 'uploads/penawaran/';
                            if ($file_tmp->isValid())
                            {
                                $myFile=$file_tmp->getClientOriginalName(); // nama file with extension
                                $file_name = pathinfo($myFile, PATHINFO_FILENAME); // nama file without extension

                                $extension = $file_tmp->getClientOriginalExtension();
                                // kjppID_penawaranID_namaFile_userID_time
                                $newFileName = $request->kjpp_rekanan_id.'_'.$id.'_'.$file_name.'_'.Auth::user()->id."_".time() .'.'. $extension;
                                Storage::disk('public')->put($folderPath.'/'.$newFileName,file_get_contents($file_tmp));

                                $newFileNameWithPath = $folderPath . $newFileName;
                                $dataDetailPenawaran['attachment'] = $myFile;
                                $dataDetailPenawaran['dokumen_persetujuan'] = $newFileNameWithPath;
                            }
                            else
                            {
                                $pleaseCommit=false;
                                $data['status'] = 'error';
                                $data['message']['check_file_jenis'] = array("Silahkan upload file pdf");
                            }
                        }
                        else
                        {
                            $data['status'] = 'error';
                            $data['message']['check_file'] = array("Silahkan upload file");

                        }

                        $detailpenawaran->update($dataDetailPenawaran);

                        if($pleaseCommit)
                        {
                            DB::commit();

                            $data['id'] = $id;
                            $data['detailpenawaran'] = $detailpenawaran;
                            $data['status'] = 'success';
                            $data['message']['message_success'] = array('Proses Penawarn KJPP Ulang successfully');
                        }
                        else
                        {
                            DB::rollBack();
                            $data['status'] = 'error';
                            $data['message']['message_error'] = array("Proses Penawarn KJPP Ulang failed..");
                        }

                    } catch (Exception $e) {
                        DB::rollBack();
                        $data['status'] = 'error';
                        $data['message']['message_error_try_catch'] = array('Proses Penawarn KJPP Ulang failed.');
                    }
                }
                else
                {
                    $data['status'] = 'error';
                    $data['message']['active_date_range'] = array("Penawaran sudah di tutup");
                }

            }

        } else {
            $data['status'] = 'error';
            $data['message']['message_ajax'] = array("no ajax request");
        }

        return response()->json($data);
    }

    public function rulesEditUlangnya($request, $id)
    {
        $validateIt = [
            // 'name' diambil dari definisi parameter yang di kirim pada POST Data
            'no_proposal' => 'required',
            'tgl_proposal' => 'required',
            'biaya_penawaran' => 'required',
            'dokumen_persetujuan' => 'required|file|mimes:pdf'
        ];

        $messageIt = [
            'no_proposal.required' => 'Silahkan isi No Proposal',
            'tgl_proposal.required' => 'Silahkan isi Tanggal Penawaran',
            'biaya_penawaran.required' => 'Silahkan isi Biaya Penawaran',
            'dokumen_persetujuan.required' => 'Silahkan isi dokumen',
            'dokumen_persetujuan.file' => 'Silahkan isi file',
            'dokumen_persetujuan.mimes' => 'Silahkan upload pdf'
        ];

        $validator = Validator::make($request->all(), $validateIt, $messageIt);

        $data['fails'] = $validator->fails();
        $data['errors'] = $validator->errors();

        return $data;
    }

    public function storeUlang(Request $request): JsonResponse
    {
        // init
        $data = array();
        // $data['request']=$request->all();
        $dataDetailPenawaran = array();
        // cek masa aktif penawaran
        $checkActiveDateRange = checkActiveDateRangePenawaran($request->penawaran_id);
        // cek masa aktif penawaran

        // cek apakah blm di approve (penawaran.status = proposal-tender)
        $penawaran = PenawaranTender::find($request->penawaran_id);
        // cek apakah blm di approve (penawaran.status = proposal-tender)
        if($checkActiveDateRange && ('proposal-tender'==$penawaran->status))
        {
            try
            {
                $biaya_penawaran="";
                if($request->biaya_penawaran)
                    $biaya_penawaran= str_replace(".","",$request->biaya_penawaran);
                $dataDetailPenawaran  = [
                    'kjpp_rekanan_id' => $request->kjpp_rekanan_id,
                    'no_proposal' => $request->no_proposal,
                    'tgl_proposal' => $request->tgl_proposal,
                    'biaya_penawaran' => $biaya_penawaran,
                    'penawaran_id' => $request->penawaran_id,
                    'created_by' => Auth::id(),
                    'created_at' => Carbon::now()
                ];

                if ($request->hasFile('dokumen_persetujuan'))
                {
                    $file_tmp = $request->file('dokumen_persetujuan');
                    $folderPath = 'uploads/penawaran/';
                    if ($file_tmp->isValid())
                    {
                        $myFile=$file_tmp->getClientOriginalName(); // nama file with extension
                        $file_name = pathinfo($myFile, PATHINFO_FILENAME); // nama file without extension

                        $extension = $file_tmp->getClientOriginalExtension();
                        // kjppID_penawaranID_namaFile_userID_time
                        $newFileName = $request->kjpp_rekanan_id.'_'.$request->penawaran_id.'_'.$file_name.'_'.Auth::user()->id."_".time() .'.'. $extension;
                        Storage::disk('public')->put($folderPath.'/'.$newFileName,file_get_contents($file_tmp));

                        $newFileNameWithPath = $folderPath . $newFileName;
                        $dataDetailPenawaran['attachment'] = $myFile;
                        $dataDetailPenawaran['dokumen_persetujuan'] = $newFileNameWithPath;
                    }
                    else
                    {
                        $pleaseCommit=false;
                        $data['status'] = 'error';
                        $data['message']['check_file_jenis'] = array("Silahkan upload file pdf");
                    }
                }
                else
                {
                    $data['status'] = 'error';
                    $data['message']['check_file'] = array("Silahkan upload file");

                }
                PenawaranDetailTender::create($dataDetailPenawaran);

                $data['status'] = 'success';
                $data['message'] ['message_success'] = array('Proses Tambah KJPP Ulang successfully');
            }
            catch (Exception $e)
            {
                dd($e);
                $data['status'] = 'error';
                $data['message'] ['message_error_try_catch'] = array('Proses Tambah KJPP Ulang failed.');
            }
        }
        else
        {
            $data['status'] = 'error';
            $data['message']['active_date_range'] = array("Penawaran sudah di tutup");
        }

        return response()->json($data);
    }

    // merger permohonan
    /**
     * Show the form for creating a new resource.
     */
    public function createPenawaran($id)
    {
        // id ==> permohonan.id
        $permohonan = Permohonan::find($id);
        // dd($permohonan);
        $status = StatusPermohonan::all();
        $tujuan_penilaian_kjpp = TujuanPenilaianKJPP::all();
        $jenis_laporan = JenisLaporan::all();
        $kjpp = KJPP::all();

        return view('lpj::prosespenawaran.createPenawaran', compact('id', 'status', 'tujuan_penilaian_kjpp', 'jenis_laporan', 'kjpp', 'permohonan'));
    }

    public function storePenawaran(ProsesPenawaranRequest $request, $id)
    {
        $validated = $request->validated();

        DB::beginTransaction();

        try {

            $permohonan = Permohonan::find($id);

            $userId = Auth::user()->id;
            $validated['nomor_registrasi'] = $permohonan->nomor_registrasi;
            $validated['status'] = 'tender';
            $validated['updated_by'] = $userId; // Updating the record
            $validated['end_date'] = $request->input('end_date') . ' 23:59:59';

            $permohonan->update($validated);

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

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

            foreach ($kjpps as $kjpp) {
                PenawaranDetailTender::create([
                    'penawaran_id' => $penawaran->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.prosespenawaran.index')
                 ->with('success', 'Data Penawaran created successfully');
        } catch (Exception $e) {
            DB::rollBack();

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

    public function showPermohonan($id)
    {
        // $id => permohonan.id
        $permohonan  = Permohonan::find($id);
        return view('lpj::prosespenawaran.showPermohonan', compact('id', 'permohonan'));
    }
    // merger permohonan
}
