<?php

    namespace Modules\Lpj\Http\Controllers;

    use Illuminate\Http\Request;
    use Illuminate\Routing\Controller;
    use Log;
    use Modules\Location\Models\Province;
    use Modules\Lpj\Http\Requests\BankDataRequest;
    use Modules\Lpj\Models\BankData;
    use Modules\Lpj\Models\Inspeksi;
    use Modules\Lpj\Models\JenisJaminan;
    use Modules\Lpj\Services\BankDataService;

    class BankDataController extends Controller
    {
        protected $bankDataService;
        protected $user;

        public function __construct(BankDataService $bankDataService)
        {
            $this->bankDataService = $bankDataService;
        }

        public function index(Request $request)
        {
            $provinces    = Province::all();
            $jenisJaminan = JenisJaminan::all();

            //insert data pembanding

            $inspeksi = Inspeksi::all();

            foreach ($inspeksi as $item) {
                if (isset($item->data_pembanding)) {
                    $data_pembanding = json_decode($item->data_pembanding);

                    $objekPenilaian = $data_pembanding->objek_penilaian;
                    if (isset($objekPenilaian)) {
                        $_lat = $objekPenilaian->kordinat_lat;
                        $_lng = $objekPenilaian->kordinat_lng;

                        if (!empty($_lat) && !empty($_lng) && $_lng !== null && $_lat !== null && $_lat !== '' && $_lng !== '') {
                            $_lat = floatval($_lat);
                            $_lng = floatval($_lng);
                            if ($_lat >= -90 && $_lat <= 90 && $_lng >= -180 && $_lng <= 180) {

                                $_data          = [
                                    'address'          => $objekPenilaian->address,
                                    'village_code'     => $objekPenilaian->village_code,
                                    'district_code'    => $objekPenilaian->district_code,
                                    'city_code'        => $objekPenilaian->city_code,
                                    'province_code'    => $objekPenilaian->province_code,
                                    'tahun'            => $item->created_at->format('Y'),
                                    //
                                    'luas_tanah'       => isset($objekPenilaian->luas_tanah)  && is_numeric($objekPenilaian->luas_tanah) ? $objekPenilaian->luas_tanah : 0,
                                    'luas_bangunan'    => isset($objekPenilaian->luas_bangunan) && is_numeric($objekPenilaian->luas_bangunan) ? $objekPenilaian->luas_bangunan : 0,
                                    //
                                    'tahun_bangunan'   => isset($objekPenilaian->tahun_bangunan) && is_numeric($objekPenilaian->tahun_bangunan) ? $objekPenilaian->tahun_bangunan : 0,
                                    //
                                    'harga'            => isset($objekPenilaian->harga) && is_numeric($objekPenilaian->harga) ? $objekPenilaian->harga : 0,
                                    'harga_diskon'     => isset($objekPenilaian->harga_diskon) && is_numeric($objekPenilaian->harga_diskon) ? $objekPenilaian->harga_diskon : 0,
                                    'diskon'           => isset($objekPenilaian->diskon) && is_numeric(str_replace(',', '.', $objekPenilaian->diskon)) ? str_replace(',', '.', $objekPenilaian->diskon) : 0,
                                    'total'            => isset($objekPenilaian->total) && is_numeric($objekPenilaian->total) ? $objekPenilaian->total : 0,
                                    'harga_penawaran'  => isset($objekPenilaian->harga_penawaran) && is_numeric($objekPenilaian->harga_penawaran) ? $objekPenilaian->harga_penawaran : 0,
                                    'nama_nara_sumber' => $objekPenilaian->nama_nara_sumber,
                                    'peruntukan'       => $objekPenilaian->peruntukan ?? "",
                                    //
                                    'penawaran'        => $objekPenilaian->penawaran ?? "",
                                    //
                                    'telepon'          => $objekPenilaian->telepon ?? "",
                                    'hak_properti'     => $objekPenilaian->hak_properti ?? "",
                                    'jenis_aset'       => $objekPenilaian->jenis_aset ?? "",
                                    'foto_objek'       => $objekPenilaian->foto_objek ?? "",
                                    'tanggal'          => $objekPenilaian->tanggal ?? null,
                                    'kategori'         => 'penilaian',
                                ];


                                BankData::updateOrCreate(
                                    [
                                        'kordinat_lat' => $_lat,
                                        'kordinat_lng' => $_lng,
                                        'kategori'     => 'penilaian'
                                    ],
                                    $_data
                                );
                            }
                        } else {
                            // Invalid coordinates
                            Log::warning("Invalid coordinates: Lat: $_lat, Lng: $_lng");// Do something to handle this situation, such as logging an error or skipping the record
                        }
                    }

                    foreach ($data_pembanding->data_pembanding as $dataPembanding) {
                        $lat = $dataPembanding->kordinat_lat;
                        $lng = $dataPembanding->kordinat_lng;

                        if (!empty($lat) && !empty($lng) && $lng !== null && $lat !== null && $lat !== '' && $lng !== '') {
                            $lat = floatval($lat);
                            $lng = floatval($lng);

                            if ($lat >= -90 && $lat <= 90 && $lng >= -180 && $lng <= 180) {
                                $data = [
                                    'address'          => $dataPembanding->address,
                                    'village_code'     => $dataPembanding->village_code,
                                    'district_code'    => $dataPembanding->district_code,
                                    'city_code'        => $dataPembanding->city_code,
                                    'province_code'    => $dataPembanding->province_code,
                                    'tahun'            => isset($dataPembanding->tahun) && is_numeric($dataPembanding->tahun) ? $dataPembanding->tahun : 0,
                                    'luas_tanah'       => isset($dataPembanding->luas_tanah) && is_numeric($dataPembanding->luas_tanah) ? $dataPembanding->luas_tanah : 0,
                                    'luas_bangunan'    => isset($dataPembanding->luas_bangunan) && is_numeric($dataPembanding->luas_bangunan) ? $dataPembanding->luas_bangunan : 0,
                                    'tahun_bangunan'   => isset($dataPembanding->tahun_bangunan) && is_numeric($dataPembanding->tahun_bangunan) ? $dataPembanding->tahun_bangunan : 0,
                                    'harga'            => isset($dataPembanding->harga) && is_numeric($dataPembanding->harga) ? $dataPembanding->harga : 0,
                                    'harga_diskon'     => isset($dataPembanding->harga_diskon) && is_numeric($dataPembanding->harga_diskon) ? $dataPembanding->harga_diskon : 0,
                                    'diskon'           => isset($dataPembanding->diskon) && is_numeric(str_replace(',', '.', $dataPembanding->diskon)) ? str_replace(',', '.', $dataPembanding->diskon) : 0,
                                    'total'            => isset($dataPembanding->total) && is_numeric($dataPembanding->total) ? $dataPembanding->total : 0,
                                    'harga_penawaran'  => isset($dataPembanding->harga_penawaran) && is_numeric($dataPembanding->harga_penawaran) ? $dataPembanding->harga_penawaran : 0,
                                    'nama_nara_sumber' => $dataPembanding->nama_nara_sumber,
                                    'peruntukan'       => $dataPembanding->peruntukan,
                                    'penawaran'        => $dataPembanding->penawaran,
                                    'telepon'          => $dataPembanding->telepon,
                                    'hak_properti'     => $dataPembanding->hak_properti,
                                    'jenis_aset'       => $dataPembanding->jenis_aset,
                                    'foto_objek'       => $dataPembanding->foto_objek,
                                    'tanggal'          => $dataPembanding->tanggal,
                                    'kategori'         => 'data_pembanding',
                                ];

                                BankData::updateOrCreate(
                                    [
                                        'kordinat_lat' => $lat,
                                        'kordinat_lng' => $lng,
                                        'kategori'     => 'data_pembanding'
                                    ],
                                    $data
                                );
                            }
                        } else {
                            // Invalid coordinates
                            Log::warning("Invalid coordinates: Lat: $lat, Lng: $lng");// Do something to handle this situation, such as logging an error or skipping the record
                        }
                    }
                }
            }

            return view('lpj::bank-data.index', compact('provinces', 'jenisJaminan'));
        }

        public function create()
        {
            return view('lpj::bank-data.create');
        }

        public function store(BankDataRequest $request)
        {
            $data     = $request->validated();
            $bankData = $this->bankDataService->createBankData($data);
            return redirect()
                ->route('lpj.bank-data.show', $bankData->id)
                ->with('success', 'Bank data created successfully.');
        }

        public function show($id)
        {
            $bankData = $this->bankDataService->findBankData($id);
            return view('lpj::bank-data.show', compact('bankData'));
        }

        public function edit($id)
        {
            $bankData = $this->bankDataService->findBankData($id);
            return view('lpj::bank-data.edit', compact('bankData'));
        }

        public function update(BankDataRequest $request, $id)
        {
            $data     = $request->validated();
            $bankData = $this->bankDataService->updateBankData($id, $data);
            return redirect()
                ->route('lpj.bank-data.show', $bankData->id)
                ->with('success', 'Bank data updated successfully.');
        }

        public function destroy($id)
        {
            $this->bankDataService->deleteBankData($id);
            return redirect()->route('lpj.bank-data.index')->with('success', 'Bank data deleted successfully.');
        }

        public function dataForDatatables(Request $request)
        {
            if (is_null($this->user) || !$this->user->can('bank-data.view')) {
                //abort(403, 'Sorry! You are not allowed to view bank data.');
            }

            // Retrieve data from the database
            $query = BankData::query();

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

                    if ($search['province_code']) {
                        $query->ofProvince($search['province_code']);
                    }

                    if ($search['kategori']) {
                        $query->where('kategori', $search['kategori']);
                    }

                    if ($search['city_code']) {
                        $query->ofCity($search['city_code']);
                    }

                    if ($search['district_code']) {
                        $query->ofDistrict($search['district_code']);
                    }

                    if ($search['village_code']) {
                        $query->ofVillage($search['village_code']);
                    }

                    if ($search['jenis_asset']) {
                        $query->ofAssetType($search['jenis_asset']);
                    }

                    if ($search['tahun']) {
                        $query->where('tahun', $search['tahun']);
                    }

                    if ($search['start_date'] && $search['end_date']) {
                        $query->betweenDates($search['start_date'], $search['end_date']);
                    }
                } else {
                    $search = $request->get('search');
                    $query->where(function ($q) use ($search) {
                        $q->where('jenis_aset', '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->get();

            // Format the data as needed
            $formattedData = $data->map(function ($item) {
                return [
                    'id'            => $item->id,
                    'jenis_aset'    => $item->jenis_aset,
                    'tanggal'       => $item->tanggal ? $item->tanggal->format('d-m-Y') : '-',
                    'tahun'         => $item->tahun,
                    'luas_tanah'    => $item->luas_tanah,
                    'luas_bangunan' => $item->luas_bangunan,
                    'harga'         => $item->harga,
                    'sumber'        => $item->kategori ? ucwords(str_replace('_', ' ', $item->kategori)) : '-',
                    'kategori'        => $item->kategori ?? 'data_pembanding',
                    'nilai_pasar'   => $item->nilai_pasar,
                    'location'      => $item->kordinat_lat . ', ' . $item->kordinat_lng,
                    'address'       => formatAlamat($item),
                    'photos'        => json_decode($item->foto_objek, true) ?: [$item->foto_objek],
                    // Add more fields as needed
                ];
            });

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

            // Calculate the current page number
            $currentPage = $request->get('page', 1);

            // Ensure current page doesn't exceed page count
            $currentPage = min($currentPage, $pageCount);


            // 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'            => $formattedData,
            ]);
        }
    }
