<?php

namespace Modules\Lpj\Http\Controllers;

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

// use Modules\Lpj\Models\JenisPenilaian;

// use Modules\Lpj\Models\Regions;

class PembayaranController extends Controller
{
    public $user;

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

    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();

        // 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 edit($id)
    {
        $permohonan = Permohonan::find($id);

        $persetujuanPenawaran = PersetujuanPenawaran::where('permohonan_id', $permohonan->id)->first();
        return view('lpj::pembayaran.form', compact('permohonan', 'persetujuanPenawaran'));
    }

    public function store(PersetujuanPenawaranRequest $request)
    {
        $validated               = $request->validated();
        $validated['created_by'] = Auth::id();
        $validated['status']     = '0';

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

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

            $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 = 'done';
            $permohonan->save();
        } else {
            $persetujuanPenawaran = PersetujuanPenawaran::create(
                $validated
            );

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

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

        // 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 = Permohonan::query()->where(function ($query) {
            $query->where(['status_bayar' => 'belum_bayar', 'jenis_penilaian_id' => 1])
                  ->orWhere('status', 'revisi-pembayaran');
        })
        ->where(function ($query) {
            $query->whereNotIn('id', function ($subquery) {
                $subquery->select('permohonan_id')
                         ->from('persetujuan_penawaran')
                         ->whereNotNull('permohonan_id');
            })
            ->orWhere('status', 'revisi-pembayaran');
        });


        // Pencarian berdasarkan parameter search
        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->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('jenisPenilaian', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhere('status', 'LIKE', '%' . $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->with(['user', 'debiture', 'branch', 'jenisPenilaian'])->get();


        // 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,
        ]);
    }
}
