<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Potential;
use Illuminate\Http\Request;

class PotentialController extends Controller
{
    public function index(Request $request)
    {
        // Auto-seed if empty or update missing photos
        if (Potential::count() === 0) {
            (new \Database\Seeders\PotentialSeeder())->run();
        } else {
            Potential::where('nama', 'LIKE', '%Gedung Balai Desa%')->delete();
            Potential::firstOrCreate(
                ['nama' => 'Gapura PLG (Pusat Latihan Gajah) Seblat'],
                [
                    'kategori'  => 'pariwisata',
                    'deskripsi' => 'Gapura pintu masuk utama kawasan Pusat Latihan Gajah (PLG) Seblat. Merupakan ikon kebanggaan Desa Suka Baru dan gerbang wisata konservasi Gajah Sumatera.',
                    'foto'      => 'images/gapura.jpeg',
                    'lokasi'    => 'Perbatasan Desa - Kawasan TWA Seblat',
                ]
            );
            Potential::where('nama', 'LIKE', '%Gapura%')->update(['foto' => 'images/gapura.jpeg']);
            Potential::where('nama', 'LIKE', '%Sungai Seblat%')->update(['foto' => 'images/sungai seblat.jpeg']);
            Potential::where('nama', 'LIKE', '%Posyandu%')->update(['foto' => 'images/posyandu.jpeg']);
            Potential::where('nama', 'LIKE', '%Kantor & Balai Desa%')->update(['foto' => 'images/balai desa.jpeg']);
            Potential::where('nama', 'LIKE', '%Pusat Latihan Gajah (PLG) Seblat%')->update(['foto' => 'images/pusat pelatihan gaja 1.jpeg']);
        }

        $kategori   = $request->get('kategori');
        $query      = Potential::query();

        $allowedCategories = [
            'perdagangan', 'peribadatan', 'kesehatan', 'olahraga',
            'pemerintahan', 'pendidikan', 'pariwisata', 'pertanian',
            'perkebunan', 'peternakan', 'umkm'
        ];

        if ($kategori && in_array($kategori, $allowedCategories)) {
            $query->where('kategori', $kategori);
        }

        $allPotentials = Potential::all();
        $potentials    = $query->paginate(16);

        return view('public.potensi', compact('potentials', 'allPotentials', 'kategori'));
    }

    public function show($id)
    {
        if (Potential::count() === 0) {
            (new \Database\Seeders\PotentialSeeder())->run();
        }

        $potential = Potential::findOrFail($id);
        $related   = Potential::where('kategori', $potential->kategori)
                             ->where('id', '!=', $potential->id)
                             ->take(4)
                             ->get();

        return view('public.potensi-detail', compact('potential', 'related'));
    }
}
