<?php

namespace App\Controllers;
use App\Models\PetaModel;

class Peta extends BaseController
{
    protected $petaModel;

    public function __construct()
    {
        $this->petaModel = new PetaModel();
    }

    // Menampilkan Peta untuk SEMUA STAF
    public function index()
    {
        $data = [
            'title'      => 'Peta Spasial - KPH III Asahan',
            'titik_peta' => $this->petaModel->findAll() // Mengambil semua titik dari database
        ];
        return view('peta', $data);
    }

    // Halaman Manajemen Tabel (Khusus Admin/Kepala)
    public function kelola()
    {
        if (session()->get('role') != 'Admin' && session()->get('role') != 'Kepala KPH') return redirect()->to('/peta');
        
        $data = [
            'title'      => 'Kelola Titik Peta',
            'titik_peta' => $this->petaModel->orderBy('id_titik', 'DESC')->findAll()
        ];
        return view('data_peta', $data);
    }

    // Form Tambah/Edit Titik
    public function form($id = null)
    {
        if (session()->get('role') != 'Admin' && session()->get('role') != 'Kepala KPH') return redirect()->to('/peta');

        $data = ['title' => $id ? 'Edit Titik Peta' : 'Tambah Titik Peta'];
        if ($id) $data['titik_edit'] = $this->petaModel->find($id);

        return view('form_peta', $data);
    }

    public function simpan()
    {
        $id = $this->request->getPost('id_titik');
        $dataSimpan = [
            'nama_lokasi' => $this->request->getPost('nama_lokasi'),
            'kategori'    => $this->request->getPost('kategori'),
            'latitude'    => $this->request->getPost('latitude'),
            'longitude'   => $this->request->getPost('longitude'),
            'deskripsi'   => $this->request->getPost('deskripsi'),
        ];

        if ($id) {
            $this->petaModel->update($id, $dataSimpan);
        } else {
            $this->petaModel->save($dataSimpan);
        }
        return redirect()->to('/peta/kelola');
    }

    public function hapus($id)
    {
        if (session()->get('role') == 'Admin' || session()->get('role') == 'Kepala KPH') {
            $this->petaModel->delete($id);
        }
        return redirect()->to('/peta/kelola');
    }
}