<?php

namespace App\Controllers;

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

class Sales extends BaseController
{
	private $page_controller = "sales";
	private $page_route = "sales";

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

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

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

			$row = [];
			$row[] = $button;
            $row[] = $link_view;
            $row[] = printDate(["value" => $line->trans_date]);
            $row[] = printText(["value" => $line->customer_id_txt]);
            $row[] = printText(["value" => $line->product_id_txt]);
            $row[] = printNumber(["value" => $line->qty]);
            $row[] = printMoney(["value" => $line->total_amount]);
            $row[] = printCheckbox(["value" => $line->doc_list]);
            $row[] = printNoYes(["value" => $line->taxed]);
            $row[] = printText(["value" => $line->status]);
			$data[] = $row;
		}

		$output = [
			"draw" => $request->getPost("draw"),
			"recordsTotal" => $sales_model->countAll(),
			"recordsFiltered" => $sales_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" => "deleteSales()", "color" => "danger"]
		]);
        $generalModel = new GeneralModel();
        $product_id_list = $generalModel->dropdownList(["table" => "product", "id"=>"row_id", "text"=>"name"]);
        $doc_list_list = ["Invoice" => "Invoice", "Warranty" => "Warranty"];
        $status_list = ["" => "", "Draft" => "Draft", "Paid" => "Paid"];

		$sales_model = new SalesModel();
		$data = $sales_model->getSelect("sales.row_id = '".$row_id."'");
		
		$output = [
			"page_controller" => $this->page_controller,
			"page_title" => str("sales"),
			"page_route" => $this->page_route,
			"page_button" => $page_button,
			"row_id" => $id,
			"data" => $data,
            "product_id_list" => $product_id_list,
            "doc_list_list" => $doc_list_list,
            "status_list" => $status_list,
		];
		echo view("sales/form", $output);
	}

	public function save() {
        $request = Services::request();
		$sales_model = new SalesModel();
		$input = new SalesEntity();
		$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 = $sales_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->trans_date = $request->getPost("trans_date");
        $input->customer_id = $request->getPost("customer_id");
        $input->product_id = $request->getPost("product_id");
        $input->description = $request->getPost("description");
        $input->qty = $request->getPost("qty");
        $input->total_amount = $request->getPost("total_amount");
        $input->taxed = $request->getPost("taxed");
        $input->doc_list = $request->getPost("doc_list");
        $input->status = $request->getPost("status");

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

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

		echo json_encode($output);
	}

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

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

		echo json_encode($output);
	}

	public function excel() 
	{
		$sales_model = new SalesModel();
		$data = $sales_model->exportExcel();		
		generateExcel($data, str("sales"));
	}

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

		$sales_model = new SalesModel();
		$data = $sales_model->getSelect("sales.row_id = '".$row_id."'");

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

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