<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * UserCards Controller
 *
 * @property \App\Model\Table\UserCardsTable $UserCards
 *
 * @method \App\Model\Entity\UserCard[] paginate($object = null, array $settings = [])
 */
class UserCardsController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Http\Response|void
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['Users', 'Organizes']
        ];
        $userCards = $this->paginate($this->UserCards);

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

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

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

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

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user card could not be saved. Please, try again.'));
        }
        $users = $this->UserCards->Users->find('list', ['limit' => 200]);
        $organizes = $this->UserCards->Organizes->find('list', ['limit' => 200]);
        $this->set(compact('userCard', 'users', 'organizes'));
        $this->set('_serialize', ['userCard']);
    }

    /**
     * Edit method
     *
     * @param string|null $id User Card id.
     * @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $userCard = $this->UserCards->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $userCard = $this->UserCards->patchEntity($userCard, $this->request->getData());
            if ($this->UserCards->save($userCard)) {
                $this->Flash->success(__('The user card has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user card could not be saved. Please, try again.'));
        }
        $users = $this->UserCards->Users->find('list', ['limit' => 200]);
        $organizes = $this->UserCards->Organizes->find('list', ['limit' => 200]);
        $this->set(compact('userCard', 'users', 'organizes'));
        $this->set('_serialize', ['userCard']);
    }

    /**
     * Delete method
     *
     * @param string|null $id User Card 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']);
        $userCard = $this->UserCards->get($id);
        if ($this->UserCards->delete($userCard)) {
            $this->Flash->success(__('The user card has been deleted.'));
        } else {
            $this->Flash->error(__('The user card could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
    public function checkOrg()
    {
        $this->autoRender = false;
        if($this->request->is('post')) {
            $this->loadModel('MasterOrganizations');
            $MasterOrganizations = $this->MasterOrganizations->find('all', [
                'fields' => [
                    'id',
                    'org_code',
                    'org_name_th'
                ], 'conditions' => [
                    'org_code' => $this->request->data['organize_code']
                ]
            ])->toArray();
            if(!empty($MasterOrganizations)){
                $UserCards = $this->UserCards->find('all', [
                    'fields' => [
                        'id',
                        'user_id',
                        'organize_id'
                    ], 'conditions' => [
                        'user_id' => $this->Auth->user('id'),
                        'organize_id' => $MasterOrganizations[0]['id']
                    ]
                ])->toArray();
                if(empty($UserCards)){
                    $MasterOrganizations['chkuser'] = false;
                    $data = json_encode($MasterOrganizations);
                    echo $data;
                }else{
                    $MasterOrganizations['chkuser'] = true;
                    $data = json_encode($MasterOrganizations);
                    echo $data;
                }
            }else{
                echo 'false';
            }
        }
    }
    public function checkEmp()
    {
        $this->autoRender = false;
        if($this->request->is('post')) {
            // pr($this->request->data);die;
            $this->loadModel('MasterOrganizations');
            $MasterOrganizations = $this->MasterOrganizations->find('all', [
                'fields' => [
                    'id',
                    'org_code',
                    'org_name_th'
                ], 'conditions' => [
                    'org_code' => $this->request->data['organize_code']
                ]
            ])->first();
            // pr($MasterOrganizations);die;
            if(!empty($MasterOrganizations)){
                $this->loadModel('TempUserCards');
                $TempUserCards = $this->TempUserCards->find('all', [
                    'conditions' => [
                        'organize_id' => $MasterOrganizations['id'],
                        'card_code' => $this->request->data['employee_val']
                    ]
                ])->first();
                if(!empty($TempUserCards)){
                    $UserCards = $this->UserCards->find('all', [
                        'fields' => [
                            'id',
                            'user_id',
                            'organize_id'
                        ], 'conditions' => [
                            'user_id' => $this->Auth->user('id'),
                            'organize_id' => $MasterOrganizations['id']
                        ]
                    ])->first();
                    if(empty($UserCards)){
                        $TempUserCards['chkuser'] = false;
                        $data = json_encode($TempUserCards);
                        echo $data;
                    }else{
                        $TempUserCards['chkuser'] = true;
                        $data = json_encode($TempUserCards);
                        echo $data;
                    }
                }else{
                echo 'false';
                }
            }else{
                echo 'false';
            }
        }
    }
    public function viewCard($user_id = null){
        $this->viewBuilder()->layout('blank');
        $user_id = $this->Auth->user('id');
        $this->loadModel('UserCards');
        $UserCards = $this->UserCards->find('all')
         ->select($this->UserCards)
        ->select(
            'morg.org_name_th'
        )
        ->join([             
            'morg' => [
                'table' => 'master.master_organizations',
                'type' => 'INNER',
                'conditions' => [
                    'morg.id = userCards.organize_id'
                ],
            ]
        ])
        ->where([
            'userCards.user_id' => $user_id   
        ])
        ->order(['userCards.id' => 'ASC'])
        ->toArray();

        // pr($UserCards);die;
        $this->set(compact('UserCards'));

        // -----------------------------ในส่วนของการ add-------------------------

        $this->loadModel('TempUserCards');
        $this->loadModel('MasterOrganizations');
        if($this->request->is('post')) {
            // pr($this->request->data());die;
            // pr($this->Auth->user('id'));die;
            $birthdate = explode("/", $this->request->data['UserCards']['birthdate']);
            $birthdate = $birthdate['2'].'-'.$birthdate['1'].'-'.$birthdate['0'];
            $TempUserCards = $this->TempUserCards->find('all', [
                'conditions' => [
                    'organize_id' => $this->request->data['UserCards']['organize_id'],
                    'card_code' => $this->request->data['UserCards']['employee'],
                    'birthdate' => $birthdate
                ]
            ])->first();
            // pr($TempUserCards);die;
            if(!empty($TempUserCards)){
                $UserCards = $this->UserCards->find('all', [
                    'conditions' => [
                        'organize_id' => $TempUserCards['organize_id'],
                        'card_code' => $TempUserCards['card_code']
                    ]
                ])->first();
                // pr($UserCards);die;
                if(empty($UserCards)){
                    $userCard = $this->UserCards->newEntity();
                    $userCard['organize_id'] = $TempUserCards['organize_id'];
                    $userCard['card_code'] = $TempUserCards['card_code'];
                    $userCard['img_path'] = $TempUserCards['img_path'];
                    $userCard['prefix_name_th'] = $TempUserCards['prefix_name_th'];
                    $userCard['firstname_th'] = $TempUserCards['firstname_th'];
                    $userCard['lastname_th'] = $TempUserCards['lastname_th'];
                    $userCard['prefix_name_en'] = $TempUserCards['prefix_name_en'];
                    $userCard['firstname_en'] = $TempUserCards['firstname_en'];
                    $userCard['lastname_en'] = $TempUserCards['lastname_en'];
                    $userCard['department_name'] = $TempUserCards['department_name'];
                    $userCard['section_name'] = $TempUserCards['section_name'];
                    $userCard['position_name'] = $TempUserCards['position_name'];
                    $userCard['gender'] = $TempUserCards['gender'];
                    $userCard['blood_group'] = $TempUserCards['blood_group'];
                    $userCard['birthdate'] = $TempUserCards['birthdate'];
                    $userCard['date_issued'] = $TempUserCards['date_issued'];
                    $userCard['date_expiry'] = $TempUserCards['date_expiry'];
                    $userCard['signature'] = $TempUserCards['signature'];
                    $userCard['is_used'] = $TempUserCards['is_used'];
                    $userCard['created_by'] = $this->Auth->user('id');
                    $userCard['user_id'] = $this->Auth->user('id');
                    // pr($userCard);die;
                    if ($this->UserCards->save($userCard)) {
                        $TempUserCards['is_used'] = 0;
                        $this->TempUserCards->save($TempUserCards);
                        $this->loadModel('UserEntities');
                        $UserEntities = $this->UserEntities->find('all', [
                            'conditions' => [
                                'user_id' => $this->Auth->user('id'),
                                'entity_code' => $TempUserCards['organize_id']
                            ]
                        ])->first();
                        if(empty($UserEntities)){
                            $UserEntities = $this->UserEntities->newEntity();
                            $UserEntities['entity_code'] = $this->request->data['UserCards']['organize_code'];
                            $UserEntities['user_id'] = $this->Auth->user('id');
                            $UserEntities['create_uid'] = $this->Auth->user('id');
                            $UserEntities['update_uid'] = $this->Auth->user('id');
                            $this->UserEntities->save($UserEntities);
                        }


                        $this->Flash->success(__('Save Complete'));
                        return $this->redirect(['controller' => 'Profiles', 'action' => 'index']);
                    }
                }else{
                    $this->Flash->error(__('Already registered'));
                    return $this->redirect(['controller' => 'UserCards', 'action' => 'viewCard']);
                }
            }else{
                $this->Flash->error(__('Data not found'));
                return $this->redirect(['controller' => 'UserCards', 'action' => 'viewCard']);
            }
        }
    }
}