<?php
 namespace Extension;
 use TCMS\ControlExtension;
 use TCMS\TException;
 class ChocolaSelect extends ControlExtension {
 private $option = [ 'name' => 'select', 'class' => 'form-control', 'data_source' => null, 'value_member' => 'id', 'display_member' => null, 'display_text' => false, 'error' => false, 'key' => false, ];
 public function render($value, $option = null) {
 copy_option($this->option, $option);
 if(!$this->option['key']) {
 throw new TException('Vui lòng truyền key cho extension chocola-select');
 }
 $model = \Model::load($this->option['data_source']);
 $model->select($this->option['value_member'], $this->option['display_member']);
 if(area_name() == 'master') {
 $auth = load_auth();
 $user = $auth->getUser();
 if($auth->hasRole(\RoleGlobal::$role->viewAllBranch)) {
 if(strtolower($this->option['key']) == 'branchid') {
 $model->whereIn($this->option['key'], $user->getBranchsId());
 }
 else {
 $model->where($this->option['key'], $user->storeID);
 }
 }
 else {
 if(strtolower($this->option['key']) == 'branchid') {
 $model->where($this->option['key'], $user->branchID);
 }
 else {
 $model->where($this->option['key'], $user->storeID);
 }
 }
 }
 $data = $model->toArray();
 echo '<select name="' . $this->option['name'] . '" class="' . $this->option['class'] . ($this->option['error'] ? ' error' : '') . ' ">';
 if($this->option['display_text']) {
 echo '<option value="">' . $this->option['display_text'] . '</option>';
 }
 $valueMember = $this->option['value_member'];
 $textMember = $this->option['display_member'];
 foreach($data as $d) {
 if($value && $value == $d[$valueMember]) echo '<option selected value="' . $d[$valueMember] . '">' . $d[$textMember] . '</option>';
 else echo '<option value="' . $d[$valueMember] . '">' . $d[$textMember] . '</option>';
 }
 echo '</select>';
 }
 }
