<?php
/*--------------------------------------------------------- 
 * File:checkBoxList.php
 * Author:Tomix
 * Description: 
 * Created:2009
 * -------------------------------------------------------
 * Modified history:2023/08/23
 * Copyright © 2023 蘋果世界股份有限公司 版權所有
 * -------------------------------------------------------
 */
class checkBoxList {
	public $id = "checkBoxList1";	// ID
	public $name;					// 名稱
	public $cssClass;				// 樣式
	public $valueField;				// 值字段
	public $titleField;				// 標題(文本)字段
	public $dataSource = [];		// 數據源
	public $checkedValue = [];		// 當前選中值
	
	public function getContent(): string {
		$text = "";
		if (!is_array($this->dataSource)) return "Data source is not an array!";
		
		foreach ($this->dataSource as $row) {
			$text .= $this->buildListItem($row) . "\r\n";
		}
		return $text;
	}
    
    public function render(): void {
        echo $this->getContent();
    }
    
    private function buildListItem(array $row): string {
        if (is_array($this->checkedValue) && in_array($row[$this->valueField], $this->checkedValue, true)) {
            return "<input type=\"checkbox\" name=\"" . $this->name . "[]\" value=\"" . $row[$this->valueField] . "\" checked=\"checked\" /><label>" . $row[$this->titleField] . "</label>";
        } else {
            return "<input type=\"checkbox\" name=\"" . $this->name . "[]\" value=\"" . $row[$this->valueField] . "\" /><label>" . $row[$this->titleField] . "</label>";
        }
    }
}
?>