<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Carbon\Carbon;
    use Exception;
    use Illuminate\Http\JsonResponse;
    use Illuminate\Http\Request;
    use Illuminate\Http\Response;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Support\Facades\Validator;
    use Maatwebsite\Excel\Facades\Excel;
    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;

    class OtorisasiPenawaranController extends Controller
    {
        public $user;
		
		/**
         * Display a listing of the resource.
         */
        public function index()
        {
            // dd('hai otorisasi');
            return view('lpj::otorisasipenawaran.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()->select(
                    'penawaran.*',
                    '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',
                )->leftJoin('permohonan', 'permohonan.nomor_registrasi', '=', 'penawaran.nomor_registrasi')->leftJoin(
                    'debitures',
                    'debitures.id',
                    '=',
                    'permohonan.debiture_id',
                )->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(
                    'tujuan_penilaian_kjpp',
                    'tujuan_penilaian_kjpp.id',
                    '=',
                    'penawaran.tujuan_penilaian_kjpp_id',
                )->where('penawaran.status', '=', 'proposal-tender')->withCount('penawarandetails');

            // 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->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();
            $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::otorisasipenawaran.edit', compact('id'));
		}
		
		public function setData(Request $request): JsonResponse
		{
			$data                = [];
            $penawaran           = [];
            $penawrandetails     = [];
            $penawarandetailLogs = [];

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

				if ($penawaran) {
					$penawarandetailLogs = PenawaranDetailTenderLog::where('penawaran_id',$id)
												->leftJoin('kjpp', 'kjpp.id', '=', 'detail_penawaran_logs.kjpp_rekanan_id')
												->select('detail_penawaran_logs.*', DB::raw("DATE_FORMAT(detail_penawaran_logs.created_at, '%d-%m-%Y %H:%i') AS created_at2"),'kjpp.code AS kjpp_code', 'kjpp.name AS kjpp_name')
												->get();
					$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(sizeof($penawarandetailLogs)>0)
					{
						$h=0;
						foreach($penawarandetailLogs as $obj1)
						{
							// tgl_proposal
							if ($obj1->tgl_proposal) {
								$penawarandetailLogs[$h]->tgl_proposal = Carbon::parse($obj1->tgl_proposal)->format('d M Y');
							}

							if($obj1->dokumen_persetujuan && Storage::disk('public')->exists($obj1->dokumen_persetujuan))
							{
								$penawarandetailLogs_path = Storage::url($obj1->dokumen_persetujuan);
								$penawarandetailLogs[$h]->dokumen_persetujuan = $penawarandetailLogs_path;
							}
							$h++;
						}

					}

					$i=0;
					foreach($penawrandetails as $obj)
					{
						// tgl_proposal
						if ($obj->tgl_proposal) {
							$penawrandetails[$i]->tgl_proposal = Carbon::parse($obj->tgl_proposal)->format('d M Y');
						}

						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;
					}

					$kjpp=null;
					$kjpp = KJPP::pluck('name', 'id');
					$data['penawaran'] = $penawaran;
					$data['penawrandetails'] = $penawrandetails;
					$data['penawarandetailLogs'] = $penawarandetailLogs;
					$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 otorisasiPenawaranKJPP(Request $request, $id): JsonResponse
		{
			$data                   = [];
            $dataDetailPenawaranLog = [];
			if (request()->ajax()) {

				// cek masa aktif penawaran
				$detailpenawaran  = PenawaranDetailTender::find($id);
				$penawaran = PenawaranTender::findOrFail($detailpenawaran->penawaran_id);
				$checkActiveDateRange = checkActiveDateRangePenawaran($detailpenawaran->penawaran_id);
				// cek masa aktif penawaran
				if($checkActiveDateRange)
				{
					DB::beginTransaction();
					try {

						// update status KJPP yg tidak terpilih menjadi 2 -> kalah
						// update status Penawaran menjadi persetujuan-penawaran (20241205)
						// update status Permohonan menjadi persetujuan-penawaran (20241205)
						// insert detail_permohonan_log

						PenawaranDetailTender::where('status', 1)
								->where('penawaran_id', $request->penawaran_id)
								->whereNotIn('id', [$id])
								->update(['status' => 2,
										'updated_by' => Auth::id(),
										'updated_at' => now()
										]);
						// 20241205 arahkan ke persetujuan-penawaran				
						PenawaranTender::where('id', $request->penawaran_id)
										->update(['status'=>'persetujuan-penawaran',
												'nama_kjpp_sebelumnya'=>$request->kjppName,
												'biaya_kjpp_sebelumnya'=>$request->biaya_penawaran,
												'tanggal_penilaian_sebelumnya'=>now(),
												'authorized_status'=>1,
												'authorized_at'=>now(),
												'authorized_by'=>Auth::id(),
												'updated_by' => Auth::id(),
												'updated_at' => now()
										]);

						Permohonan::where('nomor_registrasi',$request->noReg)
											->update(['status'=>'persetujuan-penawaran',
											'updated_by' => Auth::id(),
											'updated_at' => now()
										]);

						// log
						$detailPenawaran = PenawaranDetailTender::where('penawaran_id', $request->penawaran_id)->get();
						if(sizeof($detailPenawaran)>0)
						{

							foreach ($detailPenawaran as $model) {
								array_push($dataDetailPenawaranLog, [
									'detail_penawaran_id' =>$model->id,
									'kjpp_rekanan_id'     =>$model->kjpp_rekanan_id,
									'penawaran_id'        =>$model->penawaran_id,
									'no_proposal'         =>$model->no_proposal,
									'tgl_proposal'        =>$model->tgl_proposal,
									'biaya_penawaran'     =>$model->biaya_penawaran,
									'attachment'          =>$model->attachment,
									'dokumen_persetujuan' =>$model->dokumen_persetujuan,
									'status'              =>$model->status,
									'authorized_status'   =>$model->authorized_status,
									'authorized_at'       =>$model->authorized_at,
									'authorized_at'       =>$model->authorized_at,
									'created_at'          =>$model->created_at,
									'updated_at'          =>$model->updated_at,
									'deleted_at'          =>$model->deleted_at,
									'created_by'          =>$model->created_by,
									'updated_by'          =>$model->updated_by,
									'deleted_by'          =>$model->deleted_by
								]);

							}

							PenawaranDetailTenderLog::insert($dataDetailPenawaranLog);
						}
						// log

						DB::commit();
						$data['status'] = 'success';
						$data['message']['message_success'] = array('Otorisasi Penawaran KJPP '.$request->kjppName.' successfully');
					} catch (Exception $e) {
						DB::rollBack();
						$data['status'] = 'error';
						$data['message']['message_error'] = array("Otorisasi Penawaran KJPP failed..");
					}
				}
				else
				{
					$data['status'] = 'error';
					$data['message']['message_error'] = array("Penawaran sudah di tutup");
				}

			} else {
				$data['status'] = 'error';
				$data['message']['message_error'] = array("no ajax request");
			}
			return response()->json($data);
		}
		
		public function show($id)
		{
			$prosespenawaran  = PenawaranTender::with(['permohonan','tujuanPenilaianKjpp'])->find($id);
            $permohonan = $prosespenawaran->permohonan;
			return view('lpj::otorisasipenawaran.show', compact('id','prosespenawaran','permohonan'));
		}
		
		public function penawaranulang(Request $request, $id): JsonResponse
		{
			// $id ==> penawaran.id
			$data = [];
			$dataDetailPenawaranLog=[];
			if (request()->ajax()) {

				
				DB::beginTransaction();
				try {

					// update detail_penawaran => detail_penawaran.status = 1 (untuk all KJPP)
					// update penawaran => penawaran.status ="tender", penawaran.updated_at, penawaran.updated_by
					// update permohonan => permohonan.status ="tender", permohonan.updated_at, permohonan.updated_by
					// insert detail_permohonan_log
					
					PenawaranDetailTender::where('penawaran_id', $id)
										->update(['status' => 1,
												'updated_by' => Auth::id(),
												'updated_at' => now()
										]);
					
					PenawaranTender::where('id', $id)
										->update(['status'=>'tender',
												'updated_by' => Auth::id(),
												'updated_at' => now()
										]);
									   
					Permohonan::where('nomor_registrasi',$request->noReg)
										->update(['status'=>'tender',
										'updated_by' => Auth::id(),
										'updated_at' => now()
									]);
								
					$detailPenawaran = PenawaranDetailTender::where('penawaran_id', $id)
											->distinct()
											->get();

					// log
					if(sizeof($detailPenawaran)>0)
					{

						foreach ($detailPenawaran as $model) {
							array_push($dataDetailPenawaranLog, [
								'detail_penawaran_id' =>$model->id,
								'kjpp_rekanan_id'     =>$model->kjpp_rekanan_id,
								'penawaran_id'        =>$model->penawaran_id,
								'no_proposal'         =>$model->no_proposal,
								'tgl_proposal'        =>$model->tgl_proposal,
								'biaya_penawaran'     =>$model->biaya_penawaran,
								'attachment'          =>$model->attachment,
								'dokumen_persetujuan' =>$model->dokumen_persetujuan,
								'status'              =>$model->status,
								'authorized_status'   =>$model->authorized_status,
								'authorized_at'       =>$model->authorized_at,
								'authorized_at'       =>$model->authorized_at,
								'created_at'          =>$model->created_at,
								'updated_at'          =>$model->updated_at,
								'deleted_at'          =>$model->deleted_at,
								'created_by'          =>$model->created_by,
								'updated_by'          =>$model->updated_by,
								'deleted_by'          =>$model->deleted_by
							]);

						}

						PenawaranDetailTenderLog::insert($dataDetailPenawaranLog);
					}
					// log

					DB::commit();
					$data['detailPenawaran'] = $detailPenawaran;
					$data['status'] = 'success';
					$data['message']['message_success'] = array('Penawaran ulang successfully');
				} catch (Exception $e) {
					DB::rollBack();
					$data['status'] = 'error';
					$data['message']['message_error'] = array("Penawaran ulang failed..");
				}
			   

			} else {
				$data['status'] = 'error';
				$data['message']['message_error'] = array("no ajax request");
			}
			return response()->json($data);
		}
	}