<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\KemiringanLerengModel;

class KemiringanLereng extends BaseController
{
    protected $model;

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

        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' => 'Kemiringan Lereng',
            'kemiringan' => $this->model->orderBy('id_lereng', 'DESC')->findAll()
        ];

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

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

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

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

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

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

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