<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\PetaKerawananModel;
use App\Models\KemiringanLerengModel;
use App\Models\PenggunaanLahanModel;
use App\Models\JenisTanahModel;
use App\Models\GeologiModel;
use App\Models\WilayahModel;

class PetaKerawanan extends BaseController
{
    protected $petaModel;
    protected $kemiringanModel;
    protected $lahanModel;
    protected $tanahModel;
    protected $geologiModel;
    protected $wilayahModel;

    public function __construct()
    {
        $this->petaModel = new PetaKerawananModel();
        $this->kemiringanModel = new KemiringanLerengModel();
        $this->lahanModel = new PenggunaanLahanModel();
        $this->tanahModel = new JenisTanahModel();
        $this->geologiModel = new GeologiModel();
        $this->wilayahModel = 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' => 'Peta Kerawanan',
            'peta'  => $this->petaModel
                ->orderBy('id_peta', 'DESC')
                ->findAll()
        ];

        return view('admin/peta_kerawanan/index', $data);
    }
    public function store()
    {
        $file = $this->request->getFile('file_geojson');

        $namaFile = null;

        if ($file && $file->isValid()) {

            $namaFile = $file->getRandomName();

            $file->move(
                FCPATH . 'uploads/peta_kerawanan',
                $namaFile
            );
        }

        $this->petaModel->save([
            'judul'          => $this->request->getPost('judul'),
            'tanggal_update' => $this->request->getPost('tanggal_update'),
            'deskripsi'      => $this->request->getPost('deskripsi'),
            'file_geojson'   => $namaFile
        ]);

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

    public function delete($id)
    {
        $peta = $this->petaModel->find($id);

        if (!$peta) {
            return redirect()
                ->to('admin/peta-kerawanan')
                ->with('error', 'Data tidak ditemukan');
        }

        if (!empty($peta['file_geojson'])) {

            $path = FCPATH . 'uploads/peta_kerawanan/' . $peta['file_geojson'];

            if (file_exists($path)) {
                unlink($path);
            }
        }

        $this->petaModel->delete($id);

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

    public function detail($id)
    {
        $peta = $this->petaModel->find($id);

        if (!$peta) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $data = [
            'title'       => 'Preview Peta Kerawanan',
            'peta'        => $peta,
            'kemiringan'  => $this->kemiringanModel->findAll(),
            'lahan'       => $this->lahanModel->findAll(),
            'jenis_tanah' => $this->tanahModel->findAll(),
            'geologi'     => $this->geologiModel->findAll(),
            'wilayah'     => $this->wilayahModel->findAll()
        ];

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

    public function buatPeta()
    {
        $data = [
            'title' => 'Buat Peta Kerawanan'
        ];

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

    public function simpanPeta()
    {
        $data = $this->request->getJSON(true);

        if (!$data) {

            return $this->response->setJSON([
                'status' => false,
                'message' => 'Data tidak ditemukan'
            ]);
        }

        if (!is_dir(FCPATH . 'uploads/peta_kerawanan')) {

            mkdir(FCPATH . 'uploads/peta_kerawanan', 0777, true);
        }

        $namaFile = 'peta_' . time() . '.geojson';

        file_put_contents(

            FCPATH . 'uploads/peta_kerawanan/' . $namaFile,

            json_encode(
                $data['geojson'],
                JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
            )

        );

        $this->petaModel->insert([

            'judul' => $data['judul'],

            'tanggal_update' => $data['tanggal_update'],

            'deskripsi' => $data['deskripsi'],

            'file_geojson' => $namaFile

        ]);

        return $this->response->setJSON([

            'status' => true,

            'message' => 'Peta berhasil disimpan.'

        ]);
    }
}
