<?php

App::uses('ApiController', 'Controller');
App::uses('Api', 'Model');

include_once 'AjaxTrait.php';

class KartypracyController extends ApiController
{

	use AjaxTrait;

	public function daj_karty_pracy($tab = null)
	{
		$this->view = 'tabs';

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

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

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

	}

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

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

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

	public function lista_pracownikow()
	{

		$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->query('okresOd');
		$do = $this->request->query('okresDo');
		$nrewid = $this->request->query('nrewid') ?: -1;


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

	private function lista($nrewid = null, $od = null, $do = null)
	{
		$this->view = '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'));
	}


}
