<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use \App\Models\GuruModel;
use App\Models\GuruDataModel;
use Config\Services;

class Guru extends BaseController
{
	protected $guruModel;

	public function __construct()
	{
		$this->guruModel = new GuruModel();
	}

	public function index()
	{	
		return view('admin/guru/index', [
			'title' => 'Guru',
			'gurus' => $this->guruModel->findAll(),
		]);
	}

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

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

		$foto = $this->request->getFile('foto_guru');
		if ($foto->isValid()) {
			$name = $foto->getName();
			$newName = $foto->getRandomName();
			$foto->move('img/guru', $newName);
		} else {
			$newName = "default.jpg";
		}
		$data = [
			'nip_nik' => $this->request->getPost('nip_nik'),
			'nama_guru' => $this->request->getPost('nama_guru'),
			'email' => $this->request->getPost('email'),
			'foto_guru' => $newName,
			'jabatan' => $this->request->getPost('jabatan'),
		];

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

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

	public function update($id)
	{
		try {
			$foto = $this->request->getFile('foto_guru');
			if ($foto->isValid() && !$foto->hasMoved()) {
				$newName = $foto->getRandomName();
				$foto->move('img/guru', $newName);

				$fotoLama = $this->request->getPost('foto_guru_lama');
				if ($fotoLama && $fotoLama != 'default.jpg' && file_exists('img/guru/' . $fotoLama)) {
					unlink('img/guru/' . $fotoLama);
				}
			} else {
				$newName = $this->request->getPost('foto_guru_lama');
			}

			$data = [
				'nip_nik'   => $this->request->getPost('nip_nik'),
				'nama_guru' => $this->request->getPost('nama_guru'),
				'email'     => $this->request->getPost('email'),
				'jabatan'   => $this->request->getPost('jabatan'),
				'foto_guru' => $newName,
			];

			$this->guruModel->update($id, $data);
			session()->setFlashdata('success', 'Data guru berhasil diubah.');
			return redirect()->to('/admin/guru');
			
		} catch (\Exception $e) {
			log_message('error', 'Guru Update Error: ' . $e->getMessage());
			session()->setFlashdata('error', 'Terjadi kesalahan saat mengupdate data guru: ' . $e->getMessage());
			return redirect()->back()->withInput();
		}
	}

	public function delete($id)
	{
		$guru = $this->guruModel->find($id);

		if ($guru && $guru['foto_guru'] != 'default.jpg' && file_exists('img/guru/' . $guru['foto_guru'])) {
			unlink('img/guru/' . $guru['foto_guru']);
		}

		$this->guruModel->delete($id);
		session()->setFlashdata('success', 'Data guru berhasil dihapus.');
		return redirect()->to('/admin/guru');
	}
	public function listData()
    {
        $request = Services::request();
        $datamodel = new GuruDataModel($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/guru/".$list->foto_guru."' alt=\"Foto Guru $list->nama_guru\" class=\"\" width=\"100\">";
                $btnEdit = "<a href='" . base_url() . "/admin/guru/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/guru/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->nip_nik;
				$row[] = $list->nama_guru;
				$row[] = $list->email;
				$row[] = $foto;
				$row[] = $list->jabatan;
                $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);
        }
    }
}
