<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Schools Controller
 *
 * @property \App\Model\Table\SchoolsTable $Schools
 *
 * @method \App\Model\Entity\School[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class SchoolsController extends AppController
{
    public function showajax($snr = null) {
        $session = $this->request->session();
        $schooltype = $session->read('SchoolType');

        $this->autoRender = false; 
        $myfile = fopen(WWW_ROOT . DS .  'files' . DS . 'debug-single.txt', "w");
        $data = $this->request->input('json_decode');
        $this->loadModel('Budget');
        $this->loadModel('wl_Budgets');
        //fwrite($myfile,$schooltype . PHP_EOL);
        fwrite($myfile,$snr . PHP_EOL);

        foreach($data as $line) {      
            fwrite($myfile,json_encode($line) . PHP_EOL);     
            //fwrite($myfile,'Size: ' . strlen($line[0]) . PHP_EOL);
            if(strlen($line[0]) > 0) {
                //fwrite($myfile,'Budget: ' . $line[0] . PHP_EOL);
                $query = $this->wl_Budgets->find('all', [
                    'conditions' => array('wl_kurz_bezeichnung' => $line[0])
                ]);
                $wl_budget = $query->first();
                //fwrite($myfile,json_encode($wl_budget). PHP_EOL);
                $query = $this->Budget->find('all', [
                    'conditions' => array('snr' => $snr, 'wl_budget_id' => $wl_budget['id'])
                ]); 
                //fwrite($myfile,$wl_budget['id'] . PHP_EOL);
                        
                if(!($query->isEmpty())) {
                    $budget = $query->first();
                    //fwrite($myfile,json_encode($budget). PHP_EOL);
                    if($budget['wl_budget_id'] != $wl_budget['id'] ) {
                        $budget['wl_budget_id'] = $wl_budget['id'];
                        $this->Budget->save($budget);
                    }
                    elseif($budget['count'] != $line[1] ) {
                        if($line[1] > 0) {
                            $budget['count'] = $line[1];
                            $this->Budget->save($budget);
                        }
                        else {
                            $this->Budget->delete($budget);
                        }
                    }
                    elseif($budget['comment'] != $line[2] ) {
                        $budget['comment'] = $line[2];
                        $this->Budget->save($budget);
                    }
                    //fwrite($myfile,'full' . PHP_EOL);
                }
                else {
                    //fwrite($myfile,'empty' . PHP_EOL);
                    $new = $this->Budget->newEntity();   
                    $new_budget['wl_schooltype_id'] = $schooltype; 
                    $new_budget['snr'] = $snr;
                    $new_budget['wl_budget_id'] = $wl_budget['id'];
                    $new_budget['count'] = $line[1];
                    $new_budget['comment'] = $line[2];
                    $new_budget['year'] = '2018';
                    //fwrite($myfile,'New: ' . json_encode($new_budget). PHP_EOL);
                    $new = $this->Budget->patchEntity($new, $new_budget);
           
                    $this->Budget->save($new);
                } 
                //fwrite($myfile,serialize($budget). PHP_EOL); 
                    //fwrite($myfile,$line[0] . ' ' .($i+$wl_offset) . ' ' . $line[$i]. PHP_EOL);
            }           
        } 
        fclose($myfile);
    }


    public function showbudgets($snr = null) {
        $session = $this->request->session();
        //debug($session->read('SchoolType'));die;
        $schooltype = $session->read('SchoolType');
        if ($schooltype == '02') {
            $schulart = 'RS';
        }
        else {
            $schulart = 'GY';
        }
        
        $query = $this->Schools->find('all', [
            'conditions' => array('dst_schluessel' => $snr)
        ]);
        $school = $query->first();
        $this->loadModel('Budget');
        $budgets = $this->Budget->find('all', [
            'conditions' => ['snr' => $snr]
        ]);
        $this->loadModel('wl_Budgets');
        $data = array();
        foreach($budgets as $budget) {
            $line = array();
            //debug($budget);
            $wl_budget = $this->wl_Budgets->get($budget['wl_budget_id']);
            //debug($wl_budget);
            array_push($line,$wl_budget['wl_kurz_bezeichnung']);
            array_push($line,$budget['count']);
            array_push($line,$budget['comment']);
            array_push($data,$line);
        }
        for($i=0;$i<5;$i++) {
            $line = array();
            array_push($line,'');
            array_push($line,'');
            array_push($line,'');
            array_push($data,$line);           
        }
        $query = $this->wl_Budgets->find('list', [
            'conditions' => array('schulart' => $schulart),
            'valueField' => 'wl_kurz_bezeichnung'
        ]);
        $wl_budgets = $query->toArray();
        $budgets_arr = array();
        foreach ($wl_budgets as $wl_budget) {
            array_push($budgets_arr,$wl_budget);
        }
        //debug(json_encode($budgets_arr));die;
        $this->set('budgets_arr',$budgets_arr);
        $this->set('school',$school);
        $this->set('data',$data);

    }

    public function show() {
        $results = $this->Schools->find('all');

        //$results = $query->all();
        //debug($results);
        $this->set('results',$results);
    }

    /**
     * Index method
     *
     * @return \Cake\Http\Response|void
     */
    public function index()
    {
        $schools = $this->paginate($this->Schools);

        $this->set(compact('schools'));
    }

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

        $this->set('school', $school);
    }

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

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

    /**
     * Edit method
     *
     * @param string|null $id School 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)
    {
        $school = $this->Schools->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $school = $this->Schools->patchEntity($school, $this->request->getData());
            if ($this->Schools->save($school)) {
                $this->Flash->success(__('The school has been saved.'));

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

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

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