<?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;
use Modules\Lpj\Models\Branch;
use Modules\Lpj\Services\PreviewLaporanService;
use Modules\Lpj\Models\Inspeksi;
use Modules\Lpj\Models\Penilai;

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

    protected $previewLaporanService;

    public function __construct(PreviewLaporanService $previewLaporanService)
    {
        $this->previewLaporanService = $previewLaporanService;
    }

    public function index()
    {
        $status_permohonan = StatusPermohonan::all();
        return view('lpj::laporan-penilai-jaminan.index', compact('status_permohonan'));
    }


    /**
     * Show the specified resource.
     */
    public function show($permohonan_id, $dokumen_id, $jaminan_id)
    {
        $back = route('laporan-penilai-jaminan.index');
        return $this->previewLaporanService->previewLaporan($permohonan_id, $dokumen_id, $jaminan_id, $back);
    }



    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();
        $query = $query->where('status', 'done')->orderBy('tanggal_permohonan', 'desc');
        // Apply search filter if provided
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = json_decode($request->get('search'));

            if (!empty($search->start_date) || !empty($search->end_date)) {
                $startDate = $search->start_date ?? '1900-01-01';
                $endDate = $search->end_date ?? now()->toDateString();

                $query->where(function ($q) use ($startDate, $endDate) {

                    $q->whereHas('penilaian', function ($q2) use ($startDate, $endDate) {
                        $q2->whereBetween('tanggal_kunjungan', [$startDate, $endDate]);
                    });

                    // OR check if has penawaran with date in range
                    $q->orWhereHas('penawaran', function ($q3) use ($startDate, $endDate) {
                        $q3->whereBetween('tanggal_penilaian_sebelumnya', [$startDate, $endDate]);
                    });
                });


            }


            if (isset($search->branch_id) && !empty($search->branch_id)) {
                $query->where('branch_id', $search->branch_id);
            }

            if (isset($search->laporan) && is_array($search->laporan) && !empty($search->laporan)) {
                foreach ($search->laporan as $type) {
                    $query->whereHas('penilai', function ($q) use ($type) {
                        $q->where('type_penilai', 'LIKE', '%' . $type . '%');
                    });
                }
            }


            // dd($search->search);

            if (isset($search->search)) {

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

                    $q->orWhereRelation('jenisFasilitasKredit', 'name', 'LIKE', '%' . $search->search . '%');
                    $q->orWhereRelation('jenisPenilaian', 'name', 'LIKE', '%' . $search->search . '%');
                    $q->orWhere('status', 'LIKE', '%' . $search->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 data with necessary relationships
        $data = $query->with(['user', 'debiture', 'branch', 'tujuanPenilaian', 'penilaian', 'dokumenjaminan.jenisJaminan','nilaiPlafond', 'penilai', 'dokumenjaminan.inspeksi'])->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,
        ]);
    }

    public function export(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');

        // Validate the date format
        if (isset($startDate) && isset($endDate)) {
            $startDate = date('Y-m-d', strtotime($startDate));
            $endDate = date('Y-m-d', strtotime($endDate));

            if ($startDate > $endDate) {
                return redirect()->back()->with('error', 'Tanggal awal tidak boleh lebih kecil dari tanggal akhir');
            }
        }
        // name the file
        $filename = $this->createNameLaporan($request);

        return Excel::download(
            new LaporanPenilaiJaminanExport($request),
            $filename
        );
    }


    public function createNameLaporan($request)
    {
        $startDate = $request->start_date ?? null;
        $endDate = $request->end_date ?? null;
        $branchId = $request->branch_id ?? null;
        $laporan = $request->laporan ?? null;

        // Initialize filename parts
        $parts = ['Laporan Penilai Jaminan'];
        if ($startDate && $endDate) {
            $parts[] = "{$startDate}_{$endDate}";
        }
        if ($laporan) {
            $parts[] = $laporan;
        }
        if ($branchId) {
            $parts[] = $this->getBranchId($branchId);
        }
        // Return concatenated filename with extension
        return implode('_', $parts) . '.xlsx';
    }

    public function getBranchId($branchId)
    {
        $branchesName = Branch::find($branchId)->name ?? null;
        return $branchesName;
    }
}
