<?php

namespace App\Controllers;

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

class Product extends BaseController
{
	private $page_controller = "product";
	private $page_route = "product";

	public function index()
	{		
		$page_button = button([
			["access" => getAccess($this->page_route), "label" => str("button_export_excel"), "url" => admin_url($this->page_route."/excel"), "color" => "success"],
			["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("product")
		];
		echo view("product/index", $output);
	}

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

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

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

		$output = [
			"draw" => $request->getPost("draw"),
			"recordsTotal" => $product_model->countAll(),
			"recordsFiltered" => $product_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_print_pdf"), "url" => admin_url($this->page_route."/print/".$id), "color" => "secondary"],
			["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" => "deleteProduct()", "color" => "danger"]
		]);

		$product_model = new ProductModel();
		$data = $product_model->getSelect("product.row_id = '".$row_id."'");
		
		$output = [
			"page_controller" => $this->page_controller,
			"page_title" => str("product"),
			"page_route" => $this->page_route,
			"page_button" => $page_button,
			"row_id" => $id,
			"data" => $data,
		];
		echo view("product/form", $output);
	}

	public function save() {
        $request = Services::request();
		$product_model = new ProductModel();
		$input = new ProductEntity();
		$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 = $product_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->price = $request->getPost("price");

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

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

		echo json_encode($output);
	}

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

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

		echo json_encode($output);
	}

	public function excel() 
	{
		$product_model = new ProductModel();
		$data = $product_model->exportExcel();		
		generateExcel($data, str("product"));
	}

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

		$product_model = new ProductModel();
		$data = $product_model->getSelect("product.row_id = '".$row_id."'");

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

		$dompdf = new \Dompdf\Dompdf();		
		$dompdf->loadHtml(view("product/print", $output));
		$dompdf->setPaper("A4", "portrait");
		$dompdf->render();
		$dompdf->stream(str("product"));
	}
}
