<?php
namespace App\Controller;

use App\Controller\AppController;
use AsdCurl\AsdUp;

/**
 * Budget Controller
 *
 * @property \App\Model\Table\BudgetTable $Budget
 *
 * @method \App\Model\Entity\Budget[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class BudgetController extends AppController
{
    public function changeSchool()
    {
        $session = $this->request->session();
        if ($session->read('SchoolType') == '02') {
            $session->write('SchoolType','04');
        }
        else {
            $session->write('SchoolType','02');
        }
        /* debug($this->Cookie->read('schooltype'));
        if($this->Cookie->read('schooltype') == '2') {
            debug('Gymnasium');
            //$this->Cookie->delete('schooltype');
            $this->Cookie->write('schooltype', '4');
            debug($this->Cookie->read('schooltype'));
        }
        else {
            debug('Realschule');
            //$this->Cookie->delete('schooltype');
            $this->Cookie->write('schooltype', '2');
            debug($this->Cookie->read('schooltype'));
        }
        */
        //die;
        $this->redirect($this->referer());
    }

    public function listBudgets() {

        $session = $this->request->session();
        //debug($session->read('SchoolType'));die;
        $schooltype = $session->read('SchoolType');
        if ($schooltype == '02') {
            $schulart = 'RS';
        }
        else {
            $schulart = 'GY';

        }
        
        $wlBudgets = $this->Budget->wlBudgets->find('all', [
            'conditions' => array('schulart' => $schulart)
        ]);
        $this->set('wlBudgets',$wlBudgets);  
    }

    public function editBudget($id = null) {
        $session = $this->request->session();
        //debug($session->read('SchoolType'));die;
        $schooltype = $session->read('SchoolType');
        
        $this->loadModel('Schools');
        $schools = $this->Schools->find('all', [
            'conditions' => array('dst_schulart' => $schooltype)
        ]);
        $data = array();
        foreach($schools as $school) {
            $line = array();
            array_push($line,$school['dst_schluessel']);
            array_push($line,$school['dst_name']);
            array_push($line,'','');
            $data[$school['dst_schluessel']] = $line;
        }
        
        $budgets = $this->Budget->find('all', [
            'conditions' => array('wl_budget_id' => $id)
        ]);

        foreach($budgets as $budget) {           
            $data[$budget['snr']][2] = $budget['count'];
            $data[$budget['snr']][3] = $budget['comment'];
        }
        $data_arr = array();
        foreach($data as $entry) {
            array_push($data_arr,$entry);
        }
        $budget = $this->Budget->wlBudgets->get($id);
        $this->set('budget',$budget);
        $this->set('data',$data_arr);
        $this->set('schooltype',$schooltype);
    }

    public function editajax() {
        $this->autoRender = false; 
        $myfile = fopen(WWW_ROOT . DS .  'files' . DS . 'debug-edit.txt', "w");
        //fwrite($myfile,$id . PHP_EOL);
        $data = $this->request->input('json_decode');
        $params = $this->request->params;
        debug($params['?']);
        fwrite($myfile,json_encode($params['?']['budget']) . PHP_EOL);
        fwrite($myfile,json_encode($params['?']['schooltype']) . PHP_EOL);
        $id = $params['?']['budget'];
        $schooltype = $params['?']['schooltype'];
        if($schooltype = '02') {
            $schooltype_nr = '2';
        }
        else {
            $schooltype_nr = '4';
        }

        foreach($data as $line) {                       
            
            //fwrite($myfile,json_encode($line[0]) . PHP_EOL);
            //$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
            //preg_match_all("/$regexp/siU", $line[0], $matches);
            //fwrite($myfile,json_encode($line) . PHP_EOL);
            $query = $this->Budget->find('all', [
                'conditions' => array('snr' => $line[0], 'wl_budget_id' => $id)
            ]);
                        
            if(!($query->isEmpty())) {
                $budget = $query->first();
                fwrite($myfile,json_encode($budget) . PHP_EOL);
                if($budget['count'] != $line[2] ) {
                    if($line[2] > 0) {
                        $budget['count'] = $line[2];
                        $this->Budget->save($budget);
                    }
                    else {
                        $this->Budget->delete($budget);
                    }
                    fwrite($myfile,'full-count' . PHP_EOL);
                }                       
                if($budget['comment'] != $line[3] ) {
                     $budget['comment'] = $line[3];
                    $this->Budget->save($budget);
                    fwrite($myfile,'full-comment' . PHP_EOL);
                }                        
            }
            else {
                fwrite($myfile,'empty' . PHP_EOL);
                $new = $this->Budget->newEntity();   
                $new_budget['wl_schooltype_id'] = $schooltype_nr; 
                $new_budget['snr'] = $line[0];
                $new_budget['wl_budget_id'] = $id;
                $new_budget['count'] = $line[2];
                $new_budget['comment'] = $line[3];
                $new_budget['year'] = '2018';
                $new = $this->Budget->patchEntity($new, $new_budget);           
                $this->Budget->save($new);
            } 
            //fwrite($myfile,serialize($budget). PHP_EOL); 
            //fwrite($myfile,$line[0] . ' ' .($i-1) . ' ' . $line[$i]. PHP_EOL);
                      
        } 
        fclose($myfile);
    }

    public function sajax($schooltype = null) {

        //$session = $this->request->session();
        //debug($session->read('SchoolType'));die;
        //$schooltype = $session->read('SchoolType');
        if ($schooltype == '02') {
            $wl_offset = 31;
            $schooltype_id = '2';
        }
        else {
            $schooltype_id = '4';
            $wl_offset = -1;
        }

        $this->autoRender = false; 
        $myfile = fopen(WWW_ROOT . DS .  'files' . DS . 'debug.txt', "w");

        $query = $this->Budget->find('all', [
            'conditions' => array('wl_schooltype_id' => $schooltype_id)
        ]);
        $count = $query->count();
        fwrite($myfile,json_encode($count) . PHP_EOL);
        $dbdata = $query->toArray();
        $search_arr = array();
        foreach($dbdata as $entry) {
            $key = $entry['snr'] . '_' . $entry['wl_budget_id'];
            fwrite($myfile,json_encode($key) . PHP_EOL);
            $search_arr[$key]['count'] = $entry['count'];
            //$search_arr[$key]['comment'] = $entry['comment'];
            fwrite($myfile,json_encode($search_arr[$key]) . PHP_EOL);
        }
        

        $data = $this->request->input('json_decode');
        //fwrite($myfile,json_encode($dbdata) . PHP_EOL);
        //fwrite($myfile,'hallo' . PHP_EOL);
        // neue und geänderte Daten eintragen
        foreach($data as $line) {           
            for($i=2;$i < sizeof($line);$i++) {
                if($line[$i] > 0) {
                    $key = $line[0] . '_' . ($i+$wl_offset);
                    fwrite($myfile,json_encode($key) . PHP_EOL);
                    if(isset($search_arr[$key])) {
                        if($search_arr[$key]['count'] != $line[$i] ) {
                            $query = $this->Budget->find('all', [
                                'conditions' => array('snr' => $line[0], 'wl_budget_id' => $i+$wl_offset)
                            ]);
                            $budget = $query->first();
                            $budget['count'] = $line[$i];
                            $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_id; 
                        $new_budget['snr'] = $line[0];
                        $new_budget['wl_budget_id'] = $i+$wl_offset;
                        $new_budget['count'] = $line[$i];
                        $new_budget['comment'] = 'auto';
                        $new_budget['year'] = '2018';

                        $new = $this->Budget->patchEntity($new, $new_budget);          
                        $this->Budget->save($new);
                    }
                }
            }
        }

        // wurde etwas gelöscht?
        
        foreach($dbdata as $entry) {
            fwrite($myfile,json_encode($entry) . PHP_EOL);
            fwrite($myfile,$entry->snr . PHP_EOL);
            $value = array_search($entry->snr,array_column($data,0));

            fwrite($myfile,json_encode($value). PHP_EOL);
            fwrite($myfile,json_encode($data[$value]). PHP_EOL);
            fwrite($myfile,json_encode($data[$value][$entry->wl_budget_id - $wl_offset]). PHP_EOL);
            if($data[$value][$entry->wl_budget_id - $wl_offset] > 0) {
                fwrite($myfile,'passt' . PHP_EOL);
            }
            else {
                fwrite($myfile,'loeschen' . PHP_EOL);
                //$budget = $this->Budget->get($id);
                $this->Budget->delete($entry);
            }
        }
        

        fclose($myfile);
    }

    public function overview() {

        //debug($this->Cookie->read('schooltype'));
        //debug($this->request);
        //$cookie = $this->response->getCookie('schooltype');
        //debug($cookie['value']);
        //$schooltype = $cookie['value'];
        //die;

        $session = $this->request->session();
        //debug($session->read('SchoolType'));die;
        $schooltype = $session->read('SchoolType');
        /** 
        $cookie_value = $this->Cookie->read('schooltype');
        if($cookie_value == 2) {
            $schooltype = '02';
        }
        else {
            $schooltype = '04';
        } */
        if ($schooltype == '02') {
            $schulart = 'RS';
            $offset = -31;
        }
        else {
            $schulart = 'GY';
            $offset = 1;
        }

        $wlBudgets = $this->Budget->wlBudgets->find('all', [
            'conditions' => array('schulart' => $schulart)
        ]);
        //debug($wlBudgets);die;
        
        $this->loadModel('Schools');
        $schools = $this->Schools->find('all', [
            'conditions' => array('dst_schulart' => $schooltype)
        ]);
        $data = array();
        foreach($schools as $school) {
            $line = array();
            array_push($line,$school['dst_schluessel']);
            array_push($line,$school['dst_name']);
            foreach($wlBudgets as $wlbudget) {
                array_push($line,'');
                //debug($budget);
            }
            $data[$school['dst_schluessel']] = $line;
        }
        
        $budgets = $this->Budget->find('all', [
            'contain' => ['WlSchooltypes'],
            'conditions' => array('WlSchooltypes.key_value' => $schooltype)          
        ]);
        foreach($budgets as $budget) {
            $i = $budget['wl_budget_id']+$offset;           
            $data[$budget['snr']][$i] = $budget['count'];
        }
        $data_arr = array();
        foreach($data as $entry) {
            array_push($data_arr,$entry);
        }

        $this->set('data',$data_arr);
        $this->set('wlBudgets',$wlBudgets);
        $this->set('schooltype',$schooltype);
    }

    public function gettype($id = null) {
        $budget = $this->Budget->newEntity();
        if ($this->request->is('post')) {
            //debug($this->request);
            $r = $this->request;
            debug($r->params);
            $wl_id = $r->params['pass']['0'];
            //debug($wl_id);die;
            $wlBudget = $this->Budget->WlBudgets->get($wl_id);
            debug($wlBudget);
            debug($r->data);
            die;
        }
        
        $budgettype = $this->Budget->WlBudgets->get($id);
        //debug($budgettype);
        $this->loadModel('Schools');
        $schools = $this->Schools->find('all');
        //debug($schools);
        $this->set('budget',$budget);
        $this->set('schools',$schools);
    }

    public function importCsv() {
        $uploadData = '';
        if ($this->request->is('post')) {
            if(!empty($this->request->data['file']['name'])){
                $fileName = $this->request->data['file']['name'];
                $uploadPath = 'uploads/';
                $uploadFile = $uploadPath.$fileName;
                if(move_uploaded_file($this->request->data['file']['tmp_name'],$uploadFile)){
                    $this->Flash->success(__('The File has been uploaded.'));
                    return $this->redirect(['action' => 'displayCsv', $fileName]);
                } else {
                    $this->Flash->error(__('Unable to upload file, please try again.'));
                }
            } else {
                $this->Flash->error(__('Please choose a file to upload.'));
            }
        }
        $this->set('uploadData', $uploadData);              
    }

    public function displayCsv($filename) {
        //debug($filename);die;
        $uploadPath = 'uploads/';
        $handle = fopen($uploadPath.$filename, "r");
        $head = true;
        $content_arr = array();
        if ($handle) {
            while (($line = fgets($handle)) !== false) {
                if(strlen($line) > 2) {
                    if($head) {
                        $headers = explode(';',$line);
                        $head = false;
                    }
                    else {
                        array_push($content_arr,explode(';',$line));
                    }
                }
            }
            fclose($handle);
        } else {
        // error opening the file.
        }  
        $this->set('headers',$headers);
        $this->set('content_arr',$content_arr);
    }

    public function exportCsv() {
        $this->response->download('export.csv');

        $exports = $this->Budget->find('all', [
            'contain' => ['WlBudgets'],
            'fields' => ['Budget.snr','WlBudgets.wl_werteliste_nr','WlBudgets.wl_kurz_bezeichnung','Budget.count','Budget.comment']
        ]);
        $data = array();
        foreach($exports as $export) {
            $line['snr'] = $export->snr;
            $line['werteliste_id'] = $export->wl_budget->wl_werteliste_id;
            $line['bezeichnung'] = $export->wl_budget->wl_kurz_bezeichnung;
            $line['count'] = $export->count;
            $line['comment'] = $export->comment;
            array_push($data,$line); 
            //debug(json_decode(json_encode($export)));
        }
        //debug($data);die;
        $_serialize = 'data';
        $_header = ['Schulnummer', 'Werteliste ID', 'Bezeichnung', 'Count', 'Comment'];
        $_delimiter = ';';
        $this->set(compact('data', '_serialize', '_header', '_delimiter'));
        $this->viewBuilder()->className('CsvView.Csv');

    }

    public function writeAsd()
    {
        $curl = new AsdUp();
        //debug($curl->status);
        $ch = $curl->init_curl_params();
        //$curl->login_school($ch); //Login Schulportal
        $curl->login_asd($ch);
        //debug($curl->html);
        
        $budget['snr'] = '9310';
        $budget['budget_id'] = '1519';
        $budget['count'] = '5';
        $budget['comment'] = 'Schüler Hans Mustermann';
        $curl->goto_budget($ch,$budget);
        $curl->write_budget($ch,$budget);
        $snr = '0181';
        $curl->change_school($ch,$snr);
        $this->set('html',$curl->html);
    }

    public function readAsd($snr) {
        //debug($snr);
        $snr = '9310';
        $curl = new AsdUp();
        $ch = $curl->init_curl_params();
        $curl->login_asd($ch);
        $budget['snr'] = $snr;
        $curl->goto_budget($ch,$budget);
        $data  = $curl->read_budget($ch,$snr);
        //debug($data);
        $asd_budget = $this->Budget->find('all',array('conditions' => array('snr' => $snr)));
        
        
        foreach($asd_budget as $entry) {
            $new['herkunft'] = 'ASD';
            //debug($entry);
            $wl_budget =  json_decode(json_encode($this->Budget->WlBudgets->get($entry['wl_budget_id'])));
            //debug($wl_budget);
            $new['budget'] = $wl_budget->wl_kurz_bezeichnung;
            $new['von'] = '01.08.2018';
            $new['bis'] = '31.07.2019';
            $new['count'] = $entry['count'];
            $new['comment'] = $entry['comment'];
            //debug($new);
            
            array_push($data,$new);
        }
        //debug($data);
        //die;

        $budget = $this->Budget->newEntity();
        if ($this->request->is('post')) {
            $budget = $this->Budget->patchEntity($budget, $this->request->getData());
            //debug($budget);
            //debug($this->referer);die;
            if ($this->Budget->save($budget)) {
                $this->Flash->success(__('The budget has been saved.'));

                return $this->redirect(['action' => 'readAsd',$snr]);
            }
            $this->Flash->error(__('The budget could not be saved. Please, try again.'));
        }
        $wlSchooltypes = $this->Budget->WlSchooltypes->find('list', ['limit' => 200]);
        $wlBudgets = $this->Budget->WlBudgets->find('list', ['limit' => 200]);
        $this->set(compact('budget', 'wlSchooltypes', 'wlBudgets'));
        $this->set('data',$data);
        $this->set('snr',$snr);
    }

    public function delAllAsd($snr) {
        $curl = new AsdUp();
        $ch = $curl->init_curl_params();
        $curl->login_asd($ch);
        $budget['snr'] = $snr;
        $curl->goto_budget($ch,$budget);
        $to_del  = $curl->del_all_budget($ch,$snr);   
        $this->set('to_del',$to_del);     
    }

    /**
     * Index method
     *
     * @return \Cake\Http\Response|void
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['WlSchooltypes', 'WlBudgets']
        ];
        $budget = $this->paginate($this->Budget);

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

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

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

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

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The budget could not be saved. Please, try again.'));
        }
        $wlSchooltypes = $this->Budget->WlSchooltypes->find('list', ['limit' => 200]);
        $wlBudgets = $this->Budget->WlBudgets->find('list', ['limit' => 200]);
        $this->set(compact('budget', 'wlSchooltypes', 'wlBudgets'));
    }

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

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The budget could not be saved. Please, try again.'));
        }
        $wlSchooltypes = $this->Budget->WlSchooltypes->find('list', ['limit' => 200]);
        $wlBudgets = $this->Budget->WlBudgets->find('list', ['limit' => 200]);
        $this->set(compact('budget', 'wlSchooltypes', 'wlBudgets'));
    }

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

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