<?php

namespace Modules\Lpj\Http\Controllers;

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

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();

        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['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['start_date'] && $search['end_date']) {
                    $query->betweenDates($request->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->format('d-m-Y'),
                'tahun'         => $item->tahun,
                'luas_tanah'    => $item->luas_tanah,
                'luas_bangunan' => $item->luas_bangunan,
                'harga'         => $item->harga,
                '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);

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