<?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 createCards()
    {
        $this->viewBuilder()->layout('blank');
        $this->loadModel('TempUserCards');
        $this->loadModel('MasterOrganizations');
        if ($this->request->is('post')) {
            // pr($this->Auth);die;
            // pr($this->request->data());
            $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();
            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'] = 1;
                    $userCard['user_id'] = 1;
                    // pr($userCard);die;
                    if ($this->UserCards->save($userCard)) {
                        $this->Flash->success(__('บันทึกสำเร็จ'));
                        return $this->redirect(['controller' => 'Profiles', 'action' => 'index']);
                    }
                }else{
                    $this->Flash->success(__('ลงทะเบียนไว้อยู่แล้ว'));
                    return $this->redirect(['controller' => 'UserCards', 'action' => 'createCards']);
                }
            }else{
                $this->Flash->success(__('ไม่พบข้อมูล'));
                return $this->redirect(['controller' => 'UserCards', 'action' => 'createCards']);
            }
        }
    }
    public function checkOrg()
    {
        $this->autoRender = false;
        //     $this->loadModel('MasterOrganizations');
        // $MasterOrganizations = $this->MasterOrganizations->find('all', [
        //         'fields' => [
        //             'id',
        //             'org_code',
        //             'org_name_th'
        //         ], 'conditions' => [
        //             'org_code' => 'PAGO0010'
        //         ]
        //     ])->toArray();
        // pr($MasterOrganizations);die;
        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' => 2,
                        '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';
            }
        }
    }
}