<?php

namespace Modules\Lpj\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Models\StatusPermohonan;
use Modules\Lpj\Exports\LaporanPenilaiJaminanExport;
use Maatwebsite\Excel\Facades\Excel;

class LaporanPenilaiJaminanController extends Controller
{
    public $user;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $status_permohonan = StatusPermohonan::all();
        return view('lpj::laporan-penilai-jaminan.index', compact('status_permohonan'));
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Show the specified resource.
     */
    public function show($id)
    {
        return view('lpj::laporan-penilai-jaminan.show');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        return view('lpj::edit');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        //
    }

    public function dataForDatatables(Request $request)
    {

        $user = auth()->user();


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

        $userRole = $user->roles->pluck('name')->first();
        $regionId = null;

        // If user is senior-officer, get their regionId
        if ($userRole === 'senior-officer') {
            $userTeam = TeamsUsers::with('team')->firstWhere('user_id', $user->id);
            $regionId = $userTeam?->team->regions_id;
        }
        $paramsSearch = null;
        // dd($startDate);
        // Retrieve data from the database
        $query = Permohonan::query();

        // Apply search filter if provided
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
            $paramsSearch = json_decode($search);

            $query->where(function ($q) use ($search) {
                $q->where('nomor_registrasi', 'LIKE', '%' . $search . '%')
                  ->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%')
                  ->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%')
                  ->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%')
                  ->orWhereRelation('tujuanPenilaian', 'name', 'LIKE', '%' . $search . '%')
                  ->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%');

                  if (!empty($paramsSearch->tanggal_awal) && !empty($paramsSearch->tanggal_akhir)) {
                    $q->whereBetween('tanggal_permohonan', [$paramsSearch->tanggal_awal, $paramsSearch->tanggal_akhir]);
                }


                $statusKeywords = explode(',', $search);
                foreach ($statusKeywords as $keyword) {
                    $q->orWhereRelation('penilai', 'type_penilai', 'LIKE', '%' . trim($keyword) . '%');
                }
            });
        }
        $query->where('status', 'done');



        // Default sorting if no sort provided
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        } else {
            $query->orderBy('nomor_registrasi', 'asc');
        }

        // Get total count of records before pagination
        $totalRecords = $query->count();

        // Pagination
        if ($request->has('page') && $request->has('size')) {
            $page = (int) $request->get('page', 1);
            $size = (int) $request->get('size', 10);
            $offset = ($page - 1) * $size;
            $query->skip($offset)->take($size);
        }

        // Get filtered count
        $filteredRecords = $query->count();



        $totalRecords = $query->count();

        // Pagination
        if ($request->has('page') && $request->has('size')) {
            $page = (int) $request->get('page', 1);
            $size = (int) $request->get('size', 10);
            $offset = ($page - 1) * $size;
            $query->skip($offset)->take($size);
        }

        // Get filtered count
        $filteredRecords = $query->count();

        // Get data with necessary relationships
        $data = $query->with(['user', 'debiture', 'branch', 'tujuanPenilaian', 'penilaian', 'dokumenjaminan.jenisJaminan','nilaiPlafond', 'penilai'])->get();

        // Calculate total pages
        $pageCount = ceil($totalRecords / $request->get('size', 10));




        // Calculate total pages
        $pageCount = ceil($totalRecords / $request->get('size', 10));

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

    public function export(Request $request)
    {
        $tanggalAwal = $request->input('tanggal_awal');
        $tanggalAkhir = $request->input('tanggal_akhir');
        $status = $request->input('status');
        $selectedIds = $request->input('selected_ids');

        $filename = 'laporan_penilai_jaminan_' . date('YmdHis') . '.xlsx';
        return Excel::download(
            new LaporanPenilaiJaminanExport($tanggalAwal, $tanggalAkhir, $status, $selectedIds),
            $filename
        );
    }
}
