<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\KontakModel;
use App\Models\KontakDataModel;
use Config\Services;

class Kontak extends BaseController
{
	protected $kontakModel;

	public function __construct()
	{
		$this->kontakModel = new KontakModel();
	}

	public function index()
	{
		return view('admin/kontak/index', [
			'title' => 'Form Kontak (Inbox)',
			'kontak' => $this->kontakModel->findAll(),
		]);
	}

	public function new()
	{
		return view('admin/kontak/create', [
			'title' => 'Tambah Data Kontak'
		]);
	}

	public function create()
	{
		$data = [
		    'nama' => $this->request->getPost('nama'),
		    'email' => $this->request->getPost('email'),
		    'isi' => $this->request->getPost('isi'),
		];

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

	public function delete($id)
	{
		$this->kontakModel->delete($id);
		$this->session->setFlashdata('success', 'Data Kontak Berhasil Dihapus.');
		return redirect()->to('/admin/kontak');
	}

	public function listData()
    {
        $request = Services::request();
        $datamodel = new KontakDataModel($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 = [];

				$btnDelete = "<form action='" . base_url() . "/admin/kontak/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[] = $list->nama;
				$row[] = $list->email;
				$row[] = $list->isi;
                $row[] = $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);
        }
    }
}
