<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\WilayahMitigasiModel;
use App\Models\StrategiMitigasiModel;

class WilayahMitigasi extends BaseController
{
    protected $model;
    protected $mitigasi;

    public function __construct()
    {
        $this->model = new WilayahMitigasiModel();
        $this->mitigasi = new StrategiMitigasiModel();

        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' => 'Peta Wilayah Mitigasi',
            'wilayah' => $this->model->getData(),
            'strategi' => $this->mitigasi->findAll()
        ];

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

    public function store()
    {
        $this->validate([
            'id_mitigasi' => 'required',
            'lokasi' => 'required',
            'latitude' => 'required',
            'longitude' => 'required'
        ]);

        $this->model->insert([
            'id_mitigasi' => $this->request->getPost('id_mitigasi'),
            'lokasi' => $this->request->getPost('lokasi'),
            'latitude' => $this->request->getPost('latitude'),
            'longitude' => $this->request->getPost('longitude'),
            'icon' => 'marker.png',
            'polygon' => $this->request->getPost('polygon'),
            'keterangan' => $this->request->getPost('keterangan')
        ]);

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

    public function update($id)
    {
        $this->validate([
            'id_mitigasi' => 'required',
            'lokasi' => 'required',
            'latitude' => 'required',
            'longitude' => 'required'
        ]);

        $this->model->update($id, [
            'id_mitigasi' => $this->request->getPost('id_mitigasi'),
            'lokasi' => $this->request->getPost('lokasi'),
            'latitude' => $this->request->getPost('latitude'),
            'longitude' => $this->request->getPost('longitude'),
            'icon' => 'marker.png',
            'polygon' => $this->request->getPost('polygon'),
            'keterangan' => $this->request->getPost('keterangan')
        ]);

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

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

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