<?php

namespace App\Controllers;

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

class SysWebInfo extends BaseController
{
	private $page_controller = "syswebinfo";
	private $page_route = "web-info";

	public function index()
	{		
		return redirect()->to(admin_url($this->page_route."/form/".enkripsi("1")));
	}

	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"],
		]);
        $format_date_list = ["" => "", "d-M-Y" => "14-FEB-2021", "M-d-Y" => "FEB-14-2021", "Y-m-d" => "2021-02-14"];

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

	public function save() {
        $request = Services::request();
		$syswebinfoModel = new SysWebInfoModel();
		$input = new SysWebInfoEntity();
		$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 = $syswebinfomodel->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->company_name = $request->getPost("company_name");
        $input->application_name = $request->getPost("application_name");
        $input->format_date = $request->getPost("format_date");
        $input->currency = $request->getPost("currency");
        $file = $request->getFile("web_icon");
        $web_icon = saveImage($request, "web_icon");
        $input->web_icon = $web_icon;
        $file = $request->getFile("company_logo");
        $company_logo = saveImage($request, "company_logo");
        $input->company_logo = $company_logo;

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

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

		echo json_encode($output);
	}
}
