<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Modules\Lpj\Http\Requests\PersetujuanPenawaranRequest;
    use Modules\Lpj\Models\Noc;
    use Modules\Lpj\Models\PenawaranDetailTender;
    use Modules\Lpj\Models\PenawaranDetailTenderLog;
    use Modules\Lpj\Models\PenawaranTender;
    use Modules\Lpj\Models\Permohonan;
    use Modules\Lpj\Models\PersetujuanPenawaran;

    class PersetujuanPenawaranController extends Controller
    {
        public $user;

        /**
         * Display a listing of the resource.
         */
        public function index()
        {
            $persetujuanPenawarans = PersetujuanPenawaran::all();
            return view('lpj::persetujuan_penawaran.index', compact('persetujuanPenawarans'));
        }

        /**
         * Store a newly created resource in storage.
         */
        /**
         * Store a newly created resource in storage.
         */
        /**
         * Store a newly created resource in storage.
         */
        public function store(PersetujuanPenawaranRequest $request)
        {
            $validated               = $request->validated();
            $validated['created_by'] = Auth::id();
            $validated['status']     = '0';
            $validated['nominal_bayar']     = $validated['biaya_final'];

            $persetujuanPenawaran = PersetujuanPenawaran::updateOrCreate(
                ['penawaran_id' => $validated['penawaran_id']],
                $validated,
            );

            $folderPath = 'persetujuan_penawaran/' . $validated['penawaran_id'];

            if ($request->hasFile('file_persetujuan_penawaran')) {
                $persetujuanPenawaran->file_persetujuan_penawaran = $request->file('file_persetujuan_penawaran')->store(
                    $folderPath,
                    'public',
                );
            }

            if ($request->hasFile('surat_representasi')) {
                $persetujuanPenawaran->surat_representasi = $request->file('surat_representasi')->store(
                    $folderPath,
                    'public',
                );
            }

            if ($request->hasFile('bukti_bayar')) {
                $persetujuanPenawaran->bukti_bayar = $request->file('bukti_bayar')->store($folderPath, 'public');
            }

            $persetujuanPenawaran->save();


            // Save NOC
            try {
                $noc = Noc::updateOrCreate([
                    'permohonan_id' => $persetujuanPenawaran->permohonan_id,
                    'persetujuan_penawaran_id' => $persetujuanPenawaran->id
                ],[
                    'bukti_bayar' => $persetujuanPenawaran->bukti_bayar,
                ]);
            } catch (\Exception $e) {
                \Log::error('Failed to create or update NOC: ' . $e->getMessage());
                return redirect()
                    ->route('persetujuan-penawaran.index')
                    ->with('error', 'Persetujuan Penawaran berhasil disimpan tetapi gagal membuat NOC: ' . $e->getMessage());
            }

            return redirect()
                ->route('persetujuan-penawaran.index')->with('success', 'Persetujuan Penawaran berhasil disimpan.');
        }

        /**
         * Update the specified resource in storage.
         */
        public function update(PersetujuanPenawaranRequest $request, PersetujuanPenawaran $persetujuanPenawaran)
        {
            $validated               = $request->validated();
            $validated['updated_by'] = Auth::id();

            $persetujuanPenawaran->update($validated);

            return redirect()
                ->route('persetujuan-penawaran.index')->with('success', 'Persetujuan Penawaran updated successfully');
        }

        /**
         * Show the form for creating a new resource.
         */
        public function create()
        {
            return view('lpj::persetujuan_penawaran.create');
        }

        /**
         * Display the specified resource.
         */
        public function show($id)
        {
            $permohonan             = Permohonan::find($id);
            $permohonan->status     = 'tender';
            $dataDetailPenawaranLog = [];

            // andy add update status penawaran
            // 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
            $penawaran = PenawaranTender::where('nomor_registrasi', $permohonan->nomor_registrasi)->first();
            // dd($penawaran->id);
            PenawaranDetailTender::where('penawaran_id', $penawaran->id)->update([
                'status'     => 1,
                'updated_by' => Auth::id(),
                'updated_at' => now(),
            ]);

            PenawaranTender::where('id', $penawaran->id)->update([
                'status'     => 'tender',
                'updated_by' => Auth::id(),
                'updated_at' => now(),
            ]);

            $detailPenawaran = PenawaranDetailTender::where('penawaran_id', $penawaran->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
            // andy add update status penawaran

            return $permohonan->save();
        }

        /**
         * Show the form for editing the specified resource.
         */
        public function edit($id)
        {
            $permohonan = Permohonan::with(['debiture', 'penawaranTender.detail'])->find($id);
            $persetujuanPenawaran = PersetujuanPenawaran::where('permohonan_id', $id)->first();
            return view('lpj::persetujuan_penawaran.form', compact('permohonan', 'persetujuanPenawaran'));
        }

        /**
         * Remove the specified resource from storage.
         */
        public function destroy(PersetujuanPenawaran $persetujuanPenawaran)
        {
            $persetujuanPenawaran->delete();

            return redirect()
                ->route('persetujuan-penawaran.index')->with('success', 'Persetujuan Penawaran deleted successfully');
        }

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

            // Retrieve data from the database
            //$query = Permohonan::query()->where(['status' => 'persetujuan-penawaran']);
            $query = Permohonan::query()
                ->where(['status' => 'persetujuan-penawaran'])
                ->whereHas('penawaranTender', function ($q) {
                    $q->where('status', 'persetujuan-penawaran');
                });
            // 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%");
                });
            }

            // 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(['debiture', 'penawaranTender.detail', 'penawaranTender.persetujuan'])->get();

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

            // Calculate the current page number
            $currentPage = $request->get('page', 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,
            ]);
        }
    }
