<?php

namespace App\Controllers;

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

class Customer extends BaseController
{
	private $page_controller = "customer";
	private $page_route = "customer";

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

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

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

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

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

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

	public function save() {
        $request = Services::request();
		$customer_model = new CustomerModel();
		$input = new CustomerEntity();
		$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 = $customer_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->email = $request->getPost("email");
        $input->phone = $request->getPost("phone");
        $input->address = $request->getPost("address");

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

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

		echo json_encode($output);
	}

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

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

		echo json_encode($output);
	}

	public function excel() 
	{
		$customer_model = new CustomerModel();
		$data = $customer_model->exportExcel();		
		generateExcel($data, str("customer"));
	}

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

		$customer_model = new CustomerModel();
		$data = $customer_model->getSelect("customer.row_id = '".$row_id."'");

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

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