<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\DB;
    use Maatwebsite\Excel\Facades\Excel;
    use Modules\Lpj\Exports\LaporanPembatalanExport;
    use Modules\Lpj\Models\PermohonanPembatalan;

    class LaporanPembatalanController extends Controller
    {
        public $user;

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

        public function export(Request $request)
        {
            return Excel::download(new LaporanPembatalanExport($request), 'laporan_pembatalan.xlsx');
        }

        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 = PermohonanPembatalan::query();


            if (!Auth::user()->hasAnyRole(['administrator'])) {
                $query = $query->whereHas('permohonan', function ($q) {
                    $q->where('branch_id', Auth::user()->branch_id);
                });
            }

            $query = $query->orderBy('created_at', 'desc');

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

                if (isset($search->start_date) || isset($search->end_date)) {
                    $query->whereBetween('created_at', [
                        $search->start_date ?? '1900-01-01',
                        $search->end_date ?? now()->toDateString()
                    ]);
                }

                // Filter by branch if provided
                if (isset($search->branch_id) && !empty($search->branch_id)) {
                    $query->whereHas('permohonan', function ($q) use ($search) {
                        $q->where('branch_id', $search->branch_id);
                    });
                }

                if (isset($search->search)) {
                    $query->where(function ($q) use ($search) {
                        $q->whereHas('permohonan', function ($subq) use ($search) {
                            $subq->where('nomor_registrasi', 'LIKE', '%' . $search->search . '%');
                            $subq->orWhereRelation('user', 'name', 'LIKE', '%' . $search->search . '%');
                            $subq->orWhereRelation('branch', 'name', 'LIKE', '%' . $search->search . '%');
                        });
                        $q->orWhere('alasan_pembatalan', '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();
            $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->get();

            $data = $data->map(function ($item) {
                return [
                    'id'                 => $item->id,
                    'nomor_registrasi'   => $item->permohonan->nomor_registrasi ?? '-',
                    'tanggal_permohonan' => $item->permohonan->tanggal_permohonan ? date('d-m-Y', strtotime($item->permohonan->tanggal_permohonan)) : '-',
                    'tanggal_pembatalan' => date('d-m-Y', strtotime($item->created_at)),
                    'cabang'             => $item->permohonan->branch->name ?? '-',
                    'pemohon'            => $item->permohonan->user->name ?? '-',
                    'debitur'            => $item->permohonan->debiture->name ?? '-',
                    'alasan_pembatalan'  => $item->alasan_pembatalan,
                    'status'             => $item->status,
                    'diajukan_oleh'      => $item->user->name ?? '-',
                    'disetujui_oleh'     => $item->authorized_by ? $item->authorizedUser->name : '-',
                    'tanggal_disetujui'  => $item->authorized_at ? formatTanggalIndonesia(strtotime($item->authorized_at),1) : '-'
                ];
            });


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