<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\LokasiTps;
use App\Models\KategoriTps;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class TpsController extends Controller
{

    public function index(Request $request)
    {
        $title = 'Data TPS';

        $search = $request->search;

        $tps = LokasiTps::with('kategori')
            ->withCount('aduan')
            ->when($search, function ($query) use ($search) {
                $query->where('nama_tps', 'like', '%' . $search . '%');
            })
            ->orderBy('id_tps', 'desc')
            ->paginate(10);

        return view('admin.tps.index', compact('title', 'tps', 'search'));
    }


    public function create()
    {
        $title = 'Tambah TPS';
        $kategori = KategoriTps::all();

        return view('admin.tps.create', compact('title', 'kategori'));
    }


    private function convertToDecimal($coordinate)
    {
        if (is_numeric($coordinate)) {
            return (float) $coordinate;
        }

        if (!$coordinate) return null;

        $coordinate = html_entity_decode($coordinate);
        $coordinate = strtoupper(trim($coordinate));
        $coordinate = str_replace(['°', "'", '"'], [' ', ' ', ' '], $coordinate);

        preg_match('/([NSEW])/', $coordinate, $dir);
        preg_match_all('/\d+(\.\d+)?/', $coordinate, $numbers);

        if (!$dir || count($numbers[0]) < 3) return null;

        [$deg, $min, $sec] = array_map('floatval', $numbers[0]);

        $decimal = $deg + ($min / 60) + ($sec / 3600);

        if (in_array($dir[1], ['S', 'W'])) {
            $decimal *= -1;
        }

        return $decimal;
    }


    public function store(Request $request)
    {

        $validator = Validator::make($request->all(), [

            'kategori_tps_id' => 'required|exists:kategori_tps,id_kategori_tps',
            'nama_tps' => 'required|string|max:255',
            'alamat_tps' => 'required|string|max:255',
            'status_tps' => 'required|in:Aktif,Tidak Aktif,Pembangunan',
            'tahun_pembuatan' => 'required|digits:4',
            'kapasitas_tps' => 'required|integer|min:1',
            'latitude' => 'required',
            'longitude' => 'required',
            'foto_tps' => 'required|image|mimes:jpg,jpeg,png|max:2048',

        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }


        $latitude = $this->convertToDecimal($request->latitude);
        $longitude = $this->convertToDecimal($request->longitude);


        if ($latitude === null || $latitude < -90 || $latitude > 90) {
            $validator->errors()->add('latitude', 'Latitude tidak valid.');
        }

        if ($longitude === null || $longitude < -180 || $longitude > 180) {
            $validator->errors()->add('longitude', 'Longitude tidak valid.');
        }

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }


        $foto = null;

        if ($request->hasFile('foto_tps')) {

            $foto = $request->file('foto_tps')
                ->store('tps', 'public');
        }


        LokasiTps::create([

            'kategori_tps_id' => $request->kategori_tps_id,
            'nama_tps' => $request->nama_tps,
            'alamat_tps' => $request->alamat_tps,
            'status_tps' => $request->status_tps,
            'tahun_pembuatan' => $request->tahun_pembuatan,
            'kapasitas_tps' => $request->kapasitas_tps,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'foto_tps' => $foto,

        ]);


        return redirect()->route('admin.tps.index')
            ->with('success', 'Data TPS berhasil ditambahkan.');
    }


    public function edit($id)
    {

        $title = 'Edit TPS';

        $tps = LokasiTps::findOrFail($id);

        $kategori = KategoriTps::all();

        return view('admin.tps.edit', compact('title', 'tps', 'kategori'));
    }


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

        $tps = LokasiTps::findOrFail($id);


        $validator = Validator::make($request->all(), [

            'kategori_tps_id' => 'required|exists:kategori_tps,id_kategori_tps',
            'nama_tps' => 'required|string|max:255',
            'alamat_tps' => 'required|string|max:255',
            'status_tps' => 'required|in:Aktif,Tidak Aktif,Pembangunan',
            'tahun_pembuatan' => 'required|digits:4',
            'kapasitas_tps' => 'required|integer|min:1',
            'latitude' => 'required',
            'longitude' => 'required',
            'foto_tps' => 'nullable|image|mimes:jpg,jpeg,png|max:4096',

        ]);


        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }


        $latitude = $this->convertToDecimal($request->latitude);
        $longitude = $this->convertToDecimal($request->longitude);


        if ($latitude === null || $latitude < -90 || $latitude > 90) {
            $validator->errors()->add('latitude', 'Latitude tidak valid.');
        }

        if ($longitude === null || $longitude < -180 || $longitude > 180) {
            $validator->errors()->add('longitude', 'Longitude tidak valid.');
        }

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }


        $foto = $tps->foto_tps;

        if ($request->hasFile('foto_tps')) {

            if ($tps->foto_tps) {
                Storage::disk('public')->delete($tps->foto_tps);
            }

            $foto = $request->file('foto_tps')
                ->store('tps', 'public');
        }


        $tps->update([

            'kategori_tps_id' => $request->kategori_tps_id,
            'nama_tps' => $request->nama_tps,
            'alamat_tps' => $request->alamat_tps,
            'status_tps' => $request->status_tps,
            'tahun_pembuatan' => $request->tahun_pembuatan,
            'kapasitas_tps' => $request->kapasitas_tps,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'foto_tps' => $foto,

        ]);


        return redirect()->route('admin.tps.index')
            ->with('success', 'Data TPS berhasil diperbarui.');
    }


    public function destroy($id)
    {

        $tps = LokasiTps::findOrFail($id);

        if ($tps->foto_tps) {
            Storage::disk('public')->delete($tps->foto_tps);
        }

        $tps->delete();

        return redirect()->route('admin.tps.index')
            ->with('success', 'Data TPS berhasil dihapus.');
    }
}
