<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\DataModel;

class Data extends BaseController
{
    protected $dataModel;

    public function __construct()
    {
        $this->dataModel = new DataModel();

        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' => 'Data Bencana',
            'data_bencana' => $this->dataModel->orderBy('id_data', 'DESC')->findAll()
        ];

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

    public function store()
    {
        $file = $this->request->getFile('file_data');
        $namaFile = null;

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $namaFile = $file->getRandomName();
            $file->move(FCPATH . 'uploads/data_bencana', $namaFile);
        }

        $this->dataModel->save([
            'jenis_data' => $this->request->getPost('jenis_data'),
            'tahun'      => $this->request->getPost('tahun'),
            'sumber'     => $this->request->getPost('sumber'),
            'keterangan' => $this->request->getPost('keterangan'),
            'file_data'  => $namaFile
        ]);

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

    public function update($id)
    {
        $file = $this->request->getFile('file_data');
        $old = $this->dataModel->find($id);

        $namaFile = $old['file_data'];

        if ($file && $file->isValid() && !$file->hasMoved()) {
            if ($namaFile && file_exists(FCPATH . 'uploads/data_bencana/' . $namaFile)) {
                unlink(FCPATH . 'uploads/data_bencana/' . $namaFile);
            }

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

        $this->dataModel->update($id, [
            'jenis_data' => $this->request->getPost('jenis_data'),
            'tahun'      => $this->request->getPost('tahun'),
            'sumber'     => $this->request->getPost('sumber'),
            'keterangan' => $this->request->getPost('keterangan'),
            'file_data'  => $namaFile
        ]);

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

    public function delete($id)
    {
        $data = $this->dataModel->find($id);

        if ($data['file_data'] && file_exists(FCPATH . 'uploads/data_bencana/' . $data['file_data'])) {
            unlink(FCPATH . 'uploads/data_bencana/' . $data['file_data']);
        }

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

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