<?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');
        }
        $this->redirect($this->referer());
    }

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

    public function editBudget($id = null) {
        $this->loadModel('Schools');
        $schools = $this->Schools->find('all');
        $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);
    }

    public function editajax($id = null) {
        $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');

        foreach($data as $line) {                       
            if($line[2] > 0) {
                $query = $this->Budget->find('all', [
                    'conditions' => array('snr' => $line[0], 'wl_budget_id' => $id)
                ]);
                        
                if(!($query->isEmpty())) {
                    $budget = $query->first();
                    if($budget['count'] != $line[2] ) {
                        $budget['count'] = $line[2];
                        $this->Budget->save($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'] = 4; 
                    $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() {
        $this->autoRender = false; 
        $myfile = fopen(WWW_ROOT . DS .  'files' . DS . 'debug.txt', "w");
        $data = $this->request->input('json_decode');

        foreach($data as $line) {           
            for($i=2;$i < sizeof($line);$i++) {
                if($line[$i] > 0) {
                    $query = $this->Budget->find('all', [
                        'conditions' => array('snr' => $line[0], 'wl_budget_id' => $i-1)
                    ]);
                        
                    if(!($query->isEmpty())) {
                        $budget = $query->first();
                        if($budget['count'] != $line[$i] ) {
                            $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'] = 4; 
                        $new_budget['snr'] = $line[0];
                        $new_budget['wl_budget_id'] = $i-1;
                        $new_budget['count'] = $line[$i];
                        $new_budget['comment'] = 'auto';
                        $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 overview() {
        $wlBudgets = $this->Budget->wlBudgets->find('list', [
            'conditions' => array('schulart' => 'GY')
        ]);
        //debug($wlBudgets);
        
        $this->loadModel('Schools');
        $schools = $this->Schools->find('all');
        $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');
        foreach($budgets as $budget) {
            $i = $budget['wl_budget_id']+1;           
            $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);
    }

    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_id','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']);
    }
}
