<?php

namespace App\Controllers;

use App\Models\GeneralModel;
use App\Models\SysUserModel;
use App\Entities\SysUserEntity;
use App\Controllers\BaseController;
use Config\Services;
use CodeIgniter\Exceptions\PageNotFoundException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SysUser extends BaseController
{
	private $page_controller = "sysuser";
	private $page_route = "user";

	public function index()
	{		
		$page_button = button([
			["access" => getAccess($this->page_route), "label" => str("button_create_new"), "url" => admin_url($this->page_route."/form/0")]
		]);

		$output = [
			"page_controller" => $this->page_controller,
			"page_route" => $this->page_route,
			"page_button" => $page_button,
			"page_title" => str("sysuser")
		];
		echo view("sysuser/index", $output);
	}

	public function datatable()
    {
        $request = Services::request();
		$sysuserModel = new SysUserModel($request);
		$where = $request->getPost('where');
		$list = $sysuserModel->getDatatables($where);
		$no = $request->getPost('start');
		$data = [];

		foreach ($list as $lines) {
			$row_id = enkripsi($lines["row_id"]);
			$line = new SysUserEntity();
			$line->fill($lines);
			
			$button = buttonTable([
				["access" => getAccess($this->page_route), "label" => str("button_edit"), "url" => admin_url($this->page_route."/form/".$row_id)]
			]);

			$link_view = linkView(["form_id" => dekripsi($row_id), "value" => $line->user_id, "title" => str("sysuser"), "url" => admin_url($this->page_route."/preview/".$row_id)]);

			$row = [];
			$row[] = $button;
            $row[] = $link_view;
            $row[] = printText(["value" => $line->user_access_id_txt]);
            $row[] = printText(["value" => $line->name]);
            $row[] = printText(["value" => $line->title]);
            $row[] = printText(["value" => $line->email]);
            $row[] = printNoYes(["value" => $line->is_active]);
			$data[] = $row;
		}

		$output = [
			"draw" => $request->getPost("draw"),
			"recordsTotal" => $sysuserModel->countAll(),
			"recordsFiltered" => $sysuserModel->countFiltered($where),
			"data" => $data,
			"sistemator_token" => csrf_hash()
		];

		echo json_encode($output);
    }

	public function form($id=null) 
	{
		$row_id = dekripsi($id);

		$page_button = button([
			["access" => getAccess($this->page_route), "label" => str("button_save"), "id" => "btn_save", "onclick" => "save('form_input', 'btn_save')", "color" => "success"],
			["access" => getAccess($this->page_route), "label" => str("button_delete"), "onclick" => "deleteSysUser()", "color" => "danger"]
		]);
        $generalModel = new GeneralModel();
        $user_access_id_list = $generalModel->dropdownList(["table" => "sysuseraccess", "id"=>"row_id", "text"=>"name"]);

		$sysuserModel = new SysUserModel();
		$data = $sysuserModel->getSelect("sysuser.row_id = '".$row_id."'");
		$data->pswrd = "";
		
		$output = [
			"page_controller" => $this->page_controller,
			"page_title" => str("sysuser"),
			"page_route" => $this->page_route,
			"page_button" => $page_button,
			"row_id" => $id,
			"data" => $data,
            "user_access_id_list" => $user_access_id_list,
		];
		echo view("sysuser/form", $output);
	}

	public function save() {
        $request = Services::request();
		$sysuserModel = new SysUserModel();
		$input = new SysUserEntity();
		$valid = true;
		$msg = str("process_successful");
		$status = 1;

		$row_id = $request->getPost("row_id");
		$state = ($row_id == "0") ? "create" : "update";
		if($state  == "create") {
			$input->created_date = getDatetime();
			$input->created_by = sesUsername();

			$validation = [
				["type" => "unique", "field" => "user_id", "value" => $request->getPost("user_id")],];
			if($validation != null) {
				$return_validation = $sysuserModel->checkValidation($validation);
				if(!$return_validation["valid"]) {
					$valid = false;
					$msg = $return_validation["msg"];
					$status = 0;
				}
			}
		}

		$input->row_id = dekripsi($row_id);		
		$input->modified_date = getDatetime();
		$input->modified_by = sesUsername();
        $input->user_access_id = $request->getPost("user_access_id");
        $input->name = $request->getPost("name");
        $input->title = $request->getPost("title");
        $input->email = $request->getPost("email");
        $input->user_id = $request->getPost("user_id");
        if($request->getPost("pswrd") != "") {
			$input->pswrd = password_hash($request->getPost("pswrd"), PASSWORD_DEFAULT);
		}
        $input->is_active = $request->getPost("is_active");

		if($valid) {
			$sysuserModel->save($input);
			$row_id = $sysuserModel->getInsertID();
		}

		$output = array(
			"sistemator_token" => csrf_hash(),
			"msg" => $msg,
			"status" => $status,
		);

		echo json_encode($output);
	}

	public function delete() 
	{
        $request = Services::request();
		$sysuserModel = new SysUserModel();
		$sysuserModel->deleteData(dekripsi($request->getGet('id')));

		$output = array(
			"sistemator_token" => csrf_hash(),
			"msg" => "Process successful",
			"status" => 1,
		);

		echo json_encode($output);
	}

	public function excel() 
	{
		$sysuserModel = new SysUserModel();
		$data = $sysuserModel->exportExcel();		
		generateExcel($data, str("sysuser"));
	}

	public function print($id) 
	{	
		$row_id = dekripsi($id);

		$sysuserModel = new SysUserModel();
		$data = $sysuserModel->getSelect("sysuser.row_id = '".$row_id."'");

		$output = [
			"document_name" => str("sysuser"),
			"data" => $data,
		];

		$dompdf = new \Dompdf\Dompdf();		
		$dompdf->loadHtml(view("sysuser/print", $output));
		$dompdf->setPaper("A4", "portrait");
		$dompdf->render();
		$dompdf->stream(str("sysuser"));
	
		return redirect()->to(admin_url($this->page_route));
	}
}
