<?php
namespace App\Controller;

use App\Controller\AppController;
use ZipArchive;

/**
 * Usfails Controller
 *
 * @property \App\Model\Table\UsfailsTable $Usfails
 *
 * @method \App\Model\Entity\Usfail[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class UsfailsController extends AppController
{
    public function ftp() {
        $ftp_server = "10.190.22.35";
        $ftp_port = "2587";
        $ftp_user = "LfStaD-Log";
        $ftp_pass = "135!Log!086";
        $local_file = '/test/test.zip';
        $zip_pass = '!US-US-2018!';
        $local_folder = '/test';

        $conn_id = ftp_connect($ftp_server, $ftp_port) or die("Couldn't connect to $ftp_server");

        if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
            echo "Angemeldet als $ftp_user@$ftp_server\n";
        } else {
            echo "Anmeldung als $ftp_user nicht möglich\n";
        }

        ftp_chdir($conn_id, 'ap-csv');
        $contents = ftp_nlist($conn_id, ".");
        //debug($contents);
        $abschluss = array_search('US_2018.zip',$contents);
        //debug($abschluss);
        //die;
        ftp_get($conn_id, $local_file, $contents[$abschluss], FTP_BINARY);

        $zip = new ZipArchive();
        $zip_status = $zip->open($local_file);
        
        if ($zip_status === true) {
            if ($zip->setPassword($zip_pass)) {
                if (!$zip->extractTo('/test/results/'))
                    echo "Extraction failed (wrong password?)";
            }
            //debug($zip->statIndex(0));
            $file = $zip->statIndex(0)['name'];
            //debug($file);
            //debug($file);
            $zip->close();
        }
        else {
            die("Failed opening archive: " . @$zip->getStatusString() . " (code: " . $zip_status . ")");
        }
        //echo '/bin/sed -i -E "s/[0-9]{4}[A-Z0-9]{4}[0-9]{17}/XXXXXXXX/g" /test/results/' . $file;
        //die;
        exec('/bin/sed -i -E "s/[0-9]{4}[A-Z0-9]{4}[0-9]{17}/XXXXXXXX/g" /test/results/' . $file);
        rename('/test/results/'.$file,'/var/www/html/asd-control/webroot/files/us/results.csv');
      
        ftp_close($conn_id);
        return $this->redirect(['controller' => 'Usfails', 'action' => 'import']);
    }

        public function import() {

            $sqls = $this->Usfails->schema()->truncateSql($this->Usfails->connection());
                foreach ($sqls as $sql) {
                    $this->Usfails->connection()->execute($sql)->execute();
                }
            $options = [
                'length' => 0,
                'delimiter' => ';',
                'enclosure' => ' ',
                'escape' => '\\',
                'headers' => false,
                'text' => false,
                'excel_bom' => false,
            ];
        
            
            $filepath = '/var/www/html/asd-control/webroot/files/us/results.csv';
            $handle = fopen($filepath, "r");
            $i = 1;
            //$header = fgetcsv($handle, $options['length'], $options['delimiter']);
            while ($row = fgetcsv($handle, $options['length'], $options['delimiter'])) {
                //debug($row);
                $data = (object) [];
                $data->snr                  = trim($row[0]);
                $data->name                 = trim($row[1]);
                $data->status               = trim($row[2]);
                $data->lieferdatum          = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', trim($row[3]))));
                $data->lieferung            = trim($row[4]);                           
                $data->auftrag              = trim($row[5]);
                $data->plausi               = trim($row[6]);
                $data->schluessel           = trim($row[7]);
                $data->sst_objekt           = trim($row[8]);
                $data->fehler_kurz          = trim($row[9]);
                $data->fehler_lang          = trim($row[10]);
                $data->korrekturhinweis     = trim($row[11]);
                $data->ref_feld             = trim($row[12]);

                $line = $this->Usfails->newEntity();                           
                $line = $this->Usfails->patchEntity($line, (array) $data);                       
                $fault = $result = $this->Usfails->save($line);
                //debug($fault);
                //die;
                //debug($i++);
            }
            //die;
            return $this->redirect(['action' => 'show']);
    
        }

        public function show() {
            $results = $this->Usfails->find('all',array('conditions' => array('plausi != 1')));
            //debug($results);
            $this->set('results',$results);
            $this->viewBuilder()->setLayout('usfails');
        }

        public function showdetails($snr) {
            //debug($snr);
            $details = $this->Usfails->find('all',array('conditions' => array('and' => array('snr' => $snr, 'plausi = 1' ))));
            $this->set('details',$details);
            $this->viewBuilder()->setLayout('usfails');
        }

    

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

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

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

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

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

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

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

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

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

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