<?php

namespace App\Http\Controllers\MasterData;

use App\Http\Controllers\Controller;
use App\Models\Land;
use App\Models\LandDetails;
use App\Models\Province;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class LandController extends Controller
{
    public function index()
    {
        $lands = Land::with('province', 'regency')->orderBy('created_at', 'desc')->get();
        return view('master-data.lahan.index', compact('lands'));
    }

    public function create()
    {
        $provinces = Province::all();
        return view('master-data.lahan.create', compact('provinces'));
    }

    public function store(Request $request)
    {
        $customMessage = [
            'owner.required' => 'Nama pemilik wajib diisi',
            'owner.max' => 'Nama pemilik maksimal 25 karakter',
            'owner.string' => 'Nama pemilik harus berupa string',

            'province_id.required' => 'Provinsi wajib diisi',
            'province_id.exists' => 'Provinsi tidak ditemukan',

            'regency_id.required' => 'Kota wajib diisi',
            'regency_id.exists' => 'Kota tidak ditemukan',

            'district_id.required' => 'Kecamatan wajib diisi',
            'district_id.exists' => 'Kecamatan tidak ditemukan',

            'address.required' => 'Alamat wajib diisi',
            'address.max' => 'Alamat maksimal 100 karakter',
            'address.string' => 'Alamat harus berupa string',

            'lat.required' => 'Latitude wajib diisi',
            'lat.numeric' => 'Latitude harus berupa angka',

            'lng.required' => 'Longitude wajib diisi',
            'lng.numeric' => 'Longitude harus berupa angka',

            'polygon.required' => 'Petak lahan wajib digambar',
        ];

        $validator = Validator::make($request->all(), [
            'owner' => 'required|string|max:25',
            'province_id' => 'required|exists:provinces,id',
            'regency_id' => 'required|exists:regencies,id',
            'district_id' => 'required|exists:districts,id',
            'address' => 'required|string|max:100',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
            'polygon' => 'required',
        ], $customMessage);

        $polygon = json_decode($request->polygon, true);

        if ($validator->fails()) {
            toast($validator->messages()->all()[0], 'error')->position('top')->autoclose(3000);
            return redirect()->back()->withInput();
        }

        DB::beginTransaction();
        try {
            $land = new Land();
            $land->user_id = Auth::user()->id;
            $land->owner = $request->owner;
            $land->province_code = $request->province_id;
            $land->regency_code = $request->regency_id;
            $land->district_code = $request->district_id;
            $land->address = $request->address;
            $land->latitude = $request->lat;
            $land->longitude = $request->lng;
            $land->save();

            foreach ($polygon as $point) {
                $landDetails = new LandDetails();
                $landDetails->land_id = $land->id;
                $landDetails->lat = $point['lat'];
                $landDetails->lng = $point['lng'];
                $landDetails->save();
            }
            DB::commit();
            toast('Data berhasil disimpan', 'success')->position('top-right')->autoclose(3000);

            if (Auth::user()->role == 'admin') {
                return redirect()->route('master_data.lahan.index');
            }

            return redirect()->route('lahan.index');
        } catch (\Throwable $th) {
            DB::rollBack();
            toast('Terjadi kesalahan', 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }

    public function edit($id)
    {
        $land = Land::with('detailLands')->findOrFail($id);
        $provinces = Province::all();
        $landDetails = $land->detailLands->map(function ($detail) {
            return [
                'lat' => $detail->lat,
                'lng' => $detail->lng,
            ];
        });

        return view('master-data.lahan.edit', compact('id', 'provinces', 'land', 'landDetails'));
    }

    public function update(Request $request, $id)
    {

        $customMessage = [
            'owner.required' => 'Nama pemilik wajib diisi',
            'owner.max' => 'Nama pemilik maksimal 25 karakter',
            'owner.string' => 'Nama pemilik harus berupa string',

            'province_id.required' => 'Provinsi wajib diisi',
            'province_id.exists' => 'Provinsi tidak ditemukan',

            'regency_id.required' => 'Kota wajib diisi',
            'regency_id.exists' => 'Kota tidak ditemukan',

            'district_id.required' => 'Kecamatan wajib diisi',
            'district_id.exists' => 'Kecamatan tidak ditemukan',

            'address.required' => 'Alamat wajib diisi',
            'address.max' => 'Alamat maksimal 100 karakter',
            'address.string' => 'Alamat harus berupa string',

            'lat.required' => 'Latitude wajib diisi',
            'lat.numeric' => 'Latitude harus berupa angka',

            'lng.required' => 'Longitude wajib diisi',
            'lng.numeric' => 'Longitude harus berupa angka',

            'polygon.required' => 'Petak lahan wajib digambar',
        ];

        $validator = Validator::make($request->all(), [
            'owner' => 'required|string|max:25',
            'province_id' => 'required|exists:provinces,id',
            'regency_id' => 'required|exists:regencies,id',
            'district_id' => 'required|exists:districts,id',
            'address' => 'required|string|max:100',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
            'polygon' => 'required',
        ], $customMessage);

        $polygon = json_decode($request->polygon, true);

        if ($validator->fails()) {
            toast($validator->messages()->all()[0], 'error')->position('top')->autoclose(3000);
            return redirect()->back()->withInput();
        }

        DB::beginTransaction();
        try {
            $land = Land::findOrFail($id);
            $land->user_id = Auth::user()->id;
            $land->owner = $request->owner;
            $land->province_code = $request->province_id;
            $land->regency_code = $request->regency_id;
            $land->district_code = $request->district_id;
            $land->address = $request->address;
            $land->latitude = $request->lat;
            $land->longitude = $request->lng;
            $land->save();

            LandDetails::where('land_id', $land->id)->delete();

            foreach ($polygon as $point) {
                $landDetails = new LandDetails();
                $landDetails->land_id = $land->id;
                $landDetails->lat = $point['lat'];
                $landDetails->lng = $point['lng'];
                $landDetails->save();
            }
            DB::commit();
            toast('Data berhasil diubah', 'success')->position('top-right')->autoclose(3000);

            if (Auth::user()->role == 'admin') {
                return redirect()->route('master_data.lahan.index');
            }

            return redirect()->route('lahan.index');
        } catch (\Throwable $th) {
            DB::rollBack();
            dd($th->getMessage());
            toast('Terjadi kesalahan', 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }

    public function destroy($id)
    {
        $land = Land::find($id);
        try {
            $land->delete();
            toast('Data berhasil dihapus', 'success')->position('top-right')->autoclose(3000);
            return redirect()->back();
        } catch (\Throwable $th) {
            toast('Terjadi kesalahan', 'error')->position('top')->autoclose(3000);
            return redirect()->back();
        }
    }
}
