<?php

namespace App\Controllers;

use App\Models\GeneralModel;
use App\Models\SysUserAccessModel;
use App\Entities\SysUserAccessEntity;
use App\Models\SysUserAccessAccessModel;
use App\Entities\SysUserAccessAccessEntity;
use App\Controllers\BaseController;
use Config\Services;
use CodeIgniter\Exceptions\PageNotFoundException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SysUserAccess extends BaseController
{
	private $page_controller = "sysuseraccess";
	private $page_route = "user-access";

	public function index()
	{		
		//echo json_encode(getMenu("1")); die();

		$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("sysuseraccess")
		];
		echo view("sysuseraccess/index", $output);
	}

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

		foreach ($list as $lines) {
			$row_id = enkripsi($lines["row_id"]);
			$line = new SysUserAccessEntity();
			$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->name, "title" => str("sysuseraccess"), "url" => admin_url($this->page_route."/preview/".$row_id)]);

			$row = [];
			$row[] = $button;
            $row[] = $link_view;
            $row[] = printText(["value" => $line->notes]);
			$data[] = $row;
		}

		$output = [
			"draw" => $request->getPost("draw"),
			"recordsTotal" => $sysuseraccess_model->countAll(),
			"recordsFiltered" => $sysuseraccess_model->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" => "deleteSysUserAccess()", "color" => "danger"]
		]);

		$sysuseraccess_model = new SysUserAccessModel();
		$data = $sysuseraccess_model->getSelect("sysuseraccess.row_id = '".$row_id."'");
		
		$output = [
			"page_controller" => $this->page_controller,
			"page_title" => str("sysuseraccess"),
			"page_route" => $this->page_route,
			"page_button" => $page_button,
			"row_id" => $id,
			"data" => $data,
			"table_access" => $this->tableAccess($id),
		];
		echo view("sysuseraccess/form", $output);
	}

	public function save() {
        $request = Services::request();
		$sysuseraccess_model = new SysUserAccessModel();
		$input = new SysUserAccessEntity();
		$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" => "name", "value" => $request->getPost("name")],];
			if($validation != null) {
				$return_validation = $sysuseraccess_model->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->name = $request->getPost("name");
        $input->notes = $request->getPost("notes");

		if($valid) {
			$sysuseraccess_model->save($input);
			$row_id = ($row_id == "0") ? enkripsi($sysuseraccess_model->getInsertID()) : $row_id;
		}

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

		echo json_encode($output);
	}

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

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

		echo json_encode($output);
	}

	public function excel() 
	{
		$sysuseraccess_model = new SysUserAccessModel();
		$data = $sysuseraccess_model->exportExcel();		
		generateExcel($data, str("sysuseraccess"));
	}

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

		$sysuseraccess_model = new SysUserAccessModel();
		$data = $sysuseraccess_model->getSelect("sysuseraccess.row_id = '".$row_id."'");

		$output = [
			"document_name" => str("sysuseraccess"),
			"data" => $data,
			"table_access" => $this->tableAccess($id),
		];

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

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

		$sysuseraccess_model = new SysUserAccessModel();
		$header = $sysuseraccess_model->getSelect("sysuseraccess.row_id = '".$row_id."'");

		$sysuseraccessaccess_model = new SysUserAccessAccessModel();
		$line_id = 0;
		$button_add = buttonLine(["access" => getAccess($this->page_route), "label" => str("button_add"), "url" => admin_url($this->page_route."/form-access/".$line_id."/"), "color" => "primary"]);
		$list = $sysuseraccessaccess_model->getList("sysuseraccessaccess.row_id = '".$row_id."'");
		$data = [];
		$columns = [
			["text" => $button_add, "class" => "width-10"],
            ["text" => str("sysuseraccessaccess_menu_id"), "class" => "width-10"],
            ["text" => str("sysuseraccessaccess_access_control"), "class" => "width-10"],
		];

		foreach($list as $lines) {
			$line_id = enkripsi($lines["line_id"]);
			$line = new SysUserAccessAccessEntity();
			$line->fill($lines);

			$button = buttonTableLine([
				["access" => getAccess($this->page_route), "label" => str("button_edit"), "url" => admin_url($this->page_route."/form-access/".$line_id."/")],
			]);

			$row = [];
			$row[] = ["value" => $button];
            $row[] = ["value" => printText(["value" => $line->menu_id_txt])];
            $row[] = ["value" => printText(["value" => $line->access_control])];
			$data[] = $row;
		}

		return table($columns, $data);
	}

	public function formAccess($id_detail=null, $id=null) 
	{
		$row_id = dekripsi($id);
		$line_id = dekripsi($id_detail);
        $access_control_list = ["" => "", "Full control" => "Full control", "Read only" => "Read only"];

		$sysuseraccessaccess_model = new SysUserAccessAccessModel();
		$data = $sysuseraccessaccess_model->getSelect("sysuseraccessaccess.line_id = '".$line_id."'");

		$page_button = button([
			["access" => getAccess($this->page_route), "id" => "btn_save", "onclick" => "save('form_input', 'btn_save')", "label" => str("button_save"), "color" => "success"],
			["access" => getAccess($this->page_route), "onclick" => "deleteAccess()", "label" => str("button_delete"), "color" => "danger"],
		]);

		$output = [
			"page_controller" => $this->page_controller,
			"page_title" => str("sysuseraccess"),
			"page_route" => $this->page_route,
			"page_title_line" => str("sysuseraccessaccess"),
			"page_button" => $page_button,
			"line_id" => $id_detail,
			"row_id" => $id,
			"data" => $data,
            "access_control_list" => $access_control_list,
		];
		
		echo view("sysuseraccess/formAccess", $output);
	}

	public function saveAccess() {
        $request = Services::request();
		$sysuseraccessaccess_model = new SysUserAccessAccessModel();
		$input = new SysUserAccessAccessEntity();
		$valid = true;
		$msg = str("process_successful");
		$status = 1;

		$line_id = $request->getPost("line_id");
		$state = ($line_id == "0") ? "create" : "update";
		if($state  == "create") {
			$input->created_date = getDatetime();
			$input->created_by = session()->get("name");

			$validation = [];
			if($validation != null) {
				$return_validation = $sysuseraccessaccess_model->checkValidation($validation);
				if(!$return_validation["valid"]) {
					$valid = false;
					$msg = $return_validation["msg"];
					$status = 0;
				}
			}
		}
		
		$input->line_id = dekripsi($line_id);
		$input->row_id = dekripsi($request->getPost("row_id"));		
		$input->modified_date = getDatetime();
		$input->modified_by = session()->get("name");
        $input->menu_id = $request->getPost("menu_id");
        $input->access_control = $request->getPost("access_control");

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

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

		echo json_encode($output);
	}

	function deleteAccess()
	{		
        $request = Services::request();
		$id = dekripsi($request->getGet('id'));		
		$sysuseraccessaccess_model = new SysUserAccessAccessModel();
		$sysuseraccessaccess_model->deleteData($id);

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

		echo json_encode($output);
	}
}
