<?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\NocRequest;
    use Modules\Lpj\Models\PenawaranTender;
    use Modules\Lpj\Models\Permohonan;
    use Modules\Lpj\Models\PersetujuanPenawaran;

    class NocController extends Controller
    {
        public $user;

        /**
         * Display a listing of the resource.
         */
        public function index()
        {
            $persetujuanPenawarans = PersetujuanPenawaran::all();
            return view('lpj::noc.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(NocRequest $request)
        {
            $validated               = $request->validated();
            $validated['updated_by'] = Auth::id();
            if (request()->get('status_bayar') == "sudah_bayar") {
                $validated['status'] = '1';
                $status              = "spk";
            } else {
                $status = "persetujuan-penawaran";
            }

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

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

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

            $persetujuanPenawaran->save();

            // Update the status of the related permohonan to 'spk'
            $permohonan = Permohonan::find(request()->get('permohonan_id'));
            if ($permohonan) {
                $permohonan->status_bayar = request()->get('status_bayar');
                if($permohonan->jenis_penilaian_id==2) {
                    $permohonan->status = $status;
                }
                $permohonan->save();

                // andy add, update status penawaran.status='spk'
                // $penawaran = PenawaranTender::where('nomor_registrasi',$permohonan->nomor_registrasi)->first();
                if($permohonan->jenis_penilaian_id==2) {
                    PenawaranTender::where('nomor_registrasi', $permohonan->nomor_registrasi)->update([
                        'status'     => $status,
                        'updated_by' => Auth::id(),
                        'updated_at' => now(),
                    ]);
                }
                // andy add, update status penawaran.status='spk'
            }

            return redirect()
                ->route('noc.index')->with('success', 'Penyelesaian KSL berhasil disimpan.');
        }

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

            $persetujuanPenawaran->update($validated);

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

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

        /**
         * Display the specified resource.
         */
        public function show($id) {}

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

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

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

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

            // Retrieve data from the database
            $query = PersetujuanPenawaran::query();

            // Apply search filter if provided
            if ($request->has('search') && !empty($request->get('search'))) {
                $search = $request->get('search');
                $query->where(function ($q) use ($search) {
                    $q->orWhereRelation('penawaran', '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(
                    [
                        'penawaran.permohonan.debiture',
                        'penawaran.permohonan.branch',
                        'permohonan.debiture',
                        'permohonan.branch',
                        'penawaran.detail',
                        'penawaran.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,
            ]);
        }
    }
