<?php

namespace Modules\Lpj\Http\Controllers;

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

class PembayaranController extends Controller
{
    public $user;

    public function index()
    {
        return view('lpj::pembayaran.index');
    }

    public function kurang(){
        return view('lpj::pembayaran.kurang');
    }

    public function lebih(){
        return view('lpj::pembayaran.lebih');
    }

    public function approval()
    {
        return view('lpj::pembayaran.approval');
    }

    public function dataApprovalForDatatables(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();
        if (Auth::user()->hasAnyRole(['pemohon-ao','pemohon-eo'])) {
            $query = $query->whereRelation('permohonan', 'branch_id', Auth::user()->branch_id);
        }

          // 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.user',
                    'penawaran.permohonan.debiture',
                    'penawaran.permohonan.branch',
                    'permohonan.debiture',
                    'permohonan.branch',
                    'permohonan.user',
                    'permohonan.approveBayar',
                    'penawaran.permohonan.approveBayar',
                    '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,
        ]);
    }

    public function create(){
        return view('lpj::pembayaran.create');
    }

    public function edit($id)
    {

        $req = request()->all();

        if(isset($req['tiket'])){
            $persetujuanPenawaran = PersetujuanPenawaran::find($id);
            $permohonan = Permohonan::find($persetujuanPenawaran?->permohonan_id);
        } else {
            $permohonan = Permohonan::find($id);
            $persetujuanPenawaran = PersetujuanPenawaran::where('permohonan_id', $permohonan->id)->first();
        }

        return view('lpj::pembayaran.form', compact('permohonan', 'persetujuanPenawaran'));
    }

    public function editKurang($id){
        $noc = Noc::find($id);
        $permohonan = Permohonan::find($noc->permohonan_id);
        $persetujuanPenawaran = PersetujuanPenawaran::where('permohonan_id', $permohonan->id)->first();
        return view('lpj::pembayaran.form-kurang', compact('noc','permohonan','persetujuanPenawaran'));
    }

    public function editLebih($id){
        $noc = Noc::find($id);
        $permohonan = Permohonan::find($noc->permohonan_id);
        $persetujuanPenawaran = PersetujuanPenawaran::where('permohonan_id', $permohonan->id)->first();
        return view('lpj::pembayaran.form-lebih', compact('noc','permohonan','persetujuanPenawaran'));
    }

    public function store(PersetujuanPenawaranRequest $request)
    {
        $req = request()->all();

        if(isset($req['type'])){
            if($req['type'] == 'create'){
                $data = [
                    'nomor_tiket' => $req['nomor_tiket'] ?? '',
                    'nominal_bayar' => $req['nominal_bayar'] ?? '',
                    'catatan' => $req['catatan'] ?? ''
                ];

                if(request()->hasFile('bukti_bayar')){
                    $folderPath                        = 'persetujuan_penawaran/bukti_bayar/' . $req['nomor_tiket'];
                    $data['bukti_bayar'] = $request->file('bukti_bayar')->store($folderPath, 'public');
                }

                $persetujuanPenawaran = PersetujuanPenawaran::create($data);
                $noc = [
                    'persetujuan_penawaran_id' => $persetujuanPenawaran->id,
                    'nomor_tiket' => $req['nomor_tiket'] ?? '',
                    'debiture_id' => $req['debitur_id'] ?? '',
                    'branch_id' => Auth::user()->branch_id,
                ];
                $noc = Noc::create($noc);

                $bucok = [
                    'tanggal_penuh'          => $persetujuanPenawaran->created_at ?? $noc->created_at,
                    'tanggal'                => $persetujuanPenawaran->created_at?->format('d') ?? $noc->created_at?->format('d'),
                    'bulan'                  => $persetujuanPenawaran->created_at?->format('m') ?? $noc->created_at?->format('m'),
                    'tahun'                  => $persetujuanPenawaran->created_at?->format('Y') ?? $noc->created_at?->format('Y'),
                    'nomor_tiket'            => $req['nomor_tiket'] ?? '',
                    'nominal'                => $req['nominal_bayar'] ?? '',
                    'nominal_berjalan'       => $req['nominal_bayar'] ?? '',
                    'penyelesaian'           => 'Belum Selesai',
                    'nama_sub_direktorat'    => $noc->branch?->name ?? '',
                    'nama_direktorat_cabang' => $noc->branch?->name ?? '',
                ];

                Bucok::updateOrCreate([
                    'nomor_tiket' => $req['nomor_tiket'] ?? '',
                ], $bucok);

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

            if($req['type'] == 'kurang_bayar'){
                $noc = Noc::find($req['noc_id']);
                $noc->nominal_pelunasan = $req['nominal_pelunasan'];
                if (request()->hasFile('bukti_ksl_kurang_bayar')) {
                    $folderPath                        = 'persetujuan_penawaran/bukti_ksl_kurang_bayar/' . $req['noc_id'];
                    $noc->bukti_ksl_kurang_bayar = $request->file('bukti_ksl_kurang_bayar')->store($folderPath, 'public');
                }
                $noc->save();

                $persetujuanPenawaran = PersetujuanPenawaran::find($noc->persetujuan_penawaran_id);
                $persetujuanPenawaran->bukti_ksl_kurang_bayar =  $noc->bukti_ksl_kurang_bayar;
                $persetujuanPenawaran->nominal_kurang_bayar = $req['nominal_pelunasan'];
                $persetujuanPenawaran->save();
                return redirect()
                    ->route('pembayaran.kurang.index')->with('success', 'Pelunasan Kurang Bayar berhasil disimpan.');
            }

            if($req['type'] == 'lebih_bayar'){
                $noc = Noc::find($req['noc_id']);
                if (request()->hasFile('bukti_ksl_lebih_bayar')) {
                    $folderPath                        = 'persetujuan_penawaran/bukti_ksl_lebih_bayar/' . $req['noc_id'];
                    $noc->bukti_ksl_lebih_bayar = $request->file('bukti_ksl_lebih_bayar')->store($folderPath, 'public');
                }
                $noc->save();

                return redirect()
                    ->route('pembayaran.lebih.index')->with('success', 'Pengembalian Lebih Bayar berhasil disimpan.');
            }
        }

        $validated               = $request->validated();
        $validated['nominal_bayar']    = $req['nominal_bayar'] ?? 0;
        $validated['created_by'] = Auth::id();
        $validated['created_at'] = now();
        $validated['status']     = '0';

        $persetujuanPenawaran = PersetujuanPenawaran::where('permohonan_id', $validated['permohonan_id'] ?? null)->first();
        $permohonan           = Permohonan::find(request()->get('permohonan_id'));
        if ($persetujuanPenawaran) {
            $persetujuanPenawaran->fill($validated);

            if ($request->hasFile('bukti_bayar')) {
                $folderPath                        = 'persetujuan_penawaran/' . $validated['penawaran_id'];
                $persetujuanPenawaran->bukti_bayar = $request->file('bukti_bayar')->store($folderPath, 'public');
            }

            $persetujuanPenawaran->save();

            $permohonan->approve_bayar_by = null;
            $permohonan->approve_bayar_at = null;
            $permohonan->status           = 'proses-laporan';
            $permohonan->save();
        } else {
            $persetujuanPenawaran = PersetujuanPenawaran::create(
                $validated
            );

            if(isset($validated['nomor_tiket'])){
                $noc = Noc::where('nomor_tiket',$validated['nomor_tiket'])->first();
                if($noc){
                    $noc->persetujuan_penawaran_id = $persetujuanPenawaran->id;
                    $noc->permohonan_id            = $validated['permohonan_id'];
                    $noc->save();
                }
            }

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

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

            $bucok = [
                'tanggal_penuh'          => $persetujuanPenawaran->created_at ??  $validated['created_at'],
                'tanggal'                => $persetujuanPenawaran->created_at?->format('d') ??  $validated['created_at']?->format('d'),
                'bulan'                  => $persetujuanPenawaran->created_at?->format('m') ??  $validated['created_at']?->format('m'),
                'tahun'                  => $persetujuanPenawaran->created_at?->format('Y') ??  $validated['created_at']?->format('Y'),
                'nomor_tiket'            => $req['nomor_tiket'] ?? '',
                'nominal'                => $req['nominal_bayar'] ?? '',
                'nominal_berjalan'       => $req['nominal_bayar'] ?? '',
                'penyelesaian'           => 'Belum Selesai',
                'nama_sub_direktorat'    => $noc->branch?->name ?? '',
                'nama_direktorat_cabang' => $noc->branch?->name ?? '',
                'permohonan_id' => $permohonan->id,
                'nomor_registrasi' => $permohonan->nomor_registrasi,
            ];


            if(isset($req['nomor_tiket']) && $req['nomor_tiket'] !=''){
                Bucok::updateOrCreate([
                    'nomor_registrasi' => $permohonan->nomor_registrasi,
                    'nomor_tiket' => $req['nomor_tiket'],
                ], $bucok);
            } else {
                Bucok::updateOrCreate([
                    'nomor_registrasi' => $permohonan->nomor_registrasi
                ], $bucok);
            }

          // Update the status of the related permohonan to 'spk'

        if ($permohonan) {
            $permohonan->status_bayar = request()->get('status_bayar');
            $permohonan->save();

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

        }

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

    public function update(Request $request, $id): JsonResponse
    {
          // init
        $data     = [];
        $output   = [];
        $tindakan = null;
        if (request()->ajax()) {
            try {
                $data = [
                    'approve_bayar_by' => Auth::id(),
                    'approve_bayar_at' => now(),
                ];

                if ($request->keterangan) {
                    $data['approve_keterangan_bayar'] = $request->keterangan;
                }
                $output['data'] = $data;

                  // Update the status of the related permohonan to 'spk'
                $permohonan = Permohonan::find($id);

                if ($permohonan) {

                    if ($request->type === 'revisi') {
                        $data['status']       = 'revisi-pembayaran';
                        $data['status_bayar'] = 'belum_bayar';
                    } else {
                        $data['status_bayar'] = 'sudah_bayar';
                        $data['status']       = 'proses-laporan';

                        if ($permohonan->jenis_penilaian_id == 2) {
                            $data['status_bayar'] = 'sudah_bayar';
                            $data['status']       = 'spk';
                        }
                    }

                    if ($permohonan->jenis_penilaian_id == 1) {
                        unset(
                            $data['approval_so'],
                            $data['approval_so_at'],
                            $data['approval_eo'],
                            $data['approval_eo_at'],
                            $data['approval_dd'],
                            $data['approval_dd_at'],
                            $data['keterangan']
                        );

                    }

                    $permohonan->update($data);

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

                $output['status']  = 'success';
                $output['message'] = ['Otorisasi' . $permohonan->nomor_registrasi . 'berhasil di lakukan'];
            } catch (Exception $e) {
                $output['status']  = 'error';
                $output['message'] = ['Otorisasi gagal di lakukan.'];
            }
        }
        return response()->json($output);
    }

    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.');
        }

        $query = PersetujuanPenawaran::query();

        if (Auth::user()->hasAnyRole(['pemohon-ao','pemohon-eo'])) {
            $query = $query->whereRelation('permohonan', 'branch_id', Auth::user()->branch_id);
        }

        /*$query->where(function($q) {
            $q->whereRelation('permohonan', function($query) {
                $query->where('status_bayar', 'belum_bayar')
                    ->where('jenis_penilaian_id', 1);
            });
        });*/
        $query->orWhereRelation('permohonan','status_bayar','revisi-pembayaran');
        $query->orWhere(function($q) {
            $q->where('permohonan_id',null);
            $q->where('nomor_tiket','!=',null);
        });

        // Pencarian berdasarkan parameter search
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
        }

          // Sorting berdasarkan sortField dan sortOrder
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

          // Hitung total records
        $totalRecords = $query->count();

          // Pagination (default page size 10)
        $size = $request->get('size', 10);
        if ($size == 0) {
            $size = 10;
        }

        if ($request->has('page') && $request->has('size')) {
            $page   = $request->get('page', 1);
            $offset = ($page - 1) * $size;

            $query->skip($offset)->take($size);
        }

          // Filtered records
        $filteredRecords = $query->count();

          // Ambil data dengan relasi
        $data = $query->get();

        $data = $data->map(function ($item) {
            return [
                'id'         => $item->permohonan?->id ?? $item->id,
                'nomor_registrasi' => $item->permohonan?->nomor_registrasi,
                'nomor_tiket' => $item->nomor_tiket ?? '',
                'debiture' => $item->permohonan?->debiture ?? $item->noc?->debiture,
                'user'       => $item->permohonan?->user ?? $item->creator,
                'status_bayar' => $item->permohonan?->status_bayar ?? ($item->nomor_tiket ? 'Sudah Bayar' : ''),
                'tanggal_permohonan' => $item->permohonan?->tanggal_permohonan ?? '',
                'branch' => $item->permohonan?->branch ?? $item->noc?->branch,
                'is_permohonan' => $item->permohonan ?? ''
            ];
        });


          // Hitung jumlah halaman
        $pageCount = ceil($totalRecords / $size);

          // Ambil current page
        $currentPage = max(1, $request->get('page', 1));

          // Return JSON response
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $currentPage,
            'totalCount'      => $totalRecords,
            'data'            => $data,
        ]);
    }

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

        $query = Noc::query()->where(function ($query) {
            $query->where(['status_kurang_bayar' => '1'])
                ->where('bukti_ksl_kurang_bayar',null);
        });

          // Sorting berdasarkan sortField dan sortOrder
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

          // Hitung total records
        $totalRecords = $query->count();

          // Pagination (default page size 10)
        $size = $request->get('size', 10);
        if ($size == 0) {
            $size = 10;
        }

        if ($request->has('page') && $request->has('size')) {
            $page   = $request->get('page', 1);
            $offset = ($page - 1) * $size;

            $query->skip($offset)->take($size);
        }

          // Filtered records
        $filteredRecords = $query->count();

          // Ambil data dengan relasi
        $data = $query->get();

         $data = $data->map(function ($item) {
                return [
                    'id'         => $item->id,
                    'permohonan' => $item->permohonan,
                    'pemohon'    => $item->permohonan->user,
                    'branch'     => $item->permohonan->branch,
                    'debiture'   => $item->permohonan->debiture,
                    'nominal_kurang_bayar' => formatRupiah($item->nominal_kurang_bayar,2)
                ];
         });

          // Hitung jumlah halaman
        $pageCount = ceil($totalRecords / $size);

          // Ambil current page
        $currentPage = max(1, $request->get('page', 1));

          // Return JSON response
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $currentPage,
            'totalCount'      => $totalRecords,
            'data'            => $data,
        ]);
    }

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

        $query = Noc::query()->where(function ($query) {
            $query->where(['status_lebih_bayar' => '1'])
            ->where('bukti_ksl_lebih_bayar',null);
        });

          // Sorting berdasarkan sortField dan sortOrder
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

          // Hitung total records
        $totalRecords = $query->count();

          // Pagination (default page size 10)
        $size = $request->get('size', 10);
        if ($size == 0) {
            $size = 10;
        }

        if ($request->has('page') && $request->has('size')) {
            $page   = $request->get('page', 1);
            $offset = ($page - 1) * $size;

            $query->skip($offset)->take($size);
        }

          // Filtered records
        $filteredRecords = $query->count();

          // Ambil data dengan relasi
        $data = $query->get();

         $data = $data->map(function ($item) {
                return [
                    'id'         => $item->id,
                    'permohonan' => $item->permohonan,
                    'pemohon'    => $item->permohonan->user,
                    'branch'     => $item->permohonan->branch,
                    'debiture'   => $item->permohonan->debiture,
                    'nominal_lebih_bayar' => formatRupiah($item->nominal_lebih_bayar,2)
                ];
         });

          // Hitung jumlah halaman
        $pageCount = ceil($totalRecords / $size);

          // Ambil current page
        $currentPage = max(1, $request->get('page', 1));

          // Return JSON response
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $currentPage,
            'totalCount'      => $totalRecords,
            'data'            => $data,
        ]);
    }
}
