<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\SiswaModel;
use App\Models\SiswaDataModel;
use Config\Services;

class Siswa extends BaseController
{
	protected $siswaModel;
	
	public function __construct()
	{
		$this->siswaModel = new SiswaModel();
	}

	public function index()
	{
		return view('admin/siswa/index', [
			'title' => 'Siswa',
			'siswas' => $this->siswaModel->findAll(),
		]);
	}

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

	public function create()
	{
		$rules = [
			'nisn' => [
				'rules'  => 'required',
				'errors' => []
			],
			'nama_siswa' => [
				'rules'  => 'required',
				'errors' => []
			],
		];

		$data = [
			'nisn' => $this->request->getPost('nisn'),
			'nama_siswa' => $this->request->getPost('nama_siswa'),
			'tmp_lahir' => $this->request->getPost('tmp_lahir'),
			'tgl_lahir' => $this->request->getPost('tgl_lahir'),
			'jk_siswa' => $this->request->getPost('jk_siswa'),
			'no_telp' => $this->request->getPost('no_telp'),
			'alamat' => $this->request->getPost('alamat'),
		];

		if (!$this->validate($rules)) {
			//render view with error validation message
			return redirect()->back()->withInput();
		} else {
			$this->siswaModel->save($data);
			$this->session->setFlashdata('success', 'Data Siswa Berhasil Ditambahkan.');
			return redirect()->to('/admin/siswa');
		}
	}

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

	public function update($id)
	{
		$rules = [
			'nisn' => [
				'rules'  => 'required',
				'errors' => []
			],
			'nama_siswa' => [
				'rules'  => 'required',
				'errors' => []
			],
		];

		$data = [
			'nisn' => $this->request->getPost('nisn'),
			'nama_siswa' => $this->request->getPost('nama_siswa'),
			'tmp_lahir' => $this->request->getPost('tmp_lahir'),
			'tgl_lahir' => $this->request->getPost('tgl_lahir'),
			'jk_siswa' => $this->request->getPost('jk_siswa'),
			'no_telp' => $this->request->getPost('no_telp'),
			'alamat' => $this->request->getPost('alamat'),
		];

		if (!$this->validate($rules)) {
			//render view with error validation message
			return redirect()->back()->withInput();
		} else {
			$this->siswaModel->update($id, $data);
			$this->session->setFlashdata('success', 'Data Siswa Berhasil Diubah.');
			return redirect()->to('/admin/siswa');
		}
	}

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

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

                $btnEdit = "<a href='" . base_url() . "/admin/siswa/edit/$list->id' class=\"btn bg-primary btn-sm text-white mr-2\" data-bs-toggle=\"tooltip\" title=\"Edit Data\">Edit</a>";
				$btnDelete = "<form action='" . base_url() . "/admin/siswa/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 btn-sm text-light\" onclick=\"return confirm('Apakah anda yakin menghapus data ini?')\">Hapus</button>
                </form>";

                $row[] = $no;
                $row[] = $list->nisn;
				$row[] = $list->nama_siswa;
				$row[] = $list->tmp_lahir;
				$row[] = $list->tgl_lahir;
				$row[] = ($list->jk_siswa == 0 ? 'Pria' : 'Perempuan');
				$row[] = $list->no_telp;
				$row[] = $list->alamat;
                $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);
        }
    }
}
