<?php

namespace Modules\Lpj\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Lpj\Models\Permohonan;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Lpj\Http\Controllers\PenilaiController;

class LaporanController extends Controller
{
    public $user;
    public $penilaiController;
    /**
     * Display a listing of the resource.
     */

    public function __construct(PenilaiController $penilaiController){
        $this->penilaiController = $penilaiController;
    }

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

    public function sederhana_index()
    {
        return view('lpj::laporan.sederhana_index');
    }

    public function standard_index()
    {
        return view('lpj::laporan.standard_index');
    }

    /**
     * Show the specified resource.
     */
    public function show($id) {
        $permohonan = Permohonan::with([
            'penilai',
            'dokumenjaminan',
            ])->find($id);

        if ($permohonan->penilai->type_penilai == 'memo') {
           return $this->penilaiController->print_out($request = new Request(['documentId' => $permohonan->penilai->dokument_id, 'jaminanId' => $permohonan->dokumenjaminan[0]->jenis_jaminan_id, 'permohonanId' => $permohonan->id, 'statusLpj' => 1, 'type' => 'memo']));
        }

        if ($permohonan->penilai->type_penilai == 'rap') {
            return $this->penilaiController->print_out($request = new Request(['documentId' => $permohonan->penilai->dokument_id, 'jaminanId' => $permohonan->dokumenjaminan[0]->jenis_jaminan_id, 'permohonanId' => $permohonan->id, 'statusLpj' => 1, 'type' => 'rap']));
        }

        return view('lpj::laporan.show', compact('permohonan'));
    }
    /**
     * Store form inspeksi.
     */
    public function store(Request $request) {
        $permohonan = Permohonan::find($request->permohonan_id);
        if($request->nilai_liquidasi) {
            $permohonan->nilai_liquidasi = $request->liquidasi;
            $permohonan->save();
            return redirect()->route('laporan.index')->with('success', 'Nilai Liquidasi updated successfully');
        }
    }

    public function update(Request $request, $id) {}

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

        // Retrieve data from the database
        $query = Permohonan::query()
            ->whereIn('status',['proses-laporan','done', 'paparan', 'proses-paparan']);

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

        $query = $query->orderBy('nomor_registrasi', 'desc');
        // 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 . '%');
                $q->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('tujuanPenilaian', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhere('status', '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();
        $size         = $request->get('size', 10);
        if ($size == 0) {
            $size = 10;
        }

        // 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(['user', 'debiture', 'branch', 'tujuanPenilaian', 'penilaian','jenisFasilitasKredit', 'documents.inspeksi','penilai','documents.detail','noc'])->get();

        // Calculate the page count
        $pageCount = ceil($totalRecords / $size);

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