<?php
class GroupSetting extends AppModel
{
	var $name='GroupSetting';
    private $restricted_modes = ['ON' => 1, 'OFF' => 0];

    public function getGroupSettingByURL($unique_url,$custom_select = false){

        $options = array(
            'conditions' => array('GroupSetting.unique_url' => $unique_url)
        );

        if ($custom_select) {
            $options['fields'] = array(
                'GroupSetting.categories',
                'GroupSetting.version',
                'GroupSetting.is_restricted_mode'
            );
        }

        $groupSettingData = $this->find('first', $options);

        if (empty($groupSettingData) && empty($groupSettingData['GroupSetting'])) {
            return false;
        }

        $groupSettingData['GroupSetting']['categories'] = json_decode($groupSettingData['GroupSetting']['categories'], true);
        return $groupSettingData['GroupSetting'];

    }
    public function saveGroupSetting($groupSettingData)
    {
        $request = $this->_prepareFields($groupSettingData);
        return $this->save($request);

    }

    public function PermissionEnabled($unique_url){
        $group_setting = $this->getGroupSettingByURL($unique_url);
        if (empty($group_setting)) {
            return PUBLIC_PERMIT;
        }
        $isRestricted = isset($group_setting['is_restricted_mode']) &&
            $group_setting['is_restricted_mode'] == $this->restricted_modes['OFF'];
        if ($isRestricted) {
            return NO_PERMIT;
        }
        return $group_setting;
    }
    protected function _prepareFields($data)
    {
        $returnData = array();
        if (isset($data['is_restricted_mode'])) {
            $returnData['is_restricted_mode'] = $data['is_restricted_mode'];
        }
        if (isset($data['expense_id'])) {
            $returnData['expense_id'] = $data['expense_id'];
        }
        if (isset($data['unique_url'])) {
            $returnData['unique_url'] = $data['unique_url'];
        }
        $returnData['categories'] = (!empty($data['categories'])) ? $data['categories'] : '[]';

        if (!empty($data['id'])) {
            $returnData['id'] = $data['id'];
            $returnData['version'] = $data['version'] + 1;
        }
        else{
            $returnData['version'] = 0;
        }

        return $returnData;

    }
	 
	 
	 
}