<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Exception;
    use Illuminate\Http\Request;
    use Maatwebsite\Excel\Facades\Excel;
    use Modules\Location\Models\City;
    use Modules\Location\Models\District;
    use Modules\Location\Models\Province;
    use Modules\Location\Models\Village;
    use Modules\Lpj\Exports\DebitureExport;
    use Modules\Lpj\Http\Requests\DebitureRequest;
    use Modules\Lpj\Http\Requests\DokumenJaminanRequest;
    use Modules\Lpj\Models\Branch;
    use Modules\Lpj\Models\Debiture;
    use Modules\Lpj\Models\DokumenJaminan;
    use Modules\Lpj\Models\JenisJaminan;
    use Modules\Lpj\Models\JenisLegalitasJaminan;
    use Modules\Lpj\Models\PemilikJaminan;
    use Illuminate\Support\Facades\Auth;

    class DebitureController extends Controller
    {
        public $user;

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

        public function store(DebitureRequest $request)
        {
            $validate = $request->validated();

            if ($validate) {
                try {
                    // Save to database
                    Debiture::create($validate);
                    return redirect()
                        ->route('debitur.index')
                        ->with('success', 'Debitur created successfully');
                } catch (Exception $e) {
                    return redirect()
                        ->route('debitur.create')
                        ->with('error', 'Failed to create debitur');
                }
            }
        }

        public function create()
        {
            $branches  = Branch::all();
            $provinces = Province::all();
            return view('lpj::debitur.create', compact('branches', 'provinces'));
        }

        public function edit($id)
        {
            $debitur   = Debiture::find($id);
            $branches  = Branch::all();
            $provinces = Province::all();
            $cities    = City::where('province_code', $debitur->province_code)->get();
            $districts = District::where('city_code', $debitur->city_code)->get();
            $villages  = Village::where('district_code', $debitur->district_code)->get();
            return view(
                'lpj::debitur.edit',
                compact('debitur', 'branches', 'provinces', 'cities', 'districts', 'villages'),
            );
        }

        public function update(DebitureRequest $request, $id)
        {
            //print_r($request->all());exit;
            $validate = $request->validated();

            if ($validate) {
                try {
                    // Update in database
                    $debitur = Debiture::find($id);
                    $debitur->update($validate);
                    return redirect()
                        ->route('debitur.index')
                        ->with('success', 'Debitur updated successfully');
                } catch (Exception $e) {
                    return redirect()
                        ->route('debitur.edit', $id)
                        ->with('error', 'Failed to update debitur');
                }
            }
        }

        public function destroy($id)
        {
            try {
                // Periksa apakah pengguna adalah administrator
                if (!auth()->user()->hasRole('administrator')) {
                    return response()->json(['success' => false, 'message' => 'Hanya administrator yang dapat menghapus debitur'], 403);
                }

                // Temukan debitur
                $debitur = Debiture::find($id);

                if (!$debitur) {
                    return response()->json(['success' => false, 'message' => 'Debitur tidak ditemukan'], 404);
                }

                // Periksa apakah debitur memiliki permohonan aktif
                if ($debitur->permohonan()->exists()) {
                    return response()->json(['success' => false, 'message' => 'Tidak dapat menghapus debitur yang masih memiliki permohonan aktif'], 400);
                }

                // Hapus dari database
                $debitur->delete();

                return response()->json(['success' => true, 'message' => 'Debitur berhasil dihapus']);
            } catch (Exception $e) {
                return response()->json(['success' => false, 'message' => 'Gagal menghapus debitur: ' . $e->getMessage()], 500);
            }
        }

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

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

            // 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('cif', 'LIKE', "%$search%");
                    $q->orWhere('name', 'LIKE', "%$search%");
                    $q->orWhereRelation('branch', 'name', 'LIKE', "%$search%");
                    $q->orWhere('address', 'LIKE', "%$search%");
                    $q->orWhere('npwp', 'LIKE', "%$search%");
                    $q->orWhere('nomor_id', 'LIKE', "%$search%");
                    $q->orWhere('email', 'LIKE', "%$search%");
                    $q->orWhere('phone', 'LIKE', "%$search%");
                    $q->orWhere('nomor_rekening', '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();

            // 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(['branch','permohonan'])->get();

            // Calculate the page count
            $pageCount = ceil($totalRecords / $request->get('size'));

            // Calculate the current page number
            $currentPage = 0 + 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()
        {
            return Excel::download(new DebitureExport, 'debitur.xlsx');
        }
    }
