<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\PenggunaanLahanModel;

class PenggunaanLahan extends BaseController
{
    protected $model;

    public function __construct()
    {
        $this->model = new PenggunaanLahanModel();

        if (!session()->get('logged_in')) {
            return redirect()->to(base_url('login'));
        }

        if (session()->get('role') != 'admin') {
            return redirect()->to(base_url('/'));
        }
    }

    public function index()
    {
        $data = [
            'title' => 'Penggunaan Lahan',
            'lahan' => $this->model->orderBy('id_lahan', 'DESC')->findAll()
        ];

        return view('admin/penggunaan_lahan', $data);
    }

    public function store()
    {
        $this->model->save([
            'kelas'       => $this->request->getPost('kelas'),
            'skor'        => $this->request->getPost('skor'),
            'warna_peta'  => $this->request->getPost('warna_peta'),
        ]);

        return redirect()->to('admin/penggunaan-lahan')
            ->with('success', 'Data berhasil ditambahkan');
    }

    public function update($id)
    {
        $this->model->update($id, [
            'kelas'       => $this->request->getPost('kelas'),
            'skor'        => $this->request->getPost('skor'),
            'warna_peta'  => $this->request->getPost('warna_peta'),
        ]);

        return redirect()->to('admin/penggunaan-lahan')
            ->with('success', 'Data berhasil diupdate');
    }

    public function delete($id)
    {
        $this->model->delete($id);

        return redirect()->to('admin/penggunaan-lahan')->with('success', 'Data berhasil dihapus');
    }
}
