<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\WilayahModel;

class Wilayah extends BaseController
{
    protected $model;

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

        if (!session()->get('logged_in')) {
            header('Location: ' . base_url('login'));
            exit;
        }

        if (session()->get('role') != 'admin') {
            header('Location: ' . base_url('/'));
            exit;
        }
    }

    public function index()
    {
        $data = [
            'title'   => 'Data Wilayah',
            'wilayah' => $this->model
                ->orderBy('id_wilayah', 'DESC')
                ->findAll()
        ];

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

    public function store()
    {
        $this->model->save([

            'nama_desa'        => $this->request->getPost('nama_desa'),
            'total_penduduk'   => $this->request->getPost('total_penduduk'),
            'luas_daerah'      => $this->request->getPost('luas_daerah'),
            'persentase_luas'  => $this->request->getPost('persentase_luas'),
            'latitude'         => $this->request->getPost('latitude'),
            'longitude'        => $this->request->getPost('longitude'),
            'icon_marker'      => $this->request->getPost('icon_marker'),
            'keterangan'       => $this->request->getPost('keterangan')

        ]);

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

    public function update($id)
    {
        $this->model->update($id, [

            'nama_desa'        => $this->request->getPost('nama_desa'),
            'total_penduduk'   => $this->request->getPost('total_penduduk'),
            'luas_daerah'      => $this->request->getPost('luas_daerah'),
            'persentase_luas'  => $this->request->getPost('persentase_luas'),
            'latitude'         => $this->request->getPost('latitude'),
            'longitude'        => $this->request->getPost('longitude'),
            'icon_marker'      => $this->request->getPost('icon_marker'),
            'keterangan'       => $this->request->getPost('keterangan')

        ]);

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

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

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