<?php

namespace App\Controllers;

use App\Models\GeneralModel;
use App\Models\SysMenuModel;
use App\Entities\SysMenuEntity;
use App\Models\SysMenuListModel;
use App\Entities\SysMenuListEntity;
use App\Controllers\BaseController;
use Config\Services;
use CodeIgniter\Exceptions\PageNotFoundException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SysMenu extends BaseController
{
	private $page_controller = "sysmenu";
	private $page_route = "menu";

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

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

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

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

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

		$sysmenu_model = new SysMenuModel();
		$data = $sysmenu_model->getSelect("sysmenu.row_id = '".$row_id."'");
		
		$output = [
			"page_controller" => $this->page_controller,
			"page_title" => str("sysmenu"),
			"page_route" => $this->page_route,
			"page_button" => $page_button,
			"row_id" => $id,
			"data" => $data,
			"table_list" => $this->tableList($id),
		];
		echo view("sysmenu/form", $output);
	}

	public function save() {
        $request = Services::request();
		$sysmenu_model = new SysMenuModel();
		$input = new SysMenuEntity();
		$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 = [];
			if($validation != null) {
				$return_validation = $sysmenu_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->folder_name = $request->getPost("folder_name");
        $input->seq = $request->getPost("seq");
        $input->icon = $request->getPost("icon");

		if($valid) {
			$sysmenu_model->save($input);
			$row_id = ($row_id == "0") ? enkripsi($sysmenu_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();
		$sysmenu_model = new SysMenuModel();
		$sysmenu_model->deleteData(dekripsi($request->getGet('id')));

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

		echo json_encode($output);
	}

	public function excel() 
	{
		$sysmenu_model = new SysMenuModel();
		$data = $sysmenu_model->exportExcel();		
		generateExcel($data, str("sysmenu"));
	}

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

		$sysmenu_model = new SysMenuModel();
		$data = $sysmenu_model->getSelect("sysmenu.row_id = '".$row_id."'");

		$output = [
			"document_name" => str("sysmenu"),
			"data" => $data,
			"table_list" => $this->tableList($id),
		];

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

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

		$sysmenu_model = new SysMenuModel();
		$header = $sysmenu_model->getSelect("sysmenu.row_id = '".$row_id."'");

		$sysmenulist_model = new SysMenuListModel();
		$line_id = 0;
		$button_add = buttonLine(["access" => getAccess($this->page_route), "label" => str("button_add"), "url" => admin_url($this->page_route."/form-list/".$line_id."/"), "color" => "primary"]);
		$list = $sysmenulist_model->getTable($row_id);
		$data = [];
		$columns = [
			["text" => $button_add, "class" => "width-10"],
            ["text" => str("sysmenulist_menu_name"), "class" => "width-40"],
            ["text" => str("sysmenulist_route"), "class" => "width-40"],
            ["text" => str("sysmenulist_seq"), "class" => "width-10"],
		];

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

			$row = [];
			$row[] = ["value" => $button];
            $row[] = ["value" => printText(["value" => $line->menu_name])];
            $row[] = ["value" => printText(["value" => $line->route])];
            $row[] = ["value" => printNumber(["value" => $line->seq])];
			$data[] = $row;

		}

		return table($columns, $data);
	}

	public function formList($id_detail=null, $id=null) 
	{
		$row_id = dekripsi($id);
		$line_id = dekripsi($id_detail);

		$sysmenulist_model = new SysMenuListModel();
		$data = $sysmenulist_model->getSelect("sysmenulist.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" => "deleteList()", "label" => str("button_delete"), "color" => "danger"],
		]);

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

	public function saveList() {
        $request = Services::request();
		$sysmenulist_model = new SysMenuListModel();
		$input = new SysMenuListEntity();
		$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 = [
				["type" => "unique", "field" => "route", "value" => $request->getPost("route")],];
			if($validation != null) {
				$return_validation = $sysmenulist_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_name = $request->getPost("menu_name");
        $input->route = $request->getPost("route");
        $input->seq = $request->getPost("seq");

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

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

		echo json_encode($output);
	}

	function deleteList()
	{		
        $request = Services::request();
		$id = dekripsi($request->getGet('id'));		
		$sysmenulist_model = new SysMenuListModel();
		$sysmenulist_model->deleteData($id);

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

		echo json_encode($output);
	}

	function test()
	{
		$sysmenu_model = new SysMenuModel();
		$rs = $sysmenu_model->getMenuByRoleId("1");
		echo json_encode($rs);
	}
}
