<?php

namespace Modules\Lpj\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
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\Models\KJPP;
use Modules\Lpj\Models\PenawaranDetailTender;
use Modules\Lpj\Models\PenawaranDetailTenderLog;
use Modules\Lpj\Models\PenawaranTender;

use Modules\Lpj\Models\Permohonan;

class ProsesPenawaranUlangController extends Controller
{
    public $user;

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('lpj::prosespenawaranulang.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.*',DB::raw("CONCAT(DATE_FORMAT(penawaran.start_date, '%d %M %Y'), ' -  ', DATE_FORMAT(penawaran.end_date, '%d %M %Y')) AS date_range"), 'tujuan_penilaian_kjpp.name as tujuan_penilaian_kjpp_name')
                        ->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();

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

    public function show($id)
    {
        $prosespenawaran  = PenawaranTender::find($id);
        return view('lpj::prosespenawaranulang.show', compact('id','prosespenawaran'));
    }

    public function setData(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;
                }

                $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 update(Request $request, $id): JsonResponse
    {
        // init
        $data = array();
        $dataDetailPenawaranLog = array();
        $dataDetailPenawaran = array();
        $pleaseCommit= true;
        if (request()->ajax()) {
            $validator = ProsesPenawaranUlangController::rulesEditnya($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
                if($checkActiveDateRange)
                {
                    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,
                            '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(),
                                '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);
    }

    // delete KJPP di detail_penawaran (status di buat 0)
    public function updateKJPPStatus(Request $request, $id): JsonResponse
    {
        // init
        $data = array();
        $dataku = array();
        $dataDetailPenawaranLog = array();

        DB::beginTransaction();
        try {
            $model = PenawaranDetailTender::findOrFail($id);

            // log
            $dataDetailPenawaranLog = [
                'detail_penawaran_id' =>$model->id,
                'kjpp_rekanan_id'     =>$model->kjpp_rekanan_id,
                'penawaran_id'        =>$model->penawaran_id,
                'biaya_penawaran'     =>$model->biaya_penawaran,
                'attachment'          =>$model->attachment,
                'dokumen_persetujuan' =>$model->dokumen_persetujuan,
                'status'              =>0,
                '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::create($dataDetailPenawaranLog);
            // log

            $data['id']=$id;

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

            $model->update($dataku);

            DB::commit();
            $data['status'] = 'success';
            $data['message']['message_success'] = array('Sukses delete Penawaran KJPP '.$request->kjppName);
        } catch (Exception $e) {
            DB::rollBack();
            // dd($e);
            $data['status'] = 'error';
            $data['message']['message_error_try_catch'] = array("Gagal delete Penawaran KJPP ".$request->kjppName);
        }
        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;
    }

}
