<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\PengumumanModel;
use App\Models\PengumumanDataModel;
use Config\Services;

class Pengumuman extends BaseController
{
	protected $pengumumanModel;

	public function __construct()
	{
		$this->pengumumanModel = new PengumumanModel();
	}

	public function index()
	{	
		return view('admin/pengumuman/index', [
			'title' => 'Pengumuman',
			'pengumuman' => $this->pengumumanModel->findAll(),
		]);
	}

	public function new()
	{
		return view('admin/pengumuman/create', [
			'title' => 'Tambah Data Pengumuman',
			'validation' => $this->validation
		]);
	}

	public function create()
	{
		$rules = [
			'judul_pengumuman' => [
				'rules'  => 'required',
				'errors' => []
			],
			'isi_pengumuman' => [
				'rules'  => 'required',
				'errors' => []
			],
			'foto_pengumuman' => [
				'rules'  => 'uploaded[foto_pengumuman]|mime_in[foto_pengumuman,image/jpeg,image/pjpeg,image/png,image/x-png]|ext_in[foto_pengumuman,jpg,jpeg,png]',
				'errors' => []
			],
		];

		
		if (!$this->validate($rules)) {
			//render view with error validation message
			return redirect()->back()->withInput();
		}

		$foto = $this->request->getFile('foto_pengumuman');
		if ($foto->isValid()) {
			$name = $foto->getName();
			$newName = $foto->getRandomName();
			$foto->move('img/pengumuman', $newName);
		}
		$data = [
			'judul_pengumuman' => $this->request->getPost('judul_pengumuman'),
			'isi_pengumuman' => $this->request->getPost('isi_pengumuman'),
			'foto_pengumuman' => $newName,
		];

		$this->pengumumanModel->save($data);
		$this->session->setFlashdata('success', 'Data Pengumuman Berhasil Ditambahkan.');
		return redirect()->to('/admin/pengumuman');
	}

	public function edit($id)
	{
		return view('admin/pengumuman/edit', [
			'title' => 'Edit Data Pengumuman',
			'pengumuman' => $this->pengumumanModel->find($id),
			'validation' => $this->validation
		]);
	}

	public function update($id)
	{
		$rules = [
			'judul_pengumuman' => [
				'rules'  => 'required',
				'errors' => []
			],
			'isi_pengumuman' => [
				'rules'  => 'required',
				'errors' => []
			],
			'foto_pengumuman' => [
				'rules'  => 'mime_in[foto_pengumuman,image/jpeg,image/pjpeg,image/png,image/x-png]|ext_in[foto_pengumuman,jpg,jpeg,png]',
				'errors' => []
			],
		];

		if (!$this->validate($rules)) {
			//render view with error validation message
			return redirect()->back()->withInput();
		}

		$foto = $this->request->getFile('foto_pengumuman');
		if ($foto->isValid()) {
			$name = $foto->getName();
			$newName = $foto->getRandomName();
			$foto->move('img/pengumuman', $newName);
			unlink('img/pengumuman/' . $this->request->getPost('foto_pengumuman_lama'));
		} else {
			$newName = $this->request->getPost('foto_pengumuman_lama');
		}

		$data = [
			'judul_pengumuman' => $this->request->getPost('judul_pengumuman'),
			'isi_pengumuman' => $this->request->getPost('isi_pengumuman'),
			'foto_pengumuman' => $newName,
		];

		$this->pengumumanModel->update($id, $data);
		$this->session->setFlashdata('success', 'Data Pengumuman Berhasil Diubah.');
		return redirect()->to('/admin/pengumuman');
	}

	public function delete($id)
	{
		$pengumuman = $this->pengumumanModel->find($id);
		unlink('img/pengumuman/' . $pengumuman['foto_pengumuman']);
		$this->pengumumanModel->delete($id);
		$this->session->setFlashdata('success', 'Data pengumuman Berhasil Dihapus.');
		return redirect()->to('/admin/pengumuman');
	}

	public function listData()
    {
        $request = Services::request();
        $datamodel = new PengumumanDataModel($request);
        if ($request->getMethod(true) == 'POST') {
            $lists = $datamodel->get_datatables();
            $csrfName = csrf_token();
            $csrfHash = csrf_hash();
            $data = [];
            $no = $request->getPost("start");
            foreach ($lists as $list) {
                $no++;
                $row = [];

				$foto = "<img src='".base_url()."/img/pengumuman/".$list->foto_pengumuman."' alt=\"Foto Pengumuman $list->judul_pengumuman\" class=\"\" width=\"150\">";
                $btnEdit = "<a href='" . base_url() . "/admin/pengumuman/edit/$list->id' class=\"btn bg-primary text-white mr-2\" data-bs-toggle=\"tooltip\" title=\"Edit Data\">Edit</a>";
				$btnDelete = "<form action='" . base_url() . "/admin/pengumuman/delete/$list->id' method=\"POST\" class=\"d-inline-block\">
                " . csrf_field() . "
                <input type=\"hidden\" name=\"_method\" value=\"DELETE\">
                <button type=\"submit\" class=\"btn btn-danger text-light\" onclick=\"return confirm('Apakah anda yakin menghapus data ini?')\">Hapus</button>
                </form>";

                $row[] = $no;
                $row[] = $foto;
				$row[] = $list->judul_pengumuman;
                $row[] = $btnEdit . $btnDelete;
                $data[] = $row;
            }
            $output = [
                "draw" => $request->getPost('draw'),
                "recordsTotal" => $datamodel->count_all(),
                "recordsFiltered" => $datamodel->count_filtered(),
                "data" => $data
            ];
            $output[$csrfName] = $csrfHash;
            echo json_encode($output);
        }
    }
}
