<?php
namespace App\Controller;

use Cake\Core\App;

App::className('ApiController', 'Controller');
App::className('Api', 'Service');

include_once 'AjaxTrait.php';

class KartypracyController extends ApiController
{

	use AjaxTrait;

	public function dajKartyPracy($tab = null)
	{
		$this->viewBuilder()->setTemplate('tabs');

		if($tab === null) {
			$tab = $this->request->getQuery('tab') ?: 'moje' ;
		}

        $_nrewid = $this->request->getQuery('nrewid') ?: -1;

		$allow_tabs = [
			'moje' => true,
			'pracownikow' => true,
		];

		$this->set(compact('tab', 'allow_tabs', '_nrewid'));

	}

	public function listaMoje()
	{
		$this->set('tab', 'moje');

		$od = $this->request->getQuery('okresOd');
		$do = $this->request->getQuery('okresDo');

		$this->lista(null, $od, $do);
	}

	public function listaPracownikow()
	{

		$resp = $this->Api->DajListePracownikowDoWnioskuRCP($this->_getGid());

		if (isset($resp['bPracownicy']['bPracownik'][0])) {
			$pracownicy = $resp['bPracownicy']['bPracownik'];
		} else if (isset($resp['bPracownicy']['bPracownik'])) {
			$pracownicy = [$resp['bPracownicy']['bPracownik']];
		} else {
			$pracownicy = [];
		}

		$this->set('pracownicy', $pracownicy);

		$this->set('tab', 'pracownikow');


		$od = $this->request->getQuery('okresOd');
		$do = $this->request->getQuery('okresDo');
		$nrewid = $this->request->getQuery('nrewid') ?: -1;


		$this->lista($nrewid, $od, $do);
	}

	private function lista($nrewid = null, $od = null, $do = null)
	{
		$this->viewBuilder()->setTemplate('table');

		if ($od === null) {
			$od = date('Y-m') . '-01';
		}

		if ($do === null) {
			$do = date('Y-m') . '-30';
		}

		$options = [
			'OkresOd' => $od . 'T00:00:00',
			'OkresDo' => $do . 'T23:59:59',
			'Nrewid' => $nrewid
		];

		$resp = $this->Api->DajWierszeKartRCPx($this->_getGid(), $options);

		$rjson = $this->_handle_response_json($resp);

		if (isset($rjson['login']) && !empty($rjson['login'])) {
			echo 'login';
			die();
		}

		$this->set(compact('resp', 'od', 'do', 'nrewid'));
	}


}
