<?php
namespace App\Controller;
use App\Controller\AppController;

use Cake\Core\Configure;
use Cake\Http\Client;

class ProfilesController extends AppController
{

    public function index($id = 13112){

        $this->viewBuilder()->layout('blank');

        /*******************************/

	$id = $this->Auth->user('id');
	
        $this->loadModel('Users');
        $responseUserProfile = $this->Users->get($id, [
                'contain' => []
            ]);
        $username = $responseUserProfile['username'];

        $this->loadModel('UserPersonals');
        $responseUserPersonal = $this->UserPersonals->find('all', [
            'conditions' => [
                
                'user_id' => $id ]
            ])->first();

        //********DropdownCountry********
        $this->loadModel('MasterCountries');
        $Country = $this->MasterCountries->find('list', [
            'conditions' => [
                'is_used' => true],
            'keyField' => 'id',
            'valueField' => 'country_name_th'
        ]);
        if(!empty($Country)) $Country = $Country->toArray();

        //********DropdownProvince********
        $this->loadModel('MasterProvinces');
        $Province = $this->MasterProvinces->find('list', [
            'conditions' => [
                'is_used' => true],
            'keyField' => 'id',
            'valueField' => 'province_name_th'
        ])
	->where(['master_country_id =' => $responseUserPersonal['master_country_id']])
	->order(['province_name_th']);
        // pr($Province);die;
        if(!empty($Province)) $Province = $Province->toArray();

        $res = $responseUserPersonal['birthdate'];
        $dateNow = $res->i18nFormat('dd/MM/yyyy');

        if ($this->request->is(['patch', 'post', 'put'])) {
            $data = $this->request->data;

            // pr($this->request->data);die;
            $this->loadModel('UserPersonals');
            $userPersonals = $this->UserPersonals->find('all',
                [      
                    'limit' => 1,
                    'conditions' => [
                        'user_id' => $data['Users']['user_id']
                    ]
                ]
            )->first();
 
            if($userPersonals['email'] == $this->request->data['UserPersonals']['email']){
                $chkemail = true;
            }else{
                $userPersonals = $this->UserPersonals->find('all',
                [      
                    'limit' => 1,
                    'conditions' => [
                        'email' => $data['UserPersonals']['email']
                    ]
                ]
                )->toArray();

                if(empty($userPersonals)){
                    $chkemail = true;
                }else{
                    $chkemail = false;
                }
            }

            if($chkemail == true){
            
            $birthdate = explode("/", $this->request->data['UserPersonals']['birthdate']);
            $birthdate = $birthdate[2].'-'.$birthdate[1].'-'.$birthdate[0];
            
            $userPersonals = $this->UserPersonals->patchEntity($userPersonals, $data['UserPersonals']);
            $userPersonals['firstname_th'] = $this->request->data['UserPersonals']['firstname_th'];
            $userPersonals['lastname_th'] = $this->request->data['UserPersonals']['lastname_th'];
            $userPersonals['email'] = $this->request->data['UserPersonals']['email'];
            $userPersonals['birthdate'] = $birthdate;
            $userPersonals['user_id'] = $data['Users']['user_id'];
            $userPersonals['master_country_id'] = $this->request->data['master_country_id'];
            $userPersonals['master_province_id'] = $this->request->data['master_province_id'];
            $userPersonals['modified_by'] = $id;

                if ($this->UserPersonals->save($userPersonals)) {
                    $this->Flash->success(__('Update Complete.'));
                    return $this->redirect(['action' => 'index']);
                }
            }else{
                $this->Flash->error(__('Email Address already used by others.'));
            }
            $this->Flash->error(__('Not update. Please, try again.'));
        }
        $this->set(compact('userPersonals', 'responseUserProfile',  'dateNow', 'username', 'Country', 'Province', 'responseUserPersonal'));
        $this->set('_serialize', ['userPersonals', 'responseUserProfile', 'dateNow', 'username', 'Country', 'Province']);
    }

    /*****************************************************************************/
    public function settingProfile()
    {
    	//prr($this->request->getHeaderLine('Accept-Language'));
        $this->viewBuilder()->layout('blank');
	
        $http = new Client();
        $data = [];
        $options = ['headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Authorization' => $this->request->getHeaderLine('Authorization')
                //'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1OTI0OSwidXNlcm5hbWUiOiJ0ZXN0dGVzdCIsImlwIjoiMTE2LjU4LjIyNS4yNDgiLCIkdG9waWMiOiJ0ZXN0dGVzdDMzM2Y5MWI5ZjVlMTQzMjlmMWQ2ZTc2MzgwYjhiOWVhIn0.7KwfmevJ--tz0ta5f1O_eDxKSPAjWuAzLSRCNSeWg-g'
                //'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1OTI4OCwidXNlcm5hbWUiOiJOYW5hMyIsImlwIjoiMTI3LjAuMC4xIiwiJHRvcGljIjoiTmFuYTNiODAwMjVlNWYyZTUxZDVkMmY0ZTM1Y2E4YWFkNmI1MSJ9.Up1oxsqxWASpOmj9UsAuHISlKArT2EE5NRM0bB2NLIE'
                //'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1OTI5NCwidXNlcm5hbWUiOiJOYW5hOCIsImlwIjoiMTI3LjAuMC4xIiwiJHRvcGljIjoiTmFuYThhMzQzYmRiNjNiNzYxZWFjMTFmYzBlOGU2ZDQ2NjE5YyJ9.B2vi2ftThzO8bfv7xDx3lgpo_3-us-S10OzBpFmRn2Q'
            ]
        ];
        //debug($options);
	$api_core_profile = Configure::read('Config.apiCore.profile');
	$http = new Client();
	$response = $http->post($api_core_profile,$data,$options)->body();
	$response = json_decode($response,'_full');#prr($response);
	
	$Profiles = $response['result']['Data'];
	$this->set(compact('Profiles'));
	#$Profiles['UserProfiles'][0]['organize_id'] = 10;
	#$Profiles['UserProfiles'][0]['dept_id'] = 10;
        #debug($Profiles);
	$count_user_profile = count($Profiles['UserProfiles']);
        //$Profiles['UserProfiles'] = $Profiles['UserProfiles'][0];
	$Profiles['UserProfiles']['education'] = @$Profiles['UserProfiles'][0];
	unset($Profiles['UserProfiles'][0]);
	if(count($Profiles['UserProfiles']) > 1){ $Profiles['UserProfiles']['work'] = $Profiles['UserProfiles'][1];unset($Profiles['UserProfiles'][1]);}	
	
	//$master_language_id = $Profiles['UserDefaultLanguages']['master_language_id'];	
	$master_language_id = $this->request->getHeaderLine('Accept-Language');
	$this->loadModel('MasterLanguages');
	$MasterLanguages = $this->MasterLanguages->find('list',
						[
							'conditions' => ['id' => $master_language_id],
							'keyField' => 'id',
							'valueField' => 'language_abbr'
						]
						);
	if(!empty($MasterLanguages)) $MasterLanguages = $MasterLanguages->toArray();
	#prd($MasterLanguages);	
	//$language = strtolower($MasterLanguages[$master_language_id]);		

	#Education
	#---------------------------------------------------------------------------------------------------------------
	$this->loadModel('MasterOrganizations');
	$MasterOrganizationEducations = $this->MasterOrganizations->find('list',
						[
							'conditions' => ['master_organization_type_id' => 1],
							'keyField' => 'id',
							'valueField' => 'org_name_th',
							'order' => 'org_name_th asc'
						]
						);
	if(!empty($MasterOrganizationEducations)) $MasterOrganizationEducations = $MasterOrganizationEducations->toArray();
        $this->set(compact('MasterOrganizations'));
	//debug($MasterOrganizationEducations);
		
	$this->loadModel('MasterDepartments');
	$MasterDepartments = $this->MasterDepartments->find('list',
						[
							//'conditions' => ['master_organization_id' => $Profiles['UserProfiles']['education']['organize_id']],
                                                        //'conditions' => ['master_organization_id' => $Profiles['UserProfiles'][0]['organize_id']],
                                                        'conditions' => ['master_organization_id' => 7],
							'keyField' => 'id',
							'valueField' => 'dept_name_th',
							'order' => 'dept_name_th asc'
						]
						);
	if(!empty($MasterDepartments)) $MasterDepartments = $MasterDepartments->toArray();
        $this->set(compact('MasterDepartments'));
	//debug($MasterDepartments);
	
	$this->loadModel('MasterSections');
	$MasterSections = $this->MasterSections->find('list',
						[
							//'conditions' => ['master_department_id' => $Profiles['UserProfiles']['education']['dept_id']],
                                                        //'conditions' => ['master_department_id' => $Profiles['UserProfiles'][0]['dept_id']],
                                                        'conditions' => ['master_department_id' => 49],
							'keyField' => 'id',
							'valueField' => 'section_name_th',
							'order' => 'section_name_th asc'
						]
						);
	if(!empty($MasterSections)) $MasterSections = $MasterSections->toArray();
        $this->set(compact('MasterSections'));
	//debug($MasterSections);
	
	
	
	
	#Work
	#---------------------------------------------------------------------------------------------------------------
	$MasterOrganizationPositions = [];
	if(!empty($Profiles['UserProfiles']['work']['organize_id'])){
		$this->loadModel('MasterOrganizationPositions');
		$MasterOrganizationPositions = $this->MasterOrganizationPositions->find('list',
							[
								'conditions' => ['master_organization_id' => $Profiles['UserProfiles']['work']['organize_id']],
								'keyField' => 'id',
								'valueField' => 'organization_position_name',
								'order' => 'organization_position_name asc'
							]
							);
		if(!empty($MasterOrganizationPositions)) $MasterOrganizationPositions = $MasterOrganizationPositions->toArray();
		#prd($MasterOrganizationPositions);
	}
	
	$this->loadModel('MasterBusinessTypes');
	$MasterBusinessTypes = $this->MasterBusinessTypes->find('list',
						[
							'conditions' => ['master_language_id' => $master_language_id],
							'keyField' => 'id',
							'valueField' => 'business_type_name',
							'order' => 'business_type_name asc',
						]
						);
	if(!empty($MasterBusinessTypes)) $MasterBusinessTypes = $MasterBusinessTypes->toArray();
	#prd($MasterBusinessTypes);

	$this->loadModel('MasterOrganizations');
	$MasterOrganizationWorks = $this->MasterOrganizations->find('list',
						[
							'conditions' => ['master_organization_type_id' => 2],
							'keyField' => 'id',
							'valueField' => 'org_name_th',
							'order' => 'org_name_th asc'
							
						]
						);
	if(!empty($MasterOrganizationWorks)) $MasterOrganizationWorks = $MasterOrganizationWorks->toArray();
	#prd($MasterOrganizationWorks);			
	
	$MasterSectionWorks = [];
	if(!empty($Profiles['UserProfiles']['work']['dept_id'])){	
		$this->loadModel('MasterSections');
		$MasterSectionWorks = $this->MasterSections->find('list',
							[
								'conditions' => ['master_department_id' => $Profiles['UserProfiles']['work']['dept_id']],
								'keyField' => 'id',
								'valueField' => 'section_name_th',
								'order' => 'section_name_th asc'
							]
							);
		if(!empty($MasterSectionWorks)) $MasterSectionWorks = $MasterSectionWorks->toArray();
		#prd($MasterSectionWorks);
	}
        #debug($Profiles);
        $this->set(compact(
				'Profiles', 
				'MasterOrganizationEducations', 'MasterDepartmentEducations', 'MasterSectionEducations',
				'MasterOrganizationPositions', 'MasterBusinessTypes', 'MasterOrganizationWorks', 'MasterSectionWorks'
	));

    }
    
    public function updateProfile()
    {
    
        $this->viewBuilder()->layout('blank');
	
	$data = $this->request->data;#debug($data);
	
	#$api_update_profile = 'http://connect06.pakgon.com/api/Connects/Profile/updateProfile';
	#$api_update_profile = Configure::read('Config.apiCore.profile').'/updateProfile';
	$http = new Client();
        $data = [];
        $options = ['headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Authorization' => $this->request->getHeaderLine('Authorization')
                //'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1OTI0OSwidXNlcm5hbWUiOiJ0ZXN0dGVzdCIsImlwIjoiMTE2LjU4LjIyNS4yNDgiLCIkdG9waWMiOiJ0ZXN0dGVzdDMzM2Y5MWI5ZjVlMTQzMjlmMWQ2ZTc2MzgwYjhiOWVhIn0.7KwfmevJ--tz0ta5f1O_eDxKSPAjWuAzLSRCNSeWg-g'
                //'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1OTI4OCwidXNlcm5hbWUiOiJOYW5hMyIsImlwIjoiMTI3LjAuMC4xIiwiJHRvcGljIjoiTmFuYTNiODAwMjVlNWYyZTUxZDVkMmY0ZTM1Y2E4YWFkNmI1MSJ9.Up1oxsqxWASpOmj9UsAuHISlKArT2EE5NRM0bB2NLIE'
                //'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1OTI5NCwidXNlcm5hbWUiOiJOYW5hOCIsImlwIjoiMTI3LjAuMC4xIiwiJHRvcGljIjoiTmFuYThhMzQzYmRiNjNiNzYxZWFjMTFmYzBlOGU2ZDQ2NjE5YyJ9.B2vi2ftThzO8bfv7xDx3lgpo_3-us-S10OzBpFmRn2Q'
            ]
        ];
        //debug($options);exit();
	$api_update_profile = Configure::read('Config.apiCore.profile');
	$http = new Client();
	$response = $http->post($api_update_profile,$data,$options)->body();
	//debug($response);
	$response = json_decode($response,'_full');#debug($response);
	
	$Profiles = $response['result']['Data'];
	$this->set(compact('Profiles'));
        
        $this->loadModel('UserPersonLists');
        $this->loadModel('UserProfiles');
        $this->loadModel('AppAccess');
        $this->loadModel('SubjectEnrolls');
        //debug($this->request->data);
        if ($this->request->is('post')) {
        #59294
            
          //if (!empty($this->request->data)) {
$UserPersonLists_V = $this->UserPersonLists->find('all',
						[
						#'conditions' => ['is_used' => true,'username' => $data['username']],
						'conditions' => ['user_id' => $this->request->data['data']['Users']['id']],
						'fields' => ['id', 'user_id'],
						'limit' => 1
						]
						)->toArray();
//debug($UserPersonLists[0]['id']);exit();
//if (empty($UserPersonLists[0]['id'] == null)) {
if (!empty($UserPersonLists_V)) {
            foreach($this->request->data as $UserPersonLists) {
                //$UserPersonLists=$this->UserPersonLists->newEntity();
                //debug($UserPersonLists['id'] = $this->request->data['data']['Users']['id']);exit();
                //debug($UserPersonLists['data']['Users']['id']);exit();
                //debug($UserPersonLists=$this->UserPersonLists->get($UserPersonLists['Users']['id']));exit();
                //debug($UserPersonLists_V);exit();
                $UserPersonLists=$this->UserPersonLists->get($UserPersonLists_V[0]['id']);
                $UserPersonLists['master_organization_id'] = $this->request->data['data']['UserProfiles']['education']['organize_id'];
                $UserPersonLists['master_department_id'] = $this->request->data['data']['UserProfiles']['education']['dept_id'];
                $UserPersonLists['master_section_id'] = $this->request->data['data']['UserProfiles']['education']['section_id'];
                $UserPersonLists['card_code'] = $this->request->data['data']['UserProfiles']['education']['card_code'];
                $UserPersonLists['first_name'] = $this->request->data['data']['UserPersonals']['name'];
                $UserPersonLists['last_name'] = $this->request->data['data']['UserPersonals']['name'];
                $UserPersonLists['master_user_type_id'] = '1';
                $UserPersonLists['user_id'] = $this->request->data['data']['Users']['id'];
                $UserPersonLists['is_used'] = '1';
                $UserPersonLists['created'] = date('Y-m-d H:i:s');
                $UserPersonLists['create_uid'] = '0';
                $UserPersonLists['modified'] = date('Y-m-d H:i:s');
                $UserPersonLists['update_uid'] = '0';
                $UserPersonLists['master_prefix_id'] = '1';
                //debug($UserPersonLists);exit();
                if (empty($UserPersonLists['card_code'] == null || $UserPersonLists['master_organization_id'] == null || $UserPersonLists['master_department_id'] == null || $UserPersonLists['master_section_id'] == null)) {
                if ($this->UserPersonLists->save($UserPersonLists)) {
                     
                }
                
                } else{
                    $this->Flash->error(__('ไม่สามารถปรับปรุงข้อมูลการศึกษาได้ โปรดติด่อเจ้าหน้าที่'));
            return $this->redirect(['controller' => 'Profiles', 'action' => 'index']);
                }
                //debug($this->UserPersonLists->save($UserPersonLists));exit();
            }
}else { 
                foreach($this->request->data as $UserPersonLists) {
                $UserPersonLists=$this->UserPersonLists->newEntity();
                //debug($UserPersonLists['id'] = $this->request->data['data']['Users']['id']);exit();
                //debug($UserPersonLists['data']['Users']['id']);exit();
                //debug($UserPersonLists=$this->UserPersonLists->get($UserPersonLists['Users']['id']));exit();
                //debug($UserPersonLists_V);exit();
                //$UserPersonLists=$this->UserPersonLists->get($UserPersonLists_V[0]['id']);
                $UserPersonLists['master_organization_id'] = $this->request->data['data']['UserProfiles']['education']['organize_id'];
                $UserPersonLists['master_department_id'] = $this->request->data['data']['UserProfiles']['education']['dept_id'];
                $UserPersonLists['master_section_id'] = $this->request->data['data']['UserProfiles']['education']['section_id'];
                $UserPersonLists['card_code'] = $this->request->data['data']['UserProfiles']['education']['card_code'];
                $UserPersonLists['first_name'] = $this->request->data['data']['UserPersonals']['name'];
                $UserPersonLists['last_name'] = $this->request->data['data']['UserPersonals']['name'];
                $UserPersonLists['master_user_type_id'] = '1';
                $UserPersonLists['user_id'] = $this->request->data['data']['Users']['id'];
                $UserPersonLists['is_used'] = '1';
                $UserPersonLists['created'] = date('Y-m-d H:i:s');
                $UserPersonLists['create_uid'] = '0';
                $UserPersonLists['modified'] = date('Y-m-d H:i:s');
                $UserPersonLists['update_uid'] = '0';
                $UserPersonLists['master_prefix_id'] = '1';
                //debug($UserPersonLists);exit();
                if (empty($UserPersonLists['card_code'] == null || $UserPersonLists['master_organization_id'] == null || $UserPersonLists['master_department_id'] == null || $UserPersonLists['master_section_id'] == null)) {
                
                    if ($this->UserPersonLists->save($UserPersonLists)) {
                     
                }
                
                } else{
                    $this->Flash->error(__('ไม่สามารถปรับปรุงข้อมูลการศึกษาได้ โปรดติด่อเจ้าหน้าที่'));
            return $this->redirect(['controller' => 'Profiles', 'action' => 'index']);
                }
                //debug($this->UserPersonLists->save($UserPersonLists));exit();
            }
            }
     
            
$UserProfiles = $this->UserProfiles->find('all',
						[
						'conditions' => ['user_id' => $this->request->data['data']['Users']['id']],
						'fields' => ['user_id'],
						'limit' => 1
						]
						)->toArray();
//debug($this->request->data['data']['Users']['id']);exit();
if (!empty($this->request->data['data']['Users']['id'])) {
   foreach($UserProfiles as $user_profiles) {
   $user_profiles=$this->UserProfiles->get($this->request->data['data']['UserProfiles']['education']['id']);
   //$date = date_create('2000-01-01');
                //$user_profiles['id'] = $this->request->data['data']['Users']['id'];
                //$user_profiles['user_id'] = $this->request->data['data']['Users']['id'];
                $user_profiles['organize_id'] = $this->request->data['data']['UserProfiles']['education']['organize_id'];
                $user_profiles['dept_id'] = $this->request->data['data']['UserProfiles']['education']['dept_id'];
                $user_profiles['section_id'] = $this->request->data['data']['UserProfiles']['education']['section_id'];
                $user_profiles['card_code'] = $this->request->data['data']['UserProfiles']['education']['card_code'];
                $user_profiles['user_type_id'] = '1';
                $user_profiles['img_path'] = '';
                //$user_profiles['is_used'] = '1';
                //$user_profiles['created_by'] = '0';
                $user_profiles['created'] = date('Y-m-d H:i:s');
                $user_profiles['modified_by'] = '0';
                $user_profiles['modified'] = date('Y-m-d H:i:s');
                //$user_profiles['position_org'] = '195';
                //$user_profiles['position_edu'] = '89';
                $user_profiles['enter_date'] = date('Y-m-d');
                $user_profiles['address'] = $this->request->data['data']['UserProfiles']['education']['address'];
                $user_profiles['master_business_type_id'] = '0';
                $user_profiles['phone_no'] = $this->request->data['data']['UserProfiles']['education']['phone_no'];
                $user_profiles['master_organization_position_id'] = $this->request->data['data']['UserProfiles']['education']['organize_id'];
                //debug($this->request->data)
                //debug($this->UserProfiles->save($user_profiles));exit;
                //debug($user_profiles);exit();
   if($this->UserProfiles->save($user_profiles)){
   }
   //return $this->redirect(['controller' => 'Profiles', 'action' => 'index']);
}          
}else { 
                foreach($this->request->data as $UserPersonLists) {
                $UserPersonLists=$this->UserPersonLists->newEntity();
                //debug($UserPersonLists['id'] = $this->request->data['data']['Users']['id']);exit();
                //debug($UserPersonLists['data']['Users']['id']);exit();
                //debug($UserPersonLists=$this->UserPersonLists->get($UserPersonLists['Users']['id']));exit();
                //debug($UserPersonLists_V);exit();
                //$UserPersonLists=$this->UserPersonLists->get($UserPersonLists_V[0]['id']);
                $user_profiles['organize_id'] = $this->request->data['data']['UserProfiles']['education']['organize_id'];
                $user_profiles['dept_id'] = $this->request->data['data']['UserProfiles']['education']['dept_id'];
                $user_profiles['section_id'] = $this->request->data['data']['UserProfiles']['education']['section_id'];
                $user_profiles['card_code'] = $this->request->data['data']['UserProfiles']['education']['card_code'];
                $user_profiles['user_type_id'] = '1';
                $user_profiles['img_path'] = '';
                //$user_profiles['is_used'] = '1';
                //$user_profiles['created_by'] = '0';
                $user_profiles['created'] = date('Y-m-d H:i:s');
                $user_profiles['modified_by'] = '0';
                $user_profiles['modified'] = date('Y-m-d H:i:s');
                //$user_profiles['position_org'] = '195';
                //$user_profiles['position_edu'] = '89';
                $user_profiles['enter_date'] = date('Y-m-d');
                $user_profiles['address'] = $this->request->data['data']['UserProfiles']['education']['address'];
                $user_profiles['master_business_type_id'] = '0';
                $user_profiles['phone_no'] = $this->request->data['data']['UserProfiles']['education']['phone_no'];
                $user_profiles['master_organization_position_id'] = $this->request->data['data']['UserProfiles']['education']['organize_id'];
                //debug($UserPersonLists);exit();
                
                    if ($this->UserPersonLists->save($UserPersonLists)) {
                     
                }
                
                //debug($this->UserPersonLists->save($UserPersonLists));exit();
            }
            
            }


$AppAccess = $this->AppAccess->find('all',
						[
						'conditions' => ['user_id' => $this->request->data['data']['Users']['id']],
						//'fields' => ['user_id'],
						'limit' => 1
						]
						)->toArray();
//debug($AppAccess);//exit();
//debug($AppAccess);exit();
if (!empty($AppAccess)) {
//debug($AppAccess);exit();
foreach($AppAccess as $app_access) {
    //debug($app_access);exit();
   //debug($this->request->data['data']['Users']['id']);exit();
   $app_access=$this->AppAccess->get($app_access['id']);
   //$user_profiles=$this->UserProfiles->get($this->request->data['data']['UserProfiles']['education']['id']);
   //$app_access=$this->AppAccess->newEntity();
   //debug($AppAccess);exit();
                $AppAccess['user_id'] = $this->request->data['data']['Users']['id'];
                $app_access['master_app_id'] = '3';
                $app_access['is_used'] = '1';
                $app_access['create_uid'] = '0';
                $app_access['created'] = date('Y-m-d H:i:s');
                $app_access['update_uid'] = '0';
                $app_access['modified'] = date('Y-m-d H:i:s');
                //debug($app_access);exit();
   if($this->AppAccess->save($app_access)){
   }
}
}else{
//debug($this->request->data['data']['Users']['id']);exit();
  foreach($this->request->data as $app_access) {
    //debug($this->request->data);exit();
   //debug($this->request->data['data']['Users']['id']);exit();
   //$app_access=$this->AppAccess->get($app_access['id']);
   //$user_profiles=$this->UserProfiles->get($this->request->data['data']['UserProfiles']['education']['id']);
   $app_access=$this->AppAccess->newEntity();
   //debug($this->request->data['data']['Users']['id']);exit();
                $app_access['user_id'] = $this->request->data['data']['Users']['id'];
                $app_access['master_app_id'] = '3';
                $app_access['is_used'] = '1';
                $app_access['create_uid'] = '0';
                $app_access['created'] = date('Y-m-d H:i:s');
                $app_access['update_uid'] = '0';
                $app_access['modified'] = date('Y-m-d H:i:s');
                //debug($app_access);exit();
   if($this->AppAccess->save($app_access)){
   }

}

}

$SubjectEnrolls = $this->SubjectEnrolls->find('all',
						[
						'conditions' => ['user_id' => $this->request->data['data']['Users']['id']],
						//'fields' => ['user_id'],
						'limit' => 1
						]
						)->toArray();
//$SubjectEnrolls = $this->SubjectEnrolls->find('all')->toArray();
//debug($SubjectEnrolls);exit();
if (!empty($SubjectEnrolls)) {
   foreach($this->request->data as $subject_enrolls) {
       //debug($subject_enrolls);exit();
   $subject_enrolls=$this->SubjectEnrolls->get($SubjectEnrolls[0]['id']);
   //$subject_enrolls=$this->SubjectEnrolls->newEntity();
                $subject_enrolls['subject_id'] = '';
                $subject_enrolls['user_id'] = $this->request->data['data']['Users']['id'];
                $subject_enrolls['master_organization_id'] = $this->request->data['data']['UserProfiles']['education']['organize_id'];
                $subject_enrolls['card_code'] = $this->request->data['data']['UserProfiles']['education']['card_code'];
                $subject_enrolls['is_used'] = '1';
                $subject_enrolls['create_uid'] = '0';
                $subject_enrolls['created'] = date('Y-m-d H:i:s');
                $subject_enrolls['update_uid'] = '0';
                $subject_enrolls['modified'] = date('Y-m-d H:i:s');
                //debug($subject_enrolls);exit();
   if($this->SubjectEnrolls->save($subject_enrolls)){
       if (empty($subject_enrolls)) {
                        $this->Session->setFlash(__("ไม่ถูกต้อง"));
                        return false;
                    }
   }
}
}else{
      foreach($this->request->data as $subject_enrolls) {
       //debug($subject_enrolls);exit();
   //$subject_enrolls=$this->SubjectEnrolls->get($SubjectEnrolls[0]['id']);
   $subject_enrolls=$this->SubjectEnrolls->newEntity();
                $subject_enrolls['subject_id'] = '';
                $subject_enrolls['user_id'] = $this->request->data['data']['Users']['id'];
                $subject_enrolls['master_organization_id'] = $this->request->data['data']['UserProfiles']['education']['organize_id'];
                $subject_enrolls['card_code'] = $this->request->data['data']['UserProfiles']['education']['card_code'];
                $subject_enrolls['is_used'] = '1';
                $subject_enrolls['create_uid'] = '0';
                $subject_enrolls['created'] = date('Y-m-d H:i:s');
                $subject_enrolls['update_uid'] = '0';
                $subject_enrolls['modified'] = date('Y-m-d H:i:s');
                //debug($subject_enrolls);exit();
   if($this->SubjectEnrolls->save($subject_enrolls)){
       if (empty($subject_enrolls)) {
                        $this->Session->setFlash(__("ไม่ถูกต้อง"));
                        return false;
                    }
   }
} 
}


          //}
//            $this->Flash->error(__('ไม่สามารถปรับปรุงข้อมูลการศึกษาได้ โปรดติด่อเจ้าหน้าที่'));
//            return $this->redirect(['controller' => 'Profiles', 'action' => 'index']);
                  
        }
	//debug($UserPersonLists);exit();
    $this->Flash->success(__('ปรับปรุงข้อมูลสำเร็จ'));
    return $this->redirect(['controller' => 'Profiles', 'action' => 'index']);
    }    
    
    public function profileCard()
    {
        $this->viewBuilder()->layout('blank');

    }
   
}
