<?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\Storage;

class TpsController extends Controller
{
    public function index()
    {
        $title = 'Data TPS';

        // Ambil TPS + kategori + jumlah aduan
        $tps = LokasiTps::with('kategori')
            ->withCount('aduan')
            ->get();

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

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

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

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

        $coordinate = html_entity_decode($coordinate);
        $coordinate = strtoupper(trim($coordinate));

        // ganti simbol jadi seragam
        $coordinate = str_replace(
            ['°', "'", '"'],
            [' ', ' ', ' '],
            $coordinate
        );

        // ambil arah
        preg_match('/([NSEW])/', $coordinate, $dirMatch);
        if (!$dirMatch) return null;

        $direction = $dirMatch[1];

        // ambil angka
        preg_match_all('/\d+(\.\d+)?/', $coordinate, $numbers);
        if (count($numbers[0]) < 3) return null;

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

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

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

        return $decimal;
    }

    public function store(Request $request)
    {
        $request->validate([
            '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',
            'tahun_pembuatan' => 'required|numeric',
            'kapasitas_tps' => 'required',
            'latitude' => 'required',
            'longitude' => 'required',
            'foto_tps' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        // 🔥 KONVERSI KOORDINAT
        $latitude  = $this->convertToDecimal($request->latitude);
        $longitude = $this->convertToDecimal($request->longitude);

        if ($latitude === null || $longitude === null) {
            return back()->withErrors(['Koordinat tidak valid'])->withInput();
        }

        // Upload foto
        $foto = $request->hasFile('foto_tps')
            ? $request->file('foto_tps')->store('foto-tps', 'public')
            : null;

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

        // VALIDASI
        $request->validate([
            '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',
            'tahun_pembuatan' => 'required|numeric',
            'kapasitas_tps' => 'required',
            'latitude' => 'required',
            'longitude' => 'required',
            'foto_tps' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        // 🔥 KONVERSI KOORDINAT (DMS / DECIMAL)
        $latitude  = $this->convertToDecimal($request->latitude);
        $longitude = $this->convertToDecimal($request->longitude);

        // Jika koordinat tidak valid
        if ($latitude === null || $longitude === null) {
            return back()
                ->withErrors(['Koordinat tidak valid. Gunakan format Decimal atau DMS.'])
                ->withInput();
        }

        // 📸 UPLOAD FOTO JIKA ADA
        if ($request->hasFile('foto_tps')) {

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

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

        // 💾 UPDATE DATA
        $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');
    }
}
