<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Exception;
    use Illuminate\Http\Request;
    use Modules\Lpj\Models\Permohonan;
    use Modules\Lpj\Models\PermohonanPembatalan;
    use Modules\Lpj\Services\PermohonanHistoryService;
    use Illuminate\Support\Facades\Auth;

    class PembatalanController extends Controller
    {
        public    $user;
        protected $historyService;

        public function __construct(PermohonanHistoryService $historyService)
        {
            $this->historyService = $historyService;
        }

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

        public function edit($id)
        {
            $pembatalan = PermohonanPembatalan::with(['permohonan.debiture','permohonan.branch'])->find($id);

            return view(
                'lpj::pembatalan.form',
                compact(
                    'pembatalan'
                ),
            );
        }

        public function update(Request $request, $id)
        {
            $pembatalan = PermohonanPembatalan::findOrFail($id);
            $permohonan = Permohonan::find($pembatalan->permohonan_id);
            $beforeRequest = $permohonan->toArray();

            try {
                // Update Permohonan Pembatalan
                if($request->status=='approved'){
                    $pembatalan->status = 'approved';
                    $pembatalan->authorized_at = now();
                    $pembatalan->authorized_by = auth()->user()->id;
                    $pembatalan->authorized_status = 1;
                    $pembatalan->save();

                    $permohonan->status = 'batal';
                    $permohonan->save();
                } else{
                    $pembatalan->status = 'rejected';
                    $pembatalan->authorized_at = now();
                    $pembatalan->authorized_by = auth()->user()->id;
                    $pembatalan->authorized_status = 3;
                    $pembatalan->save();
                }

                return redirect()
                    ->route('pembatalan.index')->with('success', 'Permohonan Pembatalan updated successfully');
            } catch (Exception $e) {
                return redirect()
                    ->route('pembatalan.edit', $id)->with('error', 'Failed to update permohonan Pembatalan');
            }
        }

        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(['pemohon-ao','pemohon-eo'])) {
                $query = $query->whereRelation('permohonan', '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 = $request->get('search');
                $query->where(function ($q) use ($search) {
                    $q->orWhereRelation('permohonan', 'nomor_registrasi', 'LIKE', '%' . $search . '%');
                    $q->orWhereRelation('permohonan.debiture', 'name', 'LIKE', '%' . $search . '%');
                    $q->orWhere('alasan_pembatalan', '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(['permohonan.debiture','permohonan.branch','creator'])->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,
            ]);
        }
    }
