<?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\Bucok;
use Modules\Lpj\Models\Noc;
    use Modules\Lpj\Models\PersetujuanPenawaran;
    use Modules\Lpj\Models\JenisPenilaian;

    class NocController extends Controller
    {
        public $user;

        /**
         * Display a listing of the resource.
         */
        public function index()
        {
            return redirect()->route('noc.pembayaran.index');
        }

        public function pembayaran()
        {
            $persetujuanPenawarans = PersetujuanPenawaran::all();
            $jenisPenilaians = JenisPenilaian::get();
            return view('lpj::noc.pembayaran', compact('persetujuanPenawarans', 'jenisPenilaians'));
        }

        public function penyelesaian()
        {
            $persetujuanPenawarans = PersetujuanPenawaran::all();
             $jenisPenilaians = JenisPenilaian::get();
            return view('lpj::noc.penyelesaian', compact('persetujuanPenawarans', 'jenisPenilaians'));
        }

        /**
         * 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';
            }

            $dataNoc = [
                'nominal_bayar'      => $validated['nominal_bayar'],
                'total_pembukuan'    => $validated['total_pembukuan'],
                'tanggal_pembayaran' => $validated['tanggal_pembayaran'] ?? date('Y-m-d'),
                'status_bayar'       => $validated['nominal_bayar'] < $validated['total_harus_bayar'] ? false : true,
                'catatan_noc'        => $validated['catatan_noc'] ?? '',
                'status_kurang_bayar' => $validated['status_kurang_bayar'] ?? '0',
                'status_lebih_bayar' => $validated['status_lebih_bayar'] ?? '0',
                'nominal_kurang_bayar' => $validated['nominal_kurang_bayar'] ?? '0',
                'nominal_lebih_bayar' => $validated['nominal_lebih_bayar'] ?? '0',
                'bukti_pengembalian' => $validated['bukti_pengembalian'] ?? '',
            ];

            if($validated['permohonan_id']){
                $noc     = Noc::updateOrCreate(
                [
                    'permohonan_id'            => $validated['permohonan_id'],
                    'persetujuan_penawaran_id' => $validated['persetujuan_penawaran_id'],
                ],
                $dataNoc,
            );
            } else {
                $noc     = Noc::updateOrCreate(
                [
                    'persetujuan_penawaran_id' => $validated['persetujuan_penawaran_id'],
                ],
                $dataNoc,
            );
            }

            $folderPath = 'noc/' . request()->get('persetujuan_penawaran_id') . '/bukti_ksl/';

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

            $bucok = Bucok::where('nomor_tiket', $noc->nomor_tiket)->orWhere('permohonan_id', $noc->permohonan_id)->first();
            if($bucok){
                $bucok->nominal_penyelesaian = $noc->total_pembukuan ?? '';
                $bucok->tanggal_penyelesaian = $noc->tanggal_pembayaran ?? date('Y-m-d');
                $bucok->penyelesaian = 'Selesai';
                $bucok->save();
            }

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

        /**
         * Update the specified resource in storage.
         */
        public function update(NocRequest $request, PersetujuanPenawaran $persetujuanPenawaran)
        {
            $validated = $request->validated();


            if($request->get('is_memo')){

                $memo = Noc::find($request->get('is_memo'));

                $folderPath = 'noc/' . request()->get('persetujuan_penawaran_id') . '/memo_penyelesaian/';

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

                $memo->catatan_noc = $validated['catatan_noc'];
                $memo->save();


                return redirect()
                    ->route('laporan.index')->with('success', 'Memo Penyelesaian updated successfully');
            }
            $dataNoc   = [
                'total_pembukuan'      => $validated['total_pembukuan'],
                'nominal_penyelesaian' => $validated['nominal_penyelesaian'],
                'tanggal_penyelesaian' => $validated['tanggal_penyelesaian'] ?? date('Y-m-d'),
                'status_pelunasan'     => ((int)$validated['nominal_bayar'] + (int)$validated['nominal_penyelesaian']) === (int)$validated['total_harus_bayar'] ? true : false,
                'catatan_noc'          => $validated['catatan_noc'],
            ];


            $noc = Noc::updateOrCreate(
                [
                    'permohonan_id'            => $validated['permohonan_id'],
                    'permohonan_id'            => $validated['permohonan_id'],
                    'persetujuan_penawaran_id' => $validated['persetujuan_penawaran_id'],
                ],
                $dataNoc,
            );

            $folderPath = 'noc/' . request()->get('persetujuan_penawaran_id') . '/bukti_penyelesaian/';

            if ($request->hasFile('bukti_penyelesaian')) {
                $noc->bukti_penyelesaian = $request->file('bukti_penyelesaian')->store(
                    $folderPath,
                    'public',
                );
            }
            $noc->save();


            return redirect()
                ->route('noc.index')->with('success', 'NOC 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(Noc $noc) {
           return view('lpj::noc.memo', compact('noc'));
        }

        /**
         * Show the form for editing the specified resource.
         */
        public function edit($id)
        {
            $persetujuanPenawaran = PersetujuanPenawaran::where('id', $id)->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)
        {
            // Redirect to pembayaran datatables by default
            return $this->dataForDatatablesPembayaran($request);
        }

        public function dataForDatatablesPembayaran(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();

            // Filter for pembayaran (where memo_penyelesaian is null)
            /*$query->whereDoesntHave('noc', function($q) {
                $q->whereNotNull('memo_penyelesaian');
            });*/

            // 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 . '%')
                        ->orWhereRelation('permohonan', 'nomor_registrasi', 'LIKE', '%' . $search . '%')
                        ->orWhereRelation('permohonan.debiture','name', 'LIKE', '%' . $search . '%')
                        ->orWhereRelation('permohonan.jenisPenilaian', 'name', 'LIKE', '%' . $search . '%')
                        ->orWhere('nomor_tiket', '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->get();

            $data = $data->map(function ($persetujuanPenawaran) {
                return [
                    'id'                   => $persetujuanPenawaran->id,
                    'nomor_registrasi'     => $persetujuanPenawaran->permohonan?->nomor_registrasi ?? $persetujuanPenawaran->penawaran?->nomor_registrasi,
                    'nomor_tiket'          => $persetujuanPenawaran->nomor_tiket ?? '',
                    'nama_debitur'         => $persetujuanPenawaran?->permohonan?->debiture->name ?? $persetujuanPenawaran->penawaran?->permohonan?->debiture->name ?? $persetujuanPenawaran->noc?->debiture->name,
                    'kode_cabang'          => $persetujuanPenawaran?->permohonan?->branch->code ?? $persetujuanPenawaran->penawaran?->permohonan?->branch->code ?? $persetujuanPenawaran->noc?->branch->code,
                    'cabang'               => $persetujuanPenawaran?->permohonan?->branch->name ?? $persetujuanPenawaran->penawaran?->permohonan?->branch->name ?? $persetujuanPenawaran->noc?->branch->name,
                    'tanggal_pembayaran'   => dateFormat(
                        $persetujuanPenawaran->noc->tanggal_pembayaran ?? $persetujuanPenawaran->noc?->created_at,
                        true,
                    ),
                    'nominal_bayar'        => currencyFormat($persetujuanPenawaran->nominal_bayar ?? 0,
                    ),
                    'nominal_diterima'     => currencyFormat(
                        $persetujuanPenawaran->noc->nominal_bayar ?? 0,
                    ),
                    'jenis_penilaian'      => $persetujuanPenawaran->permohonan?->jenisPenilaian?->name ?? "",
                    'bukti_ksl'            => $persetujuanPenawaran->noc->bukti_ksl ?? $persetujuanPenawaran->bukti_ksl ?? null,
                    'bukti_bayar'          => $persetujuanPenawaran->bukti_bayar ?? null,
                    'updated_at'           => dateFormat($persetujuanPenawaran->updated_at, true),
                ];
            })->sortBy('updated_at', 1)->values();

            // Calculate total nominal diterima from all filtered data (not just current page)
            $totalNominalDiterima = $data->sum(function ($item) {
                // Extract numeric value from formatted currency string
                $nominal = str_replace(['Rp', '.', ',00'], '', $item['nominal_diterima']);
                return (float) $nominal;
            });

            // 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,
                'totalNominalDiterima' => $totalNominalDiterima,
                'data'            => $data,
            ]);
        }

        public function dataForDatatablesPenyelesaian(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();

            // Filter for penyelesaian (where memo_penyelesaian is not null)
            $query->whereDoesntHave('noc', function($q) {
                $q->whereNotNull('memo_penyelesaian');
            });

            // 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 . '%')
                        ->orWhereRelation('permohonan', 'nomor_registrasi', 'LIKE', '%' . $search . '%')
                        ->orWhereRelation('permohonan.debiture','name', 'LIKE', '%' . $search . '%')
                        ->orWhereRelation('permohonan.jenisPenilaian', 'name', 'LIKE', '%' . $search . '%')
                        ->orWhere('nomor_tiket', 'LIKE', '%' . $search . '%'); $q->orWhereRelation('penawaran', 'nomor_registrasi', 'LIKE', '%' . $search . '%')
                        ->orWhereRelation('permohonan', 'nomor_registrasi', 'LIKE', '%' . $search . '%')
                        ->orWhereRelation('permohonan.debiture','name', 'LIKE', '%' . $search . '%')
                        ->orWhereRelation('permohonan.jenisPenilaian', 'name', 'LIKE', '%' . $search . '%')
                        ->orWhere('nomor_tiket', '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->get();

            $data = $data->map(function ($persetujuanPenawaran) {
                return [
                    'id'                   => $persetujuanPenawaran->id,
                    'nomor_registrasi'     => $persetujuanPenawaran->permohonan?->nomor_registrasi ?? $persetujuanPenawaran->penawaran?->nomor_registrasi ?? '',
                    'nomor_tiket'         => $persetujuanPenawaran->nomor_tiket ?? '',
                    'nama_debitur'         => $persetujuanPenawaran->permohonan?->debiture?->name ?? $persetujuanPenawaran->penawaran?->permohonan?->debiture?->name ?? $persetujuanPenawaran->noc?->debiture?->name,
                    'kode_cabang'          => $persetujuanPenawaran?->permohonan?->branch?->code ?? $persetujuanPenawaran->penawaran?->permohonan?->branch?->code ?? $persetujuanPenawaran->noc?->branch?->code ?? '',
                    'cabang'               => $persetujuanPenawaran->permohonan?->branch?->name ?? $persetujuanPenawaran->penawaran?->permohonan?->branch?->name ?? $persetujuanPenawaran->noc?->branch?->name ?? '',
                    'tanggal_pembayaran'   => dateFormat(
                        $persetujuanPenawaran->noc->tanggal_pembayaran ?? $persetujuanPenawaran->noc?->created_at,
                        true,
                    ),
                    'nominal_bayar'        => currencyFormat($persetujuanPenawaran->nominal_bayar ?? 0,
                    ),
                    'nominal_diterima'     => currencyFormat(
                        $persetujuanPenawaran->noc->nominal_bayar ?? 0,
                    ),
                    'jenis_penilaian'      => $persetujuanPenawaran->permohonan?->jenisPenilaian?->name ?? "",
                    'bukti_ksl'            => $persetujuanPenawaran->noc->bukti_ksl ?? $persetujuanPenawaran->bukti_ksl ?? null,
                    'bukti_bayar'          => $persetujuanPenawaran->bukti_bayar ?? null,
                    'memo_penyelesaian'    => $persetujuanPenawaran->noc->memo_penyelesaian ?? $persetujuanPenawaran->memo_penyelesaian ?? null,
                    'nominal_penyelesaian' => currencyFormat(
                        $persetujuanPenawaran->noc->nominal_penyelesaian ?? $persetujuanPenawaran->nominal_penyelesaian ?? 0,
                    ),
                    'bukti_penyelesaian'   => $persetujuanPenawaran->noc->bukti_penyelesaian ?? $persetujuanPenawaran->bukti_penyelesaian ?? null,
                    'tanggal_penyelesaian' => $persetujuanPenawaran->noc?->tanggal_penyelesaian ? dateFormat(
                        $persetujuanPenawaran->noc?->tanggal_penyelesaian,
                        true) : '-',
                    'updated_at'           => dateFormat($persetujuanPenawaran->updated_at, true),
                ];
            })->sortBy('updated_at', 1)->values();


            // Calculate total nominal diterima from all filtered data (not just current page)
            $totalNominalDiterima = $data->sum(function ($item) {
                // Extract numeric value from formatted currency string
                $nominal = str_replace(['Rp', '.', ',00'], '', $item['nominal_diterima']);
                return (float) $nominal;
            });

            // 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,
                'totalNominalDiterima' => $totalNominalDiterima,
                'data'            => $data,
            ]);
        }
    }
