<?php

namespace App\Controller;

use Cake\Core\Configure;
use App\Controller\AppController;
use Cake\Http\Client;

/**
 * UserProfiles Controller
 *
 * @property \App\Model\Table\UserProfilesTable $UserProfiles
 *
 * @method \App\Model\Entity\UserProfile[] paginate($object = null, array $settings = [])
 */
class UserProfilesController extends AppController {

    public function initialize() {
        parent::initialize();
        $this->viewBuilder()->layout('blank');
    }

    /**
     * Index method
     *
     * @return \Cake\Http\Response|void
     */
    public function index($id = 1) {
//        $this->viewBuilder()->layout('blank');
        $userProfile = $this->UserProfiles->get($id, [
            'contain' => []
        ]);

        $this->set('userProfile', $userProfile);
        $this->set('_serialize', ['userProfile']);
    }

    /**
     * View method
     *
     * @param string|null $id User Profile id.
     * @return \Cake\Http\Response|void
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null) {
        $userProfile = $this->UserProfiles->get($id, [
            'contain' => []
        ]);

        $this->set('userProfile', $userProfile);
        $this->set('_serialize', ['userProfile']);
    }

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
     */
    public function add() {
        $userProfile = $this->UserProfiles->newEntity();
        if ($this->request->is('post')) {
            $userProfile = $this->UserProfiles->patchEntity($userProfile, $this->request->getData());
            if ($this->UserProfiles->save($userProfile)) {
                $this->Flash->success(__('The user profile has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user profile could not be saved. Please, try again.'));
        }
        $this->set(compact('userProfile'));
        $this->set('_serialize', ['userProfile']);
    }

    /**
     * Edit method
     *
     * @param string|null $id User Profile id.
     * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function profileSetting($id = 13112) {
        $this->loadModel('Users');
        $http = new Client();
        $data = [];
        $options = ['headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
//                'Authorization' => $this->request->getHeaderLine('Authorization')
               // 'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InRlc3QiLCJwYXNzd29yZCI6InRlc3QiLCJpcCI6IjExMC43Ny4xODIuNzkifQ.xqi1iam460V-DOXJ2wxVJsAccsh4V7iLL_1slLxy99A'
               'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1OTI4NywidXNlcm5hbWUiOiJOYW5hMiIsImlwIjoiOjoxIiwidG9waWMiOiJOYW5hMmI5OTQxMWE2NDExYTRhOTlhZmI5MWRhMjM3MTJjNDQ2In0.u3OdN5QzI_dvI9KfKYojjVXfcnvTcmHz9LM0XHXvwU8'
            ]
        ];
        $tmpResponseUserProfile = json_decode($http->post('http://connect06.pakgon.com/api/Profiles', $data, $options)->body(), '_full');
        $responseUserProfile = $tmpResponseUserProfile['result']['Data'];
        unset($tmpResponseUserProfile);
        //pr($responseUserProfile);
//        $userProfiles = $this->UserProfiles->get($responseUserProfile['UserProfiles']['id'], ['contain' => ['MasterOrganizations', 'MasterDepartments']]);
//        debug($responseUserProfile);
//        exit;
//        $organiId = [];
//        foreach ($userProfiles['user_profiles'] as $k => $userProfile) {
//            $organiId = $userProfile->organize_id;
////            debug($userProfiles);
//        }
//        exit;
        // $data = $this->request->data;
        // $UserPersonal = $this->UserProfiles->UserPersonals->find('first', [
        //     'conditions' => [
        //         'UserPersonals.user_id' => $data['Users']['user_id']
        //     ]
        // ]);

        // pr($UserPersonal);die;
        if ($this->request->is(['patch', 'post', 'put'])) {
            $data = $this->request->data;
//            debug($this->request->data);
//            exit;
            // pr($data);
            
            $this->loadModel('UserPersonals');
            
            $userPersonals = $this->UserPersonals->find('all',
                [      
                    'limit' => 1,
                    'conditions' => [
                        'user_id' => $data['Users']['user_id']
                    ]
                ]
            )->toArray();
            // pr($userPersonals);
            // pr($data['UserPersonals']);
           // $userPersonals = $this->UserPersonals->newEntity();
            $userPersonals = $this->UserPersonals->patchEntity($userPersonals[0], $data['UserPersonals']);#prr($userPersonals);
            
            list($userPersonals['firstname_th'], $userPersonals['lastname_th']) = explode(' ', $data['UserPersonals']['fullname']);
            unset($userPersonals['fullname']);
            $userPersonals['birthdate'] = '2000-01-01';
            $userPersonals['user_id'] = $data['Users']['user_id'];
            $userPersonals['modified_by'] = '';
          //  $userPersonals['modified'] = '2018-01-01 00:00:00';
            
          //   pr($userPersonals->toArray());die;
           // debug($this->UserPersonals->save($userPersonals));die;
            if ($this->UserPersonals->save($userPersonals)) {
                //pr($userPersonals->toArray());die;
            }
            // $data['UserProfiles'][0]['user_id'] = $data['Users']['user_id'];
            // $data['UserProfiles'][0]['user_type_id'] = 1;
            // $data['UserProfiles'][0]['modified_by'] = '';
            // $data['UserProfiles'][1]['user_id'] = $data['Users']['user_id'];
            // $data['UserProfiles'][1]['user_type_id'] = 2;
            // $data['UserProfiles'][1]['modified_by'] = '';
            // debug($data);
            // exit;
            #$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.eyJ1c2VyX2lkIjo1OTIzMCwidXNlcm5hbWUiOiJ0ZXN0dG9uZyIsImlwIjoiMTI3LjAuMC4xIn0.37hXRDEhiwjsgqR8mcgbhxnKtAof3tIDahL2P6DnQ4I'
//                     'Authorization' => 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1OTI4NywidXNlcm5hbWUiOiJOYW5hMiIsImlwIjoiOjoxIiwidG9waWMiOiJOYW5hMmI5OTQxMWE2NDExYTRhOTlhZmI5MWRhMjM3MTJjNDQ2In0.u3OdN5QzI_dvI9KfKYojjVXfcnvTcmHz9LM0XHXvwU8'
//                 ]
//             ];
//             prr($options);
//             $response = $http->post($api_update_profile, $data, $options)->body();
//             pr($response);
//             $response = json_decode($response, '_full');
            // pr($response);
            // die;
        }

//         $organization = $this->UserProfiles->MasterOrganizations->find('list')->select(['MasterOrganizations.id', 'MasterOrganizations.org_name_th'])->where(['master_organization_type_id' => 1]);
//         $organizations = ['' => __(' --- Please Select --- ')] + $organization->toArray();
// //
//         $company = $this->UserProfiles->MasterOrganizations->find('list')->select(['MasterOrganizations.id', 'MasterOrganizations.org_name_th'])->where(['master_organization_type_id' => 2]);
//         $companys = ['' => __(' --- Please Select --- ')] + $company->toArray();
// //
//         $this->loadModel('MasterOrganizationPositions');
//         $companyPosition = $this->MasterOrganizationPositions->find('list')->select(['MasterOrganizationPositions.id', 'MasterOrganizationPositions.organization_position_name'])->where(['MasterOrganizationPositions.master_organization_id' => $responseUserProfile['UserProfiles']['organize_id']]);
//         $companyPositions = ['' => __(' --- Please Select --- ')] + $companyPosition->toArray();

//         $department = $this->UserProfiles->MasterDepartments->find('list')->select(['MasterDepartments.id', 'MasterDepartments.dept_name_th'])->where(['MasterDepartments.master_organization_id' => $responseUserProfile['UserProfiles']['organize_id']]);
//         $departments = ['' => __(' --- Please Select --- ')] + $department->toArray();
//         $section = $this->UserProfiles->MasterSections->find('list')->select(['MasterSections.id', 'MasterSections.section_name_th'])->where(['MasterSections.master_department_id' => $responseUserProfile['UserProfiles']['dept_id']]);
//         $sections = ['' => __(' --- Please Select --- ')] + $section->toArray();
//        $departMents = $departMent->toArray();
//        $secTions = $secTion->toArray();
//        debug($organizations);
//
//        debug($companyDepartments);
//        debug($companyPositions);
//        exit;
        $this->set(compact('userProfiles', 'responseUserProfile', 'organizations', 'companys', 'companyPositions', 'departments', 'sections'));
        $this->set('_serialize', ['userProfiles', 'responseUserProfile', 'organizations', 'companys', 'companyPositions', 'departments', 'section']);
    }

    /**
     * Delete method
     *
     * @param string|null $id User Profile id.
     * @return \Cake\Http\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null) {
        $this->request->allowMethod(['post', 'delete']);
        $userProfile = $this->UserProfiles->get($id);
        if ($this->UserProfiles->delete($userProfile)) {
            $this->Flash->success(__('The user profile has been deleted.'));
        } else {
            $this->Flash->error(__('The user profile could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }

    public function getDepartment($id = null) {
//        $this->autoRender = false;
//        $this->viewBuilder()->layout('ajax');
        $this->loadModel('MasterDepartments');
        $department = $this->MasterDepartments->find('all')->select(['MasterDepartments.id', 'MasterDepartments.dept_name_th'])->where(['master_organization_id' => $id]);
        $departments = $department->toArray();
        $this->set(array('departments' => $departments, '_serialize' => array('departments')));
    }

    public function getSection($id = null) {
        $this->loadModel('MasterSections');
        $section = $this->MasterSections->find('all')->select(['MasterSections.id', 'MasterSections.section_name_th'])->where(['master_department_id' => $id]);
        $sections = $section->toArray();
        $this->set(array('sections' => $sections, '_serialize' => array('sections')));
    }

    public function getCompanyDepartment($id = null) {
        $this->loadModel('MasterDepartments');
        $companyDept = $this->MasterDepartments->find('all')->select(['MasterDepartments.id', 'MasterDepartments.dept_name_th'])->where(['master_organization_id' => $id]);
        $companyDepts = $companyDept->toArray();
        $this->set(array('companyDepts' => $companyDepts, '_serialize' => array('companyDepts')));
    }

    public function getCompanySection($id = null) {
        $this->loadModel('MasterSections');
        $companySec = $this->MasterSections->find('all')->select(['MasterSections.id', 'MasterSections.section_name_th'])->where(['master_department_id' => $id]);
        $companySecs = $companySec->toArray();
        $this->set(array('companySecs' => $companySecs, '_serialize' => array('companySecs')));
    }

    public function getCompanyPosition($id = null) {
        $this->loadModel('MasterOrganizationPositions');
        $companyPosition = $this->MasterOrganizationPositions->find('all')->select(['MasterOrganizationPositions.id', 'MasterOrganizationPositions.organization_position_name'])->where(['master_section_id' => $id]);
        $companyPositions = $companyPosition->toArray();
        $this->set(array('companyPositions' => $companyPositions, '_serialize' => array('companyPositions')));
    }

    public function demo() {
        
    }

}
