<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ArtikelModel;
use App\Models\ArtikelDataModel;
use Config\Services;

class Artikel extends BaseController
{
	protected $artikelModel;
	
	public function __construct()
	{
		$this->artikelModel = new ArtikelModel();
	}

	public function index()
	{	
		return view('admin/artikel/index', [
			'title' => 'Berita',
			'artikel' => $this->artikelModel->findAll(),
		]);
	}

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

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

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

		$foto = $this->request->getFile('foto_artikel');
		if ($foto->isValid()) {
			$name = $foto->getName();
			$newName = $foto->getRandomName();
			$foto->move('img/artikel', $newName);
		}
		$data = [
			'judul' => $this->request->getPost('judul'),
			'isi' => $this->request->getPost('isi'),
			'foto_artikel' => $newName,
		];

		$this->artikelModel->insert($data);
		$this->session->setFlashdata('success', 'Data Berita Berhasil Ditambahkan.');
		return redirect()->to('/admin/artikel');
	}

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

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

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

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

		$data = [
			'judul' => $this->request->getPost('judul'),
			'isi' => $this->request->getPost('isi'),
			'foto_artikel' => $newName,
		];

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

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

	public function listData()
    {
        $request = Services::request();
        $datamodel = new ArtikelDataModel($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/artikel/".$list->foto_artikel."' alt=\"Foto Artikel $list->judul\" class=\"\" width=\"150\">";
                $btnEdit = "<a href='" . base_url() . "/admin/artikel/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/artikel/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;
                $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);
        }
    }
}
