<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

/*
 * Laravel processes routes on a first-come-first-serve basis and therefore
 * you need to place your least specific routes last in the routes file.
 * This means that you need to place your route group above any other
 * routes that have the same path.
 */

// Neuer Login mittels DHTMLX

use Jackiedo\DotenvEditor\Facades\DotenvEditor;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf AS PDF;

use Carbon\Carbon;

use horstoeko\zugferdlaravel\Facades\ZugferdLaravel;
use horstoeko\zugferd\quick\ZugferdQuickDescriptorXRechnung3;
use horstoeko\zugferd\codelists\ZugferdTextSubjectCodeQualifiers;

use FilippoToso\PdfWatermarker\Facades\TextWatermarker;
use FilippoToso\PdfWatermarker\Support\Position;

use Illuminate\Validation\ValidationException;

Route::namespace('Auth')
    ->group(function () {
    
        Route::get('/login', array('uses' => 'LoginController@dhxLoginForm'))->name('login');
        Route::post('/login', array('uses' => 'LoginController@dhxLogin'));

        
        Route::redirect('/', '/login');



        Route::get('/apps', function() {
            return response()->view("storage::Models.Forms.blade.42.42cfb5e5d4ce7eea412524b24e6b7310ec9251eb");
        });
    });

    

if(api()->_service):

    #if('phpxpress' == api()->_service->url AND !\Auth::user()->isRoot()) throw new \Exception('access denied'); 

    Route::middleware(['guest', 'auth'])
        ->prefix(api()->_service->url)
        ->namespace('Auth')
        ->group(function() {

            
            
            Route::get('/apps', function() {
                #return response()->view("storage::Models.Forms.blade.42.42cfb5e5d4ce7eea412524b24e6b7310ec9251eb");
            });

            // Service login page, available for all guests
            //Route::get('/{url}', function () {

                //return view(api()->getForm(api()->service->_login_view->getKey())->getName());
                //Route::get('/', array('uses' => 'LoginController@dhxLoginForm'));

           // })->where(['url' => '/|login']);

            // Post login data to login controller
            // Mehrfachanmeldung ist hier nicht möglich, da die Middleware "guest"
            // mit diesem Vorgang (über LoginController::__construct()) verknüpft ist.
            //Route::post('/login', 'Auth\LoginController@login');

        });

    // Register generic routes for authenticated users
    // Achtung: namespace ist deaktiviert um verschiedene Projekt auf zentrale Controller umzuleiten.

    Route::middleware(['phpxpress.login', 'phpxpress.databases'])
        ->prefix(api()->_service->url)
        ->group(function() {

        
            Route::post('/logout', function() {
                    \Auth::logout();
                    
                    request()->session()->invalidate();
 
                    request()->session()->regenerateToken();
            
            });
            

            Route::get('mkhasone', function() {
            
                            
                return;
        
                $form = \Runtime::make('forms')->findOrFail('0e33971db2811d26687b1ece6fd72f6e04b90fdd');
                
                $bl = \Runtime::make('repository_columns');
                $bl->_repository = "9f2714fe5092f80e1429c8698b8cbb5fb57162e5";
                $bl->_format = NULL;
                $bl->signifier = "_user_at_hwplus_staff";
                $bl->label = "User-Account";
                $bl->storage = 1;
                $bl->computed = 1;
                $bl->form = $form;
                #$bl->save();
                
            
                $form = \Runtime::make('forms')->findOrFail('edaa5baae23de2522ed4a81cbe4314722b3c43ed');
                $con = \Runtime::make('constraints');
                $con->_column = '32ab18c98ddcbb8fd9f664fca32541e06b0ab324';
                $con->_backlink = "8a0fe96f756879ad654aabbba2fc722a36069289";
                $con->_constraint_type = 0;
                $con->multiselect = 0;
                $con->_left_key = "d2bbfe283cdc637d021ae1f6b4242691930d4e93";
                $con->form = $form;
                #$con->save();
            
            
            });
        
            Route::post('reset', function() {

                throw new \Exception('not allowed');
            
                \DB::transaction(function() {
                    
                    if(request('reset_material')) {
                    
                        $materials= \Runtime::make('hwplus_material_master');
                        foreach($materials->get() AS $material) $material->deleteQuietly();
                        foreach(\Runtime::make('meta')->where('_repository', $materials->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();
                    
                        $folders = \Runtime::make('hwplus_material_master_folders');
                        foreach($folders->get() AS $folder) $folder->deleteQuietly();
                        foreach(\Runtime::make('meta')->where('_repository', $folders->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();

                        $root = $folders;
                        $root->descriptor = "Stammdaten";
                        $root->form = \Runtime::make('forms')->findOrFail('e1256850759665749fe0afb29f705c2cea70f7d2');
                        $root->save();
                    }
                    
                    $tickets = \Runtime::make('hwplus_tickets');
                    foreach($tickets->get() AS $ticket) $ticket->deleteQuietly();                
                    foreach(\Runtime::make('meta')->where('_repository', $tickets->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();
                    
                    $materials = \Runtime::make('hwplus_material');
                    foreach($materials->get() AS $material) $material->deleteQuietly();
                    foreach(\Runtime::make('meta')->where('_repository', $materials->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();
                    
                    $manhours = \Runtime::make('hwplus_manhours');
                    foreach($manhours->get() AS $manhour) $manhour->deleteQuietly();
                    foreach(\Runtime::make('meta')->where('_repository', $manhours->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();
                    
                    $invoices = \Runtime::make('hwplus_invoices');
                    foreach($invoices->get() AS $invoice) $invoice->deleteQuietly();
                    foreach(\Runtime::make('meta')->where('_repository', $invoices->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();
                    
                    $items = \Runtime::make('hwplus_invoice_items');
                    foreach($items->get() AS $item) $item->deleteQuietly();
                    foreach(\Runtime::make('meta')->where('_repository', $items->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();
                    
                    $items = \Runtime::make('hwplus_invoice_notes');
                    foreach($items->get() AS $item) $item->deleteQuietly();
                    foreach(\Runtime::make('meta')->where('_repository', $items->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();

                    $events = \Runtime::make('hwplus_events');
                    foreach($events->get() AS $event) $event->deleteQuietly();
                    foreach(\Runtime::make('meta')->where('_repository', $events->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();
                                        
                    if(request('reset_clients')) {
                    
                        $clients = \Runtime::make('hwplus_clients');
                        foreach($clients->get() AS $client) $client->deleteQuietly();
                        foreach(\Runtime::make('meta')->where('_repository', $clients->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();

                        $links = \Runtime::make('hwplus_client_payment_terms_pivot');
                        foreach($links->get() AS $link) $link->deleteQuietly();
                        foreach(\Runtime::make('meta')->where('_repository', $links->getConfig()->getKey())->get() AS $row) $row->deleteQuietly();

                    }
                    
                    \File::deleteDirectory(storage_path('app/Models/Invoices'));
                    \File::deleteDirectory(storage_path('app/Models/Offers'));
                    \File::deleteDirectory(storage_path('app/Models/Tickets'));

                    $settings = DotenvEditor::load(base_path('.env'));
                    $settings->setKey('NEXT_STANDING_ORDER', 1);
                    $settings->save();
                });        

            });
            
                       
            Route::get('mkupdate', function() {


            
                $zip = \Zip::create("update.zip");
            
                $export = [];
                
                // Systemtabellen
                $export[] = "constraints";
                $export[] = "form_elements_pivot";
                $export[] = "forms";
                $export[] = "repository";
                $export[] = "repository_columns";
                $export[] = "services";
                #$export[] = "hwplus_vat_rates";
                $export[] = "hwplus_units";
                
                // Anwendungstabellen
                #$export[] = "hwplus_invoice_notes_patterns";
                
                $ex = [];
            
                foreach($export AS $rep) {
                
                    $rep = \Runtime::make($rep)->getConfig();

                    foreach(\Runtime::make($rep->getKey())->with('_meta')->get() AS $rec) {
                                       
                        if(!$rec->_meta) {
                        
                            throw new \Exception('invalid meta data');
                        
                            echo $rep->signifier . ' --> ' . $rec->getKey() . '--> '. $rec->signifier .'<br>';
                            $meta = new \App\Models\PHPXPress\Meta();
                            $meta->_repository = $rep->getKey();
                            $meta->_row = $rec->getKey();
                            $meta->_user = "f5227ddaa191d7888ad4f4bdc7cdec198daaf706";
                            $meta->_type = 1;
                            $meta->history = NULL;
                            $meta->time = date("Y-m-d H:i:s");
                            $meta->_doctype = "20f8bab2b72652af63b8fddf195f9bb6675cd075";
                            #$meta->save();
                        
                        } else {
                        
                            $ex[$rep->signifier][$rec->getKey()]['data'] = $rec->getAttributes();
                            $ex[$rep->signifier][$rec->getKey()]['meta'] = $rec->_meta->getAttributes();
                        
                        }
                    }
                
                }
                
                $zip->addRaw(serialize($ex), '/tmp/records.txt');
            
                $git = new \CzProject\GitPhp\Git;
                $repo = $git->open(base_path() . '/.git');
                
                try {
                    $repo->run('update-index', '-q', '--refresh');
                    $output = $repo->run('status', '-uall', '--porcelain');
                    
                    if($output->hasErrorOutput()) dd($output->getErrorOutput());

                    if(count($output->getOutput())):
                    
                        
                        $deleted  = "";
                        
                        
                        foreach($output->getOutput() as $line) {
                            $line = trim($line);

                            $file = explode(" ", $line, 2);
                            
                            if(count($file) >= 2){
                                switch($file[0]) {
                                    case "M":
                                        $zip->add(base_path('/' . $file[1]), $file[1]);
                                    break;
                                    case "D":
                                        $deleted = $deleted . $file[1] . "\r\n";
                                    break;
                                    case "??":
                                        if(is_dir(base_path('/' . $file[1]))) echo "dir";
                                        echo file_exists(base_path('/' . $file[1]));
                                        echo $file[1];
                                        echo "<br>";
                                        $zip->add(base_path('/' . $file[1]), $file[1]);
                                    break;
                                    default:
                                        throw new \Exception('have a look');
                                        break;
                                }
                            }
                        }
                        
                        if($deleted) $zip->addRaw($deleted, '/tmp/deleted_files.txt');
                        
                        $path = storage_path('app/updates/' . date("Y") . '/' . date('n'));

                        if(File::isDirectory($path)) {

                            $fi = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS);
                            $path = $path .  "/" . iterator_count($fi) + 1;

                        } else {

                            $path = $path . "/1";
                        }

                        if(!File::exists($path)) {

                            File::makeDirectory($path, 0775, true);
                        }
                        $zip->saveTo($path);

                        d('finished');
                        
                        #$git->commit();
                    
                    endif;

                } catch (\CzProject\GitPhp\GitException $e) {
                    var_dump($e->getRunnerResult()->toText());
}
           
                
            });
            
           
            Route::get('update', function(\Codedge\Updater\UpdaterManager $updater) {


                #if($updater->source()->isNewVersionAvailable()) {

                    // Get the current installed version
                    $current = $updater->source()->getVersionInstalled();

                    // Get the new version available
                    #$versionAvailable = $updater->source()->getVersionAvailable();

                    $releaseCollection = $updater->source()->getSourceRepository()->extractFromHtml($updater->source()->getReleases()->body());

                    $sortedCollection = collect();
                    foreach($releaseCollection AS $key => $release) {
                        $key = str_replace(".", "", $key);
                        $sortedCollection[$key] = $release;
                    }

                    foreach($sortedCollection->sortKeys() AS $release => $entry) {

                        if(version_compare($current, $entry->name, '<')) {

                            $versionAvailable = $entry->name;


                            d($versionAvailable);
                            d('load update');

                            $release = $updater->source()->fetch($versionAvailable);

                            dd($release);

                            $updater->source()->update($release);



                            d('delete old files');

                            if(\File::exists(base_path('tmp/deleted_files.txt'))) {

                                $deleted = \File::get(base_path('tmp/deleted_files.txt'));

                                foreach(explode("\r\n", $deleted) as $line) \File::delete(base_path($line));

                                \File::delete(base_path('tmp/deleted_files.txt'));

                            }



                            $records = unserialize(\File::get(base_path('tmp/records.txt')));

                            \File::delete(base_path('tmp/records.txt'));

                            d('starting db migration udpate');

                            \Artisan::call('migrate');

                            DB::transaction(function () use ($records) {

                                foreach($records AS $rep => $data) {

                                    $rep = \Runtime::make($rep);

                                    $lines = $rep->get();

                                    d('update data: ' . $rep->getConfig()->descriptor);

                                    #d('remove meta data: ' . $rep->getConfig()->descriptor);


                                    $metaRows = \Runtime::make('meta')->where('_repository', $rep->getConfig()->getKey())->get();
                                    foreach($metaRows AS $line) {
                                        try { $line->deleteQuietly(); }
                                        catch(\Exception $e) {
                                            dd($line);
                                        }
                                    }

                                    #d('remove old records for: ' . $rep->getConfig()->descriptor);


                                    foreach($lines AS $line) {
                                        $line->deleteQuietly();
                                    }

                                    #d('write new meta and data: ' . $rep->getConfig()->descriptor);



                                    try {
                                        foreach($data AS $key => $item) {
                                            $row = \Runtime::make($rep->getConfig()->getKey());
                                            $row->setAttributes($item['data']);
                                            $row->saveQuietly();

                                            $meta = \Runtime::make('meta');
                                            $meta->setAttributes($item['meta']);
                                            unset($meta->_editor);
                                            #d($meta);
                                            $meta->saveQuietly();
                                        }
                                    } catch(\Exception $e) {
                                        throw $e;

                                    }

                                }
                            });





                            // Versionsnummer erhöhen ..

                            $settings = DotenvEditor::load(base_path('.env'));
                            $settings->setKey('SELF_UPDATER_VERSION_INSTALLED', $versionAvailable);
                            $settings->save();


                        }



                    }




                #}

            });

            






            /**



            Listings





            **/


            Route::get('new_file_client_select_index', function() {

                $rows = \App\Models\PHPXPress\HwplusClients::with('_meta')->whereHas('_meta', function($query) {

                    $query->where('_doctype', 'c65ddeca3e4ae821f3e47737e9911280b27a2e9b');

                })
                ->orderBy('customer_id', 'asc')
                ->get();

                return response()->json(["total"=>$rows->count(), "rows" => $rows->toArray()]);

            });


            Route::get('ticket_change_client_index', function() {

                $rows = \App\Models\PHPXPress\HwplusClients::with('_meta')->whereHas('_meta', function($query) {

                    $query->where('_doctype', 'c65ddeca3e4ae821f3e47737e9911280b27a2e9b');

                })
                ->orderBy('customer_id', 'asc')
                ->get();

                return response()->json(["total"=>$rows->count(), "rows" => $rows->toArray()]);

            });

            Route::get('hwplus_clients_index', function() {

                $rows = \App\Models\PHPXPress\HwplusClients::with('_client_at_tickets', '_meta._doctype')->whereHas('_meta._doctype', function($query) {
                    $query->where('ID', 'c65ddeca3e4ae821f3e47737e9911280b27a2e9b');
                })->orderBy('customer_id')->get();

                foreach($rows AS $row) {
                    $row['open_tickets'] = $row->_client_at_tickets->whereNull('job_number')->count();
                    $row['closed_tickets'] = $row->_client_at_tickets->whereNotNull('job_number')->count();
                    $row['num_invoices'] = \App\Models\PHPXPress\HwplusInvoices::where('customer_id', $row->customer_id)->where('descriptor', '!=', 'Dauerauftrag')->count();
                }

                return response()->json(["total"=>$rows->count(), "rows" => $rows->toArray()]);

            });

            Route::get('hwplus_invoices_index', function() {


                if(request('search')) {

                    //$page = request('offset') / request('limit');
                    $page = request('page') +1 ;
                    $rows = \App\Models\PHPXPress\HwplusInvoices::search(request('search'))->paginate(10, 'page', $page)->toArray();

                    return response()->json(["total"=>$rows['total'], "totalNotFiltered" =>\App\Models\PHPXPress\HwplusInvoices::count() , "rows" => $rows['data']]);

                }


                $rows = \App\Models\PHPXPress\HwplusInvoices::with('_meta._doctype', '_items')

                    ->whereHas('_meta._doctype', function($query) {
                        $query->whereIn('identifier', ['invoice', 'standing_order','reverse_invoice', 'adjusted_invoice']);
                    })

                    ->select('*', DB::raw('IF(mailed OR printed, 3, IF(invoice_number, 2, 1))  AS status'));

                $total = \App\Models\PHPXPress\HwplusInvoices::whereHas('_meta._doctype', function($query) {
                        $query->whereIn('identifier', ['invoice', 'standing_order','reverse_invoice', 'adjusted_invoice']);
                    })

                    ->select('*', DB::raw('IF(mailed OR printed, 3, IF(invoice_number, 2, 1))  AS status'));
;



                if(request('year') AND request('month')) {

                    $rows = $rows->whereYear('date', request('year'))->whereMonth('date', request('month'));
                    $total = $total->whereYear('date', request('year'))->whereMonth('date', request('month'));


                }

                if(in_array(request('status'), [1,2,3])) {

                    $rows = $rows->having('status', request('status'));
                    $total = $total->having('status', request('status'));

                }

                elseif(in_array(request('status'), [4])) {

                    $rows = $rows->whereNotNull('date_paid');
                    $total = $total->whereNotNull('date_paid');

                }

                elseif(in_array(request('status'), [5])) {

                    $rows = $rows->whereNull('date_paid');
                    $total = $total->whereNull('date_paid');

                }

                $rows = $rows->limit(request('limit'))

                    ->offset(request('offset'))

                    ->orderBy(request('sort') ? : 'date', request('order') ? : "asc")
                    ->get();



                foreach($rows AS $row) {

                    // Rechnungsbetrag

                    $zsum = 0; $fk = 0; $zsumvat = 0; $fkvat = 0; $pos = 0; $vat=[];

                    foreach($row->_items AS $item) {

                        $pos = round((float) str_replace(',', '.', $item->netprice) * (float) str_replace(',', '.', $item->amount), 2);
                        $zsum = $zsum + $pos;
                        $vat[$item->vat][] = $pos;
                    }


                    foreach($vat AS $index => $val) {
                        $zsumvat += $zsum /100 * (float) $index;
                    }

                    $row->gross = number_format($zsum + $zsumvat, 2, ',', '');

                    // Status

                    $row->status = ($row->mailed || $row->printed ? 3 : ($row->job_number ? 2 : 1));


                }


                return response()->json(["total"=>$total->count(), "totalNotFiltered" =>\App\Models\PHPXPress\HwplusInvoices::count() , "rows" => $rows->toArray()]);

            });


            Route::get('hwplus_tickets_closed_index', function() {

                if(request('search')) {

                    $page = (request('offset') / request('limit')) + 1;
                    $rows = \App\Models\PHPXPress\HwplusTickets::search(request('search'))->paginate('10', 'page', $page)->toArray();

                    return response()->json(["total"=>$rows['total'], "totalNotFiltered" =>\App\Models\PHPXPress\HwplusTickets::count() , "rows" => $rows['data']]);

                }

                $rows = \App\Models\PHPXPress\HwplusTickets::with('_client', '_meta._doctype')
                    //->whereHas('_meta._doctype', function($query) { $query->whereNotIn('identifier', ['lot', 'offer', 'material_offer']);  })
                    ->whereHas('_meta._doctype', function($query) { $query->whereIn('identifier', ['order', 'shipping_order']);  })
                    //->whereYear('date', request('year') ? : date('Y'))
                    //->whereMonth('date', request('month') ? : date('m'))
                    ->whereNotNull('job_number');

                $total = $rows->count();

                $rows = $rows->limit(request('limit'))

                    ->offset(request('offset'))

                    ->orderBy(request('sort'), request('order') ? : "asc")
                    ->get();


                // with(_invoice) funktioniert nicht, wir bauen es deshalb hier nach ..
                foreach($rows AS $ticket) $keys[] = $ticket->getKey();
                $invoices = \App\Models\PHPXPress\HwplusInvoices::whereNotNull('_ticket')->whereIn('_ticket', $keys)->get()->keyBy('_ticket.ID');

                foreach($rows AS $ticket) {
                        if(!array_key_exists($ticket->getKey(), $invoices->toArray()));
                        else $ticket->setRelation('_invoice', $invoices[$ticket->getKey()] ? : NULL);
                }
                return response()->json(["total"=>$total, "rows" => $rows->toArray()]);


            });
            
            
            
            /**
            
            
            Dokumente allgemein
            
            
            
            
            **/
            
            
            
            Route::post('createTicket', function() {
            
                $errors = [];
                if(!request('data')['_type']) $errors['data[_type]'] = 'Nicht vorhanden';
                if(!request('data')['_client']) $errors['data[_client_error]'] = 'Nicht vorhanden';
                #if(!request('data')['date']) $errors['data[date]'] = 'Nicht vorhanden';
                
                if($errors) throw ValidationException::withMessages($errors);

            
                switch(request('data')['_type']) {
                    case "RG":
                        $repository = \Runtime::make('hwplus_clients');
                        $model = $repository->find(request('data')['_client']);
                        return api()->getForm('d28b4963e94b6c13de73de367eee276d73039493', compact('model'))->render();
                        break;
                    case "LS":
                        $repository = \Runtime::make('hwplus_clients');
                        $client = $repository->find(request('data')['_client']);
                        $model = new \App\Models\PHPXPress\HwplusTickets;
                        $model->_client = request('data')['_client'];
                        $model->setRelation('_client', $client);
                        $flag_skip_date = false;
                        return api()->getForm('b47ffbb6d10b344b0ad4e1f1bf5526e246b917ce', compact('model', 'flag_skip_date'))->render();
                        break;
                    case "MB":
                        $repository = \Runtime::make('hwplus_clients');
                        $client = $repository->find(request('data')['_client']);
                        $model = new \App\Models\PHPXPress\HwplusTickets;
                        $model->_client = request('data')['_client'];
                        $model->setRelation('_client', $client);
                        $flag_skip_date = false;
                        return api()->getForm('e394996c8ffecef4efa6840e207181ee6bdf85d2', compact('model', 'flag_skip_date'))->render();
                        break;
                    case "AF":
                        $repository = \Runtime::make('hwplus_clients');
                        $client = $repository->find(request('data')['_client']);
                        $model = new \App\Models\PHPXPress\HwplusTickets;
                        $model->_client = request('data')['_client'];
                        $model->setRelation('_client', $client);
                        $flag_skip_date = false;
                        return api()->getForm('b1454e7841ee1d49f594494b0eaa35748029280a', compact('model', 'flag_skip_date'))->render();
                        break;
                    case "AN":
                        $repository = \Runtime::make('hwplus_clients');
                        $client = $repository->find(request('data')['_client']);
                        $model = new \App\Models\PHPXPress\HwplusTickets;
                        $model->_client = request('data')['_client'];
                        $model->setRelation('_client', $client);
                        $flag_skip_date = false;
                        return api()->getForm('d239e7cfd1029e141e34d4a8d724158e9032aced', compact('model', 'flag_skip_date'))->render();
                        break;
                    case "MA":
                        $repository = \Runtime::make('hwplus_clients');
                        $client = $repository->find(request('data')['_client']);
                        $model = new \App\Models\PHPXPress\HwplusTickets;
                        $model->_client = request('data')['_client'];
                        $model->setRelation('_client', $client);
                        $flag_skip_date = false;
                        return api()->getForm('d3bcca67e8f5c508feaff813de03a789feecaec8', compact('model', 'flag_skip_date'))->render();
                        break;
                }
            
            });
            
            
            
            /**
            
            
            Angebot
            
            
            **/
        
            

            
            Route::get('preview_offer/{repository}/{row}', function($repository, $row) {
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);
                
                $data = $model->prepareBladeData();
                $filename = \Blade::render(file_get_contents(storage_path('app/filename-offer.txt')), $data);

                if($model->flag_signed) {

                    $path = storage_path('app/Models/Tickets/'.$model->descriptor.'/'. date('Y'));
                    $path .= '/' . $model->job_number . '.pdf';

                    TextWatermarker::input($path)
                        ->output(storage_path('ticket.tmp.pdf'))
                        ->position(Position::MIDDLE_CENTER)
                        ->asBackground()
                        //->pageRange(1)
                        ->text('Kopie')
                        ->angle(25)
                        ->font(public_path('fonts/Roboto-Regular-webfont.ttf'))
                        ->size('400')
                        ->color('#c5c5c57F') // 7F is the alpha channel (transparency or opacity of color) 0 - 255 in hex
                        ->resolution(300) // 300 dpi
                        ->save();

                        return response()->download(storage_path('ticket.tmp.pdf'), 'Vorschau '.$filename.'.pdf', [], 'inline');
                }


                if(!$model->job_number) $model->job_number = '[' .$model->createJobNumber(). "]";

                $model->header = \Blade::render($model->header, $data);
                $model->footer = \Blade::render($model->footer, $data);

                $pdf = \PDF::loadView('Strommichel.offer', ['model' => $model, 'repository' => $repository], [], [
                    'watermark' => 'Vorschau',
                    'show_watermark'  => true,
                ]);


                $path = storage_path('app/Models/Tickets/preview');
                if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                $path .= "/preview.pdf";
                $pdf->save($path);
                
                
                return response()->download($path, 'Vorschau ' . $filename . '.pdf', [], 'inline');
            });
            
                        
            Route::get('close_offer/{repository}/{row}', function($repository, $row) {

                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);

                if($model->job_number);
                else {
                    #throw new \Exception('Ungültiger Vorgang');
                    $model->job_number = $model->createJobNumber();
                }
                
                $model->flag_signed = 1;
                if(!$model->date) $model->date = date('Y-m-d');

                $data = $model->prepareBladeData();
                $model->header = \Blade::render($model->header, $data);
                $model->footer = \Blade::render($model->footer, $data);
                
                $pdf = \PDF::loadView('Strommichel.offer', ['model' => $model, 'repository' => $repository]);
                $path = storage_path('app/Models/Tickets/'.$model->descriptor.'/'. date('Y'));
                if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                $path .= '/' . $model->job_number . '.pdf';
                $pdf->save($path);
                              
                $model->save();
                return response()->json([0 => $model]);

            });

            Route::post('copy_offer/{row}', function($row) {

                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);

                $new = new \App\Models\PHPXPress\HwplusTickets();

                \DB::transaction(function() use ($model, $new) {

                    $new->descriptor = $model->descriptor;
                    $new->location = $model->location;
                    $new->_client = $model->_client->getKey();
                    $new->date = $model->date;
                    $new->fare = $model->fare;
                    $new->assignment = $model->assignment;
                    $new->commission_number = $model->commission_number . ' (KOPIE)';
                    $new->note = $model->note;
                    $new->print_note = $model->print_note;
                    $new->order_number = $model->order_number;
                    $new->ID = $new->getHashId();
                    $new->form = $model->_meta->_doctype;
                    $new->date_valid_to = $model->date_valid_to;
                    $new->fare_rate_vat = $model->fare_rate_vat;
                    $new->fare_rate = $model->fare_rate;
                    $new->save();

                    foreach($model->_manhours AS $manhour) {

                        $manhour->ID = NULL;
                        $manhour->ROWID = NULL;
                        $manhour->exists = false;
                        $manhour->_manhours_at_tickets = $new->getKey();
                        $manhour->form = \App\Models\PHPXPress\Forms::find("bdf23694c97afce98ac9fbe9788ad82b8bf5719f");
                        $manhour->save();

                    }

                    foreach($model->_material->sortBy('_material_at_tickets_order ') AS $item) {

                        $item->ID = NULL;
                        $item->ROWID = NULL;
                        $item->exists = false;
                        $item->_material_at_tickets = $new->getKey();
                        $item->form = \App\Models\PHPXPress\Forms::find("f7978012a68047ec09fcafe66f8e7fff51be91fa");
                        //dd($item);
                        $item->save();
                    }
                });

                return response()->json($new);
            });

            Route::post('adjust_offer/{row}', function($row) {

                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);

                $new = new \App\Models\PHPXPress\HwplusTickets();

                \DB::transaction(function() use ($model, $new) {

                    $new->descriptor = $model->descriptor;
                    $new->location = $model->location;
                    $new->_client = $model->_client->getKey();
                    $new->date = date('Y-m-d');
                    $new->fare = $model->fare;
                    $new->assignment = $model->assignment;
                    $new->commission_number = $model->commission_number;
                    $new->note = $model->note;
                    $new->title = $model->title;
                    $new->print_note = $model->print_note;
                    $new->order_number = $model->order_number;
                    $new->ID = $new->getHashId();
                    $new->date_valid_to = $model->date_valid_to;
                    $new->fare_rate_vat = $model->fare_rate_vat;
                    $new->fare_rate = $model->fare_rate;
                    $new->form = $model->_meta->_doctype;
                    $new->save();

                    $new->header = "Angebotskorrektur zu unserem Angebot Nr. ".$model->short_name."-".$model->job_number." vom " . (new \Carbon\Carbon($model->date))->format('d.m.Y') . "\r\n" . $new->header;
                    $new->save();

                    $model->_adjusted_offer = $new->getKey();
                    $model->save();

                    foreach($model->_manhours AS $manhour) {

                        $manhour->ID = NULL;
                        $manhour->ROWID = NULL;
                        $manhour->exists = false;
                        $manhour->_manhours_at_tickets = $new->getKey();
                        $manhour->form = \App\Models\PHPXPress\Forms::find("bdf23694c97afce98ac9fbe9788ad82b8bf5719f");
                        $manhour->save();

                    }

                    foreach($model->_material->sortBy('_material_at_tickets_order ') AS $item) {

                        $item->ID = NULL;
                        $item->ROWID = NULL;
                        $item->exists = false;
                        $item->_material_at_tickets = $new->getKey();
                        $item->form = \App\Models\PHPXPress\Forms::find("f7978012a68047ec09fcafe66f8e7fff51be91fa");
                        //dd($item);
                        $item->save();
                    }
                });

                return response()->json($new);
            });
            
            Route::post('offer2ticket/{row}', function($row) {
                
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);
                
                if(!$model->job_number) throw new \Exception('Ungültiger Vorgang');
                if($model->_invoice) throw new \Exception('Ungültiger Vorgang');
                if($model->_offer_at_hwplus_tickets->first()) throw new \Exception('Ungültiger Vorgang');
                
                
                if('Materialangebot' == $model->descriptor) {
                    $form = "b47ffbb6d10b344b0ad4e1f1bf5526e246b917ce";
                    $descriptor = "Lieferschein";
                }
                elseif($model->_manhours->count() OR $model->_services->count() OR $model->_fare_charges->count()) {
                    $form = "b1454e7841ee1d49f594494b0eaa35748029280a";
                    $descriptor = "Auftrag";
                }
                elseif($model->_material->count()) {
                    $form = "b47ffbb6d10b344b0ad4e1f1bf5526e246b917ce";
                    $descriptor = "Lieferschein";
                }
                else throw new \Exception('have a look');
                
                $form = \Runtime::make('forms')->findOrFail($form);
                $new = new \App\Models\PHPXPress\HwplusTickets();
                
                \DB::transaction(function() use ($model, $form, $new, $descriptor) {
                
                    $new->descriptor = $descriptor;
                    $new->title = $model->title;
                    $new->location = $model->location;
                    $new->_client = $model->_client->getKey();
                    $new->date = $model->date;
                    $new->fare = $model->fare;
                    $new->fare_rate = $model->fare_rate;
                    $new->fare_rate_vat = $model->fare_rate_vat;
                    $new->assignment = $model->assignment;
                    $new->commission_number = $model->commission_number;;
                    $new->note = $model->note;
                    $new->print_note = $model->print_note;
                    $new->order_number = $model->order_number;
                    $new->ID = $new->getHashId();
                    $new->form = $form;
                    $new->_offer = $model->getKey();
                    $new->save();
                    
                    foreach($model->_manhours AS $manhour) {
                    
                        $manhour->ID = NULL;
                        $manhour->ROWID = NULL;
                        $manhour->exists = false;
                        $manhour->_manhours_at_tickets = $new->getKey();
                        $manhour->form = \App\Models\PHPXPress\Forms::find("bdf23694c97afce98ac9fbe9788ad82b8bf5719f");
                        $manhour->save();
                    
                    }

                    foreach($model->_services AS $service) {

                        $service->ID = NULL;
                        $service->ROWID = NULL;
                        $service->exists = false;
                        $service->_services_at_hwplus_tickets = $new->getKey();
                        $service->form = \App\Models\PHPXPress\Forms::find("96fa7fd5ac3bdcaff21ce39838c238bcae8d5667");
                        $service->save();

                    }

                    foreach($model->_fare_charges AS $fare) {

                        $fare->ID = NULL;
                        $fare->ROWID = NULL;
                        $fare->exists = false;
                        $fare->_fare_charges_at_hwplus_tickets = $new->getKey();
                        $fare->form = \App\Models\PHPXPress\Forms::find("14a6023392146d05523a30555c229f8bf90c7315");
                        $fare->save();

                    }
                    
                    foreach($model->_material->sortBy('_material_at_tickets_order ') AS $item) {
                        
                        $item->ID = NULL;
                        $item->ROWID = NULL;
                        $item->exists = false;
                        $item->_material_at_tickets = $new->getKey();
                        $item->form = \App\Models\PHPXPress\Forms::find("f7978012a68047ec09fcafe66f8e7fff51be91fa");
                        //dd($item);
                        $item->save();
                    }
                });
                
                return response()->json([0 => $new]);
            });
            
            
            
            
            
            
            
            
            /**
            
            
            Auftragsbestätigung
            
            
            **/
            
            
            
            
            
            
            
            
            Route::get('preview_confirmation/{row}', function($row) {
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);
                
                $data = $model->prepareBladeData();
                
                $model->header = \Blade::render(file_get_contents(storage_path('app/confirmation-header.txt')), $data);
                $model->footer = \Blade::render(file_get_contents(storage_path('app/confirmation-footer.txt')), $data);
                $filename = \Blade::render(file_get_contents(storage_path('app/filename-confirmation.txt')), $data);
                                
                $pdf = \PDF::loadView('Strommichel.confirmation', ['model' => $model, 'repository' => $repository], [], [
                    'watermark' => 'Vorschau',
                    'show_watermark'  => true,
                ]);
                $path = storage_path('app/Models/Tickets/preview');
                if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                $path .= "/preview.pdf";
                $pdf->save($path);
                return response()->download($path, 'Vorschau ' . $filename . '.pdf', [], 'inline');
            });
            
            Route::get('print_confirmation/{row}', function($row) {
                
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);
                
                if(!$model->job_number) throw new \Exception('ungültiger Vorgang');
                
                if(!$model->printed_confirmation) $model->printed_confirmation = date('Y-m-d');
                
                $data = $model->prepareBladeData();
                $filename = \Blade::render(file_get_contents(storage_path('app/filename-confirmation.txt')), $data);
                
                $path = storage_path('app/Models/Tickets/Auftragsbestätigung'. '/' . date('Y') );   
                
                if(!\File::exists($path . '/' . $model->job_number . '.pdf')) {
                
                    #$data = $model->prepareBladeData();
                    $model->header = \Blade::render(file_get_contents(storage_path('app/confirmation-header.txt')), $data);
                    $model->footer = \Blade::render(file_get_contents(storage_path('app/confirmation-footer.txt')), $data);
                
                    $pdf = \PDF::loadView('Strommichel.confirmation', ['model' => $model, 'repository' => $repository]);
                    if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                    $path .= '/' . $model->job_number . '.pdf';
                    $pdf->save($path);
                } else $path .= '/' . $model->job_number . '.pdf';
                
                
                $model->header = $model->getOriginal('header');
                $model->footer = $model->getOriginal('footer');
                $model->save();
                
                return response()->download($path, $filename . '.pdf', [], 'inline');
            
            });
            
            Route::post('mail_confirmation/{row}', function(\App\Http\Requests\SendEmailRequest $request, $row) {
                
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);

                if(!$model->job_number) throw new \Exception('ungültiger Vorgang');
                
                if(!$model->mailed_confirmation) $model->mailed_confirmation = date('Y-m-d');
                #$email = \Request('data.recipient');
                
                $editor = DotenvEditor::load(storage_path('app/settings.env'));
                $cc = $editor->getKey('CC_CONFIRMATION')['value'];
                
                $path = storage_path('app/Models/Tickets/Auftragsbestätigung/' . date('Y'));
                
                $data = $model->prepareBladeData();
                $filename = \Blade::render(file_get_contents(storage_path('app/filename-confirmation.txt')), $data);
                
                if(!\File::exists($path . '/' . $model->job_number . '.pdf')) {
                
                    #$data = $model->prepareBladeData();
                    $model->header = \Blade::render(file_get_contents(storage_path('app/confirmation-header.txt')), $data);
                    $model->footer = \Blade::render(file_get_contents(storage_path('app/confirmation-footer.txt')), $data);
                
                    $pdf = \PDF::loadView('Strommichel.confirmation', ['model' => $model, 'repository' => $repository]);
                    if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                    $path .= '/' . $model->job_number . '.pdf';
                    $pdf->save($path);
                } else $path .= '/' . $model->job_number . '.pdf';
                
                \Mail::send([],[], function($message) use ($model, $path, $cc, $filename) {
                    $message->attach($path, [
                        'as' => $filename . '.pdf',
                        'mime' => 'application/pdf'
                    ]);
                    $message->to(\Request('data.recipient'));
                    if($cc) $message->cc($cc);
                    $message->subject(\Request('data.subject'));
                    $message->setBody()->text(\Request('data.message'));
                });
                
                
                $model->header = $model->getOriginal('header');
                $model->footer = $model->getOriginal('footer');
                $model->save();

            });
            
            
            
            
            /**
            
            
            Tickets
            
            
            
            **/
            
            
            
            Route::post('create_invoice/{repository}/{row}', function($repository, $row) {
                
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->with('_material', '_services', '_fare_charges', '_manhours._staff')->findOrFail($row);
                $invoice = $model->createInvoice(request('recipient'));
                return response()->json($invoice);
                
            });
            
            
            
            Route::post('subscribe/{repository}/{row}', function(\App\Http\Requests\SubscriptionRequest $request, $repository, $row) {
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);

                if($model->job_number) throw new \Exception('Ungültiger Vorgang');
                
                $model->job_number = $model->createJobNumber();
                $model->signee = request('data')['signee'];
                $model->date = date('Y-m-d');
                $model->flag_signed = 1;

                $data = $model->prepareBladeData();
                $model->header = \Blade::render($model->header, $data);
                $model->footer = \Blade::render($model->footer, $data);


                $pdf = \PDF::loadView('Strommichel.ticket', ['model' => $model, 'repository' => $repository, 'signature' => request('data')['signature']]);
                $path = storage_path('app/Models/Tickets/'.$model->descriptor.'/'. date('Y'));
                if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                $path .= '/' . $model->job_number . '.pdf';
                $pdf->save($path);
                
                $model->save();
            });
            
            Route::get('preview/{repository}/{row}', function($repository, $row) {
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);
                                
                $data = $model->prepareBladeData();

                switch($model->descriptor) {

                    case "Angebot":
                        $model->header = \Blade::render(file_get_contents(storage_path('app/offer-header.txt')), $data);
                        $model->footer = \Blade::render(file_get_contents(storage_path('app/offer-footer.txt')), $data);
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-offer.txt')), $data);
                        break;
                    case "Auftrag":
                        $model->header = \Blade::render(file_get_contents(storage_path('app/order-header.txt')), $data);
                        $model->footer = \Blade::render(file_get_contents(storage_path('app/order-footer.txt')), $data);
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-order.txt')), $data);
                        break;
                    case "Lieferschein":
                        $model->header = \Blade::render(file_get_contents(storage_path('app/shipping-order-header.txt')), $data);
                        $model->footer = \Blade::render(file_get_contents(storage_path('app/shipping-order-footer.txt')), $data);
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-shipping-order.txt')), $data);
                        break;
                    case "Materialbedarf":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-lot.txt')), $data);
                        break;
                    default:
                        throw new \Exception('have a look');
                        break;
                }


                if($model->flag_signed) {

                    $path = storage_path('app/Models/Tickets/'.$model->descriptor.'/'. date('Y'));
                    $path .= '/' . $model->job_number . '.pdf';

                    TextWatermarker::input($path)
                        ->output(storage_path('ticket.tmp.pdf'))
                        ->position(Position::MIDDLE_CENTER)
                        ->asBackground()
                        //->pageRange(1)
                        ->text('Kopie')
                        ->angle(25)
                        ->font(public_path('fonts/Roboto-Regular-webfont.ttf'))
                        ->size('400')
                        ->color('#c5c5c57F') // 7F is the alpha channel (transparency or opacity of color) 0 - 255 in hex
                        ->resolution(300) // 300 dpi
                        ->save();

                    return response()->download(storage_path('ticket.tmp.pdf'), 'Vorschau '.$filename.'.pdf', [], 'inline');
                }

                if(!$model->job_number) $model->job_number = '[' .$model->createJobNumber(). "]";
                

                #dd($repository);
                
                $pdf = \PDF::loadView('Strommichel.ticket', ['model' => $model, 'repository' => $repository], [], [
                    'watermark' => 'Vorschau',
                    'show_watermark'  => true,
                ]);
                
                #dd($model);
                $path = storage_path('app/Models/Tickets/preview');
                if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                $path .= "/preview.pdf";
                $pdf->save($path);
                
                return response()->download($path, 'Vorschau ' . $filename . '.pdf', [], 'inline');
            });
            
            Route::get('print/{repository}/{row}', function($repository, $row) {
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);
                
                if(!$model->job_number) throw new \Exception('Ungültiger Vorgang');
                
                $data = $model->prepareBladeData();
                
                switch($model->descriptor) {
                
                    case "Angebot":
                    case "Materialangebot":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-offer.txt')), $data);
                        break;
                    case "Auftrag":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-order.txt')), $data);
                        break;
                    case "Lieferschein":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-shipping-order.txt')), $data);
                        break;
                    case "Materialbedarf":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-lot.txt')), $data);
                        break;
                    default:
                        throw new \Exception('have a look');
                        break;
                }
                
                $path = storage_path('app/Models/Tickets/'.$model->descriptor.'/'. date('Y'));
                $path .= '/' . $model->job_number . '.pdf';
                if(!\File::exists($path)) throw new \Exception('Keine PDF-Datei gefunden');
                if(!$model->printed) $model->printed = date('Y-m-d');
                $model->save();
                return response()->download($path, $filename . '.pdf');

            });
            
            
            Route::post('mail/{repository}/{row}', function(\App\Http\Requests\SendEmailRequest $request, $repository, $row) {
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);

                if(!$model->job_number) throw new \Exception('Ungültiger Vorgang');
                
                if(!$model->mailed) $model->mailed = date('Y-m-d');
                
                $path = storage_path('app/Models/Tickets/'.$model->descriptor.'/'. date('Y'));
                $path .= '/' . $model->job_number . '.pdf';
                if(!\File::exists($path)) throw new \Exception('Keine PDF-Datei gefunden');
                
                $editor = DotenvEditor::load(storage_path('app/settings.env'));
                
                switch($model->descriptor) {
                
                    case "Angebot":
                    case "Materialangebot":
                        $cc = $editor->getKey('CC_OFFER')['value'];
                        break;
                    case "Auftrag":
                        $cc = $editor->getKey('CC_ORDER')['value'];
                        break;
                    case "Lieferschein":
                        $cc = $editor->getKey('CC_SHIPPING_ORDER')['value'];
                        break;
                    default:
                        throw new \Exception('have a look');
                
                } 
                
                $data = $model->prepareBladeData();
                
                switch($model->descriptor) {
                
                    case "Angebot":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-offer.txt')), $data);
                        break;
                    case "Auftrag":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-order.txt')), $data);
                        break;
                    case "Lieferschein":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-shipping-order.txt')), $data);
                        break;
                    case "Materialbedarf":
                        $filename = \Blade::render(file_get_contents(storage_path('app/filename-lot.txt')), $data);
                        break;
                    default:
                        throw new \Exception('have a look');
                        break;
                }
                
                \Mail::send([],[], function($message) use ($model, $path, $cc, $filename) {
                    $subject = request('data.subject');
                    $message->attach($path, [
                        'as' => $filename . '.pdf',
                        'mime' => 'application/pdf'
                    ]);
                    $message->to(\Request('data.recipient'));
                    if($cc) $message->cc($cc);
                    $message->subject($subject);
                    $message->setBody()->text(\Request('data.message'));
                });

                $model->save();
            });
            
            
            
            
            
            
            
            
            
            
            /**
            
            Rechnung
            
            **/ 
            
            
            
            
            
            Route::get('fullTextSearch', function() {


                if(!request('searchFor')) $invoices = [];
                else $invoices = \App\Models\PHPXPress\HwplusInvoices::search(trim(request('searchFor')) ?? '')
                    ->query(function ($query) {
                        $query->join('hwplus_invoice_items', 'hwplus_invoices.ID', 'hwplus_invoice_items._items_at_hwplus_invoices')
                            ->select(['hwplus_invoices.ID', 'hwplus_invoices.descriptor', 'hwplus_invoice_items.descriptor AS article'])
                            ->orderBy('hwplus_invoices.ID', 'DESC');
                    })
                    ->get();

                return response()->json(data: $invoices, status: 200);

            });
            
            
            Route::get('preview_invoice/{repository}/{row}', function($repository, $row) {
                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->find($row);


                $data = $model->prepareBladeData();
                $filename = \Blade::render(file_get_contents(storage_path('app/filename-invoice.txt')), $data);

                if($model->flag_finished) {

                    $path = storage_path('app/Models/Invoices/'. date('Y'));
                    $path = $path . '/' . $model->issue . '.pdf';

                TextWatermarker::input($path)
                    ->output(storage_path('ticket.tmp.pdf'))
                    ->position(Position::MIDDLE_CENTER)
                    ->asBackground()
                    //->pageRange(1)
                    ->text('Kopie')
                    ->angle(25)
                    ->font(public_path('fonts/Roboto-Regular-webfont.ttf'))
                    ->size('400')
                    ->color('#c5c5c57F') // 7F is the alpha channel (transparency or opacity of color) 0 - 255 in hex
                    ->resolution(300) // 300 dpi
                    ->save();

                    return response()->download(storage_path('ticket.tmp.pdf'), 'Vorschau '.$filename.'.pdf', [], 'inline');
                }

                if(!$model->invoice_number) $model->invoice_number = '[' .$model->createInvoiceNumber(). "]";
                $model->header = \Blade::render($model->header, $data);

                $pdf = \PDF::loadView('Strommichel.invoice', ['model' => $model, 'repository' => $repository], [], [
                    'watermark' => 'Vorschau',
                    'show_watermark'  => true,
                ]);
                $path = storage_path('app/Models/Invoices/preview');
                if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                $path .= "/preview.pdf";
                $pdf->save($path);
                return response()->download($path, 'Vorschau '.$filename.'.pdf', [], 'inline');
            });
            
                        
            Route::get('finish_invoice/{repository}/{row}', function($repository, $row) {

                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->with('_client', '_items._meta._doctype')->find($row);
                
                if("Korrekturrechnung" == $model->descriptor AND !$model->invoice_number)  throw new \Exception('Ungültiger Vorgang');
                if("Korrekturrechnung" != $model->descriptor AND $model->invoice_number) throw new \Exception('Ungültiger Vorgang');
                if(!$model->_client) throw new \Exception('customer not found');
                
                $settings = DotenvEditor::load(storage_path('app/settings.env'));
                
                $model->flag_finished = 1;

                if(!$model->date)
                    $model->date = date('Y-m-d');

                if(!$model->service_date)
                    $model->service_date = date('Y-m-d');

                if(!$model->invoice_number)
                    $model->invoice_number = $model->issue = $model->createInvoiceNumber();



                // Create PDF-Rechnung
                
                $data = $model->prepareBladeData();
                $model->header = \Blade::render($model->header, $data);
                
                $pdf = \PDF::loadView('Strommichel.invoice', ['model' => $model, 'repository' => $repository]);
                
                $path = storage_path('app/Models/Invoices/'. date('Y'));
                if(!\File::exists($path)) File::makeDirectory($path, $mode = 0775, true);
                $path = $path . '/' . $model->issue . '.pdf';
                $pdf->save($path);
                
                $pdfDataOrFilename = $path;
                
                // Create XRechnung
                
                $document = (ZugferdQuickDescriptorXRechnung3::doCreateNew())
                    ->doCreateInvoice($model->issue, \DateTime::createFromFormat("Y-m-d", $model->date), "EUR")
                    #->doSetPaymentTerms("Zahlbar sofort", new \DateTime('+3 days'))
                    ->doSetBuyer($model->client, $model->postcode, $model->location, $model->streetadress . ' ' . $model->housenumber, "DE", $model->customer_id)
                    ->doSetBuyerContact($model->client)
                    ->doSetBuyerElectronicCommunication($model->email)
                    ->doSetSeller($settings->getKey('COMPANY_NAME')['value'], $settings->getKey('COMPANY_POSTCODE')['value'], $settings->getKey('COMPANY_LOCATION')['value'], $settings->getKey('COMPANY_STREETADDRESS')['value'] . ' ' . $settings->getKey('COMPANY_HOUSENUMBER')['value'], $settings->getKey('COMPANY_COUNTRY')['value'], null, null, null)
                    ->doSetSellerContact($settings->getKey('COMPANY_CONTACT_NAME')['value'], null, $settings->getKey('COMPANY_CONTACT_EMAIL')['value'], $settings->getKey('COMPANY_CONTACT_PHONE')['value'])
                    ->doSetSellerElectronicCommunication($settings->getKey('COMPANY_EMAIL')['value'])
                    ->doSetPaymentMeansForCreditTransfer(true, $settings->getKey('COMPANY_IBAN')['value']);
                    
                if($settings->getValue('COMPANY_FA')) $document->doAddSellerTaxRegistration("VA", $settings->getKey('COMPANY_FA')['value']);
                if($settings->getValue('COMPANY_VA')) $document->doAddSellerTaxRegistration("FA", $settings->getKey('COMPANY_VA')['value']);
                    
                $document->doSetPaymentTerms($model->_client->_payment_term->text, new \DateTime('+' . $model->_client->_payment_term->due_date . ' days'));
                
                $pos = 1;
                $sum = 0;

                $xunits = \Runtime::make('hwplus_units')->get();

                // Nebenleistungen

                foreach($model->_items AS $posten) {
                
                    if("050b070c151f8f0b9d76589922f58a908e67535f" == $posten->_meta->_doctype->getKey()) {

                        $unit = $xunits->where('descriptor', $posten->unit)->first();
                        if(!$unit) throw new \Exception('invalid xunitcode ' . $posten->unit);

                        $document->doAddTradeLineItem($pos, $posten->descriptor, (float) str_replace(',', '.', $posten->netprice), (float) str_replace(',', '.', $posten->amount), $unit->xunitcode, 0, "", "S", "VAT", (float) str_replace(',', '.', $posten->vat));
                        $sum += (float) str_replace(',', '.', $posten->netprice) * (float) str_replace(',', '.', $posten->amount);
                        $pos++;
                    }
 
                }

                // Arbeitsstunden
                
                foreach($model->_items AS $posten) {


                
                    if("cba3def15e0e6c1151fe202c8b00c2a0c1951909" == $posten->_meta->_doctype->getKey()) {

                        $unit = $xunits->where('descriptor', $posten->unit)->first();
                        if(!$unit) throw new \Exception('invalid xunitcode');

                        $document->doAddTradeLineItem($pos, $posten->descriptor, (float) str_replace(',', '.', $posten->netprice), (float) str_replace(',', '.', $posten->amount), $unit->xunitcode, 0, "", "S", "VAT", (float) str_replace(',', '.', $posten->vat));
                        $sum += (float) str_replace(',', '.', $posten->netprice) * (float) str_replace(',', '.', $posten->amount);
                        $pos++;
                    }
 
                }
                

                // Dienstleistungen
                
                foreach($model->_items AS $posten) {

                    if("b76663c559923d5b46f232451fea273f6887bb28" == $posten->_meta->_doctype->getKey()) {

                        $unit = $xunits->where('descriptor', $posten->unit)->first();
                        if(!$unit) throw new \Exception('invalid xunitcode');

                        $document->doAddTradeLineItem($pos, $posten->descriptor, (float) str_replace(',', '.', $posten->netprice), (float) str_replace(',', '.', $posten->amount), $unit->xunitcode, 0, "", "S", "VAT", (float) str_replace(',', '.', $posten->vat));
                        $sum += (float) str_replace(',', '.', $posten->netprice) * (float) str_replace(',', '.', $posten->amount);
                        $pos++;
                    }

                }


                // Sonstiges

                foreach($model->_items AS $posten) {

                    if("e63730ed5536eb59ae0dfd1eb96f5a862be2e5c7" == $posten->_meta->_doctype->getKey()) {

                        $unit = $xunits->where('descriptor', $posten->unit)->first();
                        if(!$unit) throw new \Exception('invalid xunitcode');

                        $document->doAddTradeLineItem($pos, $posten->descriptor, (float) str_replace(',', '.', $posten->netprice), (float) str_replace(',', '.', $posten->amount), $unit->xunitcode, 0, "", "S", "VAT", (float) str_replace(',', '.', $posten->vat));
                        $sum += (float) str_replace(',', '.', $posten->netprice) * (float) str_replace(',', '.', $posten->amount);
                        $pos++;
                    }

                }




                // Material
                
                foreach($model->_items AS $posten) {
                
                    if("854cbb63e8c1319f02330c2e61e7b93bf4682cc2" == $posten->_meta->_doctype->getKey()) {

                        $unit = $xunits->where('descriptor', $posten->unit)->first();
                        if(!$unit) throw new \Exception('invalid xunitcode');

                        $document->doAddTradeLineItem($pos, $posten->descriptor, (float) str_replace(',', '.', $posten->netprice), (float) str_replace(',', '.', $posten->amount), $unit->xunitcode, 0, "", "S", "VAT", (float) str_replace(',', '.', $posten->vat));
                        $sum += (float) str_replace(',', '.', $posten->netprice) * (float) str_replace(',', '.', $posten->amount);
                        $pos++;
                    }
 
                }

                if($model->_premium_charge) {

                    $posten = $model->_premium_charge;
                    $posten->vat = (float) str_replace(',', '.', $model->_premium_charge->_vat->rate);

                    if('%' == $posten->unit) {

                        $document->doAddTradeLineItem($pos, $posten->descriptor, round($sum / 100 * (float) str_replace(',', '.', $posten->value), 2), 1, "P1", 0, "", "S", "VAT", (float) $posten->vat);
                        $pos++;

                    } else {

                        $document->doAddTradeLineItem($pos, $posten->descriptor, (float) str_replace(',', '.', $posten->value), 1, "LS", 0, "", "S", "VAT", (float) $posten->vat);
                        $pos++;

                    }

                }

                // Check


                if(number_format((float) str_replace(',', '.', $model->net), 2, ',', '') != number_format($sum, 2, ',', '')) throw new \Exception('Nettobeträge der XML-Rechnung stimmen nicht überein');
                
                //$document->writeFile(storage_path() . "/factur-x.xml");
                $path = 'app/Models/Invoices/'. date('Y') . '/' . $model->issue . '.xml';
                $document->writeFile(storage_path($path));
                
                
                $xmlDataOrFilename = storage_path($path);
                
                
                $path = 'app/Models/Invoices/'. date('Y') . '/' . $model->issue . '.merged.pdf';
                $mergedPdfFilename = storage_path($path);

                ZugferdLaravel::buildMergedPdfByXmlDataOrXmlFilename($xmlDataOrFilename, $pdfDataOrFilename, $mergedPdfFilename);
                
                $model->save();

            });

            Route::delete('drop_invoice/{row}', function($row){

                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->with('_notes', '_items')->find($row);


                \DB::transaction(function() use ($model) {
                    foreach($model->_notes AS $note) $note->delete();
                    foreach($model->_items AS $item) $item->delete();
                    $model->delete();
                });

            });

            
            
            Route::post('change_invoice_receipient/{row}/{client}', function($row, $client){

                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->with('_meta')->find($row);
                $client = \Runtime::make('hwplus_clients')->find($client);

                if(strpos($model->email, ',') !== false) throw new \Exception('Kundenadresse gesperrt, mehrere Email-Adressen hinterlegt. Bitte verwenden Sie eine (neue) Rechnungsadresse.');

                $model->_client = $client->getKey();
                $model->client = $client->descriptor;
                $model->customer_id = $client->customer_id;
                $model->firstname = $client->firstname;
                $model->surname = $client->surname;
                $model->streetadress = $client->streetadress;
                $model->housenumber = $client->housenumber;
                $model->location = $client->location;
                $model->postcode = $client->postcode;
                $model->email = $client->email;


                if($model->invoice_number) throw new \Exception('Ungültiger Vorgang');
                else $model->save();



            });
            
            Route::post('create_standing_order/{row}', function($row) {

                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->with('_meta')->find($row);

                if($model->invoice_number) throw new \Exception('Ungültiger Vorgang');
                
                if("invoice" != $model->_meta->_doctype->identifier) throw new \Exception('Ungültige Vorlage');
                
                \DB::transaction(function() use ($model) {
                
                    $editor = DotenvEditor::load(storage_path('app/settings.env'));
                    $next_invoice_number = $editor->getValue('NEXT_STANDING_ORDER');
                    
                    $model->descriptor = "Dauerauftrag";
                    $model->billing_rotation = "1 months";
                    $model->invoice_number = $next_invoice_number;
                    $model->header = file_get_contents(storage_path('app/standing-order-header.txt'));
                    $model->save();
                    

                    $meta = \Runtime::make('meta')
                        ->where('_type', 1)
                        ->where('_row', $model->getKey())
                        ->where('_repository', $model->getConfig()->getKey())
                        ->first();
                        
                    $meta->_doctype = "d65072e9a806a18e70d810c83685b4ee0b2fd688";
                    $meta->save();
                    
                    $editor->setKey('NEXT_STANDING_ORDER', ++$next_invoice_number);
                    $editor->save();
                    
                });
                
                
                
                return response()->json([0 => $model]);
            
            }); 
            
            
            
            Route::get('print_invoice/{repository}/{row}', function($repository, $row) {
            
                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->find($row);
                
                if(!$model->invoice_number) throw new \Exception('Ungültiger Vorgang');
                
                if(!$model->printed) $model->printed = date('Y-m-d');
                
                $data = $model->prepareBladeData();
                $model->file_name = \Blade::render(file_get_contents(storage_path('app/filename-invoice.txt')), $data);
                
                $path = storage_path('app/Models/Invoices/' . date('Y'));
                $path  .= '/' . $model->issue . '.merged.pdf';
                if(!\File::exists($path)) throw new \Exception('Keine PDF-Datei gefunden');
                
                $model->save();
                return response()->download($path, $model->file_name . '.pdf');

            });
            


            
            Route::post('mail_invoice/{repository}/{row}', function(\App\Http\Requests\SendEmailRequest $request, $repository, $row) {
                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->find($row);

                if(!$model->invoice_number) throw new \Exception('Ungültiger Vorgang');
                
                if(!$model->mailed) $model->mailed = date('Y-m-d');
                
                $model->email = \Request('data.recipient');
                
                $path = storage_path('app/Models/Invoices/'. date('Y'));
                $path .= '/' . $model->issue . '.merged.pdf';
                
                $data = $model->prepareBladeData();
                $model->file_name = \Blade::render(file_get_contents(storage_path('app/filename-invoice.txt')), $data);
                
                $editor = DotenvEditor::load(storage_path('app/settings.env'));
                $cc = $editor->getKey('CC_INVOICE')['value'];

                \Mail::send([],[], function($message) use ($model, $path, $cc) {
                    $subject = \Request('data.subject');
                    $message->attach($path, [
                        'as' => $model->file_name. '.pdf',
                        'mime' => 'application/pdf'
                    ]);
                    $message->to($model->email);
                    if($cc) $message->cc($cc);
                    $message->subject($subject);
                    $message->setBody()->text(\Request('data.message'));
                });
                
                $model->save();

            });

            Route::post('copy_invoice/{row}', function($row) {

                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->with('_meta')->find($row);

                if("invoice" != $model->_meta->_doctype->identifier AND "standing_order" != $model->_meta->_doctype->identifier) throw new \Exception('Ungültige Vorlage');

                \DB::transaction(function() use ($model) {


                    $new = $model->replicate();
                    $new->commission_number .= " (Kopie)";
                    $new->invoice_number = NULL;
                    $new->flag_finished  = 0;
                    #$new->email = NULL;
                    $new->mailed = NULL;
                    $new->printed = NULL;
                    $new->file_name = "";
                    $new->issue = NULL;
                    $new->form = \Runtime::make('forms')->findOrFail('5dfe19c87715ed4ca89abb9f4eb4da4dc060c8bd');
                    $new->_reverse_invoice = NULL;
                    $new->date_reverse_invoice = NULL;
                    $new->_adjusted_invoice = NULL;
                    $new->date_adjusted = NULL;
                    $new->ID = $new->getHashId();
                    $new->date = date('Y-m-d');
                    #$new->_ticket = NULL;
                    $new->save();

                    foreach($model->_items AS $item) {

                        $item->ROWID = NULL;
                        $item->exists = false;
                        $item->_items_at_hwplus_invoices = $new->getKey();
                        $item->form = $item->_meta->_doctype;
                        $item->ID = $item->getHashId();
                        $item->save();



                    }

                    foreach($new->_notes AS $note) $note->delete();

                    foreach($model->_notes AS $note) {

                        $note->ROWID = NULL;
                        $note->exists = false;
                        $note->_notes_at_hwplus_invoices = $new->getKey();
                        $note->form = $note->_meta->_doctype;
                        $note->ID = $note->getHashId();
                        $note->save();

                    }

                });

                #$model->refresh();
                #$new->refresh();

                #if($model->net != $new->net) throw new \Exception('ungültige Nettobeträge');
                #if($model->gross != $new->gross) throw new \Exception('ungültige Bruttobeträge');

            });
            
            Route::post('create_reverse_invoice/{row}', function($row) {

                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->with('_meta')->find($row);

                if(!$model->invoice_number) throw new \Exception('Ungültiger Vorgang');
                if($model->_reverse_invoice) throw new \Exception('Ungültiger Vorgang');
                if("Stornorechnung" == $model->descriptor) throw new \Exception('Ungültiger Vorgang');
                if("invoice" != $model->_meta->_doctype->identifier AND "standing_order" != $model->_meta->_doctype->identifier) throw new \Exception('Ungültige Vorlage');

                $reverse = \DB::transaction(function() use ($model) {
                                 
                    
                    $reverse = $model->replicate();
                    $reverse->descriptor = "Stornorechnung";
                    $reverse->invoice_number = NULL;
                    $reverse->flag_finished  = 0;
                    #$reverse->email = NULL;
                    $reverse->mailed = NULL;
                    $reverse->printed = NULL;
                    $reverse->file_name = "";
                    $reverse->form = \Runtime::make('forms')->findOrFail('063675763722e0e65c40d12751e99aa2a38cb28f');
                    $reverse->ID = $reverse->getHashId();
                    $reverse->date = date('Y-m-d');
                    $reverse->save();
 
                    foreach($model->_items AS $item) {
                    
                        $item->ROWID = NULL;
                        $item->exists = false;
                        $item->_items_at_hwplus_invoices = $reverse->getKey();
                        $item->form = $item->_meta->_doctype;
                        $item->netprice = '-' . $item->netprice;
                        $item->ID = $item->getHashId();
                        $item->save();
                        
                        
                    
                    }

                    foreach($reverse->_notes AS $note) $note->delete();
                    
                    foreach($model->_notes AS $note) {

                        $note->ROWID = NULL;
                        $note->exists = false;
                        $note->_notes_at_hwplus_invoices = $reverse->getKey();
                        $note->form = $note->_meta->_doctype;
                        $note->ID = $note->getHashId();
                        $note->save();

                    }
                    
                    $model->_reverse_invoice = $reverse->getKey();
                    $model->date_reverse_invoice = date('Y-m-d');
                    $model->save();
                    
                    return $reverse;

                });
                
                #$reverse->refresh();

                #if( "-" . $model->net != $reverse->net) throw new \Exception('ungültige Nettobeträge');
                #if( "-" . $model->gross != $reverse->gross) throw new \Exception('ungültige Bruttobeträge');
                
                return response()->json([0 => $model]);
            
            }); 
            
            
            Route::post('create_adjusted_invoice/{row}', function($row) {

                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->with('_meta')->find($row);

                if(!$model->invoice_number) throw new \Exception('Ungültiger Vorgang');
                if($model->_adjusted_invoice) throw new \Exception('Ungültiger Vorgang');
                if("Korrekturrechnung" == $model->descriptor) throw new \Exception('Ungültiger Vorgang');
                if("invoice" != $model->_meta->_doctype->identifier AND "standing_order" != $model->_meta->_doctype->identifier) throw new \Exception('Ungültige Vorlage');
                
                $adjusted = \DB::transaction(function() use ($model, $repository) {
                                 
                    
                    $adjusted = $model->replicate();
                    $adjusted->descriptor = "Korrekturrechnung";
                    $adjusted->issue = $model->invoice_number . '-' . $repository->where('invoice_number', $adjusted->invoice_number)->count();
                    $adjusted->flag_finished  = 0;
                    $adjusted->mailed = NULL;
                    $adjusted->printed = NULL;
                    $adjusted->file_name = "";
                    $adjusted->form = \Runtime::make('forms')->findOrFail('c98ef4b9d199a338e5ff2cca60d539c46b19e69e');
                    $adjusted->ID = $adjusted->getHashId();
                    $adjusted->date = date('Y-m-d');
                    $adjusted->save();
 
                    foreach($model->_items AS $item) {
                    
                        $item->ROWID = NULL;
                        $item->exists = false;
                        $item->_items_at_hwplus_invoices = $adjusted->getKey();
                        $item->form = $item->_meta->_doctype;
                        $item->netprice = $item->netprice;
                        $item->ID = $item->getHashId();
                        $item->save();
                        
                    }
                    
                    foreach($adjusted->_notes AS $note) $note->delete();

                    foreach($model->_notes AS $note) {

                        $note->ROWID = NULL;
                        $note->exists = false;
                        $note->_notes_at_hwplus_invoices = $adjusted->getKey();
                        $note->form = $note->_meta->_doctype;
                        $note->ID = $note->getHashId();
                        $note->save();

                    }
                    
                    $model->_adjusted_invoice = $adjusted->getKey();
                    $model->date_adjusted = date('Y-m-d');
                    $model->save();

                    return $adjusted;
                    
                });
                
                #$model->refresh();
                #$adjusted->refresh();

                #if($model->net != $adjusted->net) throw new \Exception('ungültige Nettobeträge');
                #if($model->gross != $adjusted->gross) throw new \Exception('ungültige Bruttobeträge');
                
                return response()->json([0 => $model]);
            
            });


            Route::get('make_reverse_charge_invoice/{repository}/{row}', function($repository, $row) {

                if(1 == request('reverse_charge')) {

                    $repository = \Runtime::make($repository);
                    $model = $repository->with('_items._meta._doctype')->findOrFail($row);

                    $meta = \Runtime::make('meta')->findOrFail($model->_meta->getKey());
                    $meta->_doctype="1976857f41d6dfa39e86add5da50ffda45fd48ee";
                    $meta->save();

                    $model->descriptor= "Bauleistung";
                    $model->save();

                    $form = \Runtime::make('forms')->findOrFail('5b895c53f265570cdcfa59b26e633be4e179a38e');

                    foreach(\App\Models\PHPXPress\HwplusInvoiceNotesPatterns::where('descriptor', "Reverse Charge")->get() AS $pattern) {

                    $note =new \App\Models\PHPXPress\HwplusInvoiceNotes();
                    $note->form = $form;
                    $note->_notes_at_hwplus_invoices = $model->getKey();
                    $note->descriptor = $pattern->descriptor;
                    $note->text = $pattern->text;
                    $note->sort = $pattern->order;
                    $note->save();

                }

                }



            });
            
            
            Route::post('set_date_paid/{row}', function($row) {
            
                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->with('_meta')->find($row);
                
                $model->date_paid = request('paid') ? date('Y-m-d') : NULL;
                $model->save();
                
            
            });
            
            










            /**






            Mahnwesen







            **/



            Route::post('mail_dunning/{row}', function(\App\Http\Requests\SendEmailRequest $request, $row) {
                $repository = \Runtime::make('hwplus_invoices');
                $model = $repository->find($row);

                if(!$model->invoice_number) throw new \Exception('Ungültiger Vorgang');

                $path = storage_path('app/Models/Invoices/'. date('Y'));
                $path .= '/' . $model->issue . '.merged.pdf';

                $editor = DotenvEditor::load(storage_path('app/settings.env'));
                $cc = $editor->getKey('CC_DUNNING')['value'];

                // Zahlungserinnerung

                $data = $model->prepareBladeData();

                if(!$model->date_payment_reminder) {

                    $header = $model->header;
                    $model->header = \Blade::render(file_get_contents(storage_path('app/dunning-reminder-header.txt')), $data);
                    $filename = \Blade::render(file_get_contents(storage_path('app/filename-dunning-reminder.txt')), $data);
                    $model->date_payment_reminder = date('Y-m-d');

                } elseif(!$model->date_demand_for_payment) {

                    $header = $model->header;
                    $model->header = \Blade::render(file_get_contents(storage_path('app/dunning-demand-header.txt')), $data);
                    $filename = \Blade::render(file_get_contents(storage_path('app/filename-dunning-demand.txt')), $data);
                    $model->date_demand_for_payment = date('Y-m-d');


                } elseif(!$model->date_dunning_letter) {

                    $header = $model->header;
                    $model->header = \Blade::render(file_get_contents(storage_path('app/dunning-dun-header.txt')), $data);
                    $filename = \Blade::render(file_get_contents(storage_path('app/filename-dunning-dun.txt')), $data);
                    $model->date_dunning_letter = date('Y-m-d');


                } else throw new \Exception('have a look');

                $pdf = \PDF::loadView('Strommichel.dunning', ['model' => $model, 'repository' => $repository]);


                \Mail::send([],[], function($message) use ($model, $path, $cc, $pdf) {
                    $message->attach($path, [
                        'as' => \Request('data.invoice_name'). '.pdf',
                        'mime' => 'application/pdf'
                    ]);
                    $message->attachData($pdf->output(), \Request('data.file_name'));
                    $message->to(\Request('data.recipient'));
                    if($cc) $message->cc($cc);
                    $message->subject(\Request('data.subject'));
                    $message->setBody()->text(\Request('data.message'));
                });

                $model->header = $header;


                $model->save();

            });












            /**



            Kalender & Planung




            **/





             Route::post('createDate', function() {

                 $date = \Runtime::make('hwplus_events');
                 $date->start_date = request('start_date') . ' ' . request('start_time');
                 $date->end_date = request('end_date') . ' ' . request('end_time');
                 $date->form = \Runtime::make('forms')->findOrFail('8a5c1cf1c49cbba7062fb88489ac350fc3a02d27');
                 $date->descriptor = request('descriptor');
                 $date->_dates_at_hwplus_staff = request('_staff');
                 $date->save();


             });

            Route::put('updateDate/{row}', function($row) {

                 $date = \Runtime::make('hwplus_events')->findOrFail($row);
                 $date->start_date = request('start_date') . ' ' . request('start_time');
                 $date->end_date = request('end_date') . ' ' . request('end_time');
                 $date->form = \Runtime::make('forms')->findOrFail('8a5c1cf1c49cbba7062fb88489ac350fc3a02d27');
                 if(request('_staff')) $date->_dates_at_hwplus_staff = request('_staff');
                 $date->save();


             });


            Route::get('getDates', function() {


                $dates = \Runtime::make('hwplus_events')->get();



                $result = [];
                foreach($dates AS $date) {
                    $color = $date->_dates_at_hwplus_staff ? $date->_dates_at_hwplus_staff->color : '#20C997';
                    $result[] = [
                        'title' => $date->descriptor,
                        'start' => $date->start_date,
                        'end' => $date->end_date,
                        'id' => $date->getKey(),
                        '_staff' => $date->_dates_at_hwplus_staff,
                        'backgroundColor' => $color,
                        'borderColor' => $color
                    ];
                }

                return response()->json($result);
            });











            
            
            /**
            
            
            
            Sonstiges
            
            
            
            **/
            
            
            
            
            
   
            
            Route::post('copyTicket/{repository}/{row}', function($repository, $row) {
                
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);
                
                $new = new \App\Models\PHPXPress\HwplusTickets();
                
                \DB::transaction(function() use ($model, $new) {
                    
                    $new->descriptor = $model->descriptor;
                    $new->location = $model->location;
                    $new->_client = $model->_client->getKey();
                    $new->date = $model->date;
                    $new->fare = $model->fare;
                    $new->assignment = $model->assignment;
                    $new->commission_number = $model->commission_number . ' (KOPIE)';
                    $new->note = $model->note;
                    $new->print_note = $model->print_note;
                    $new->order_number = $model->order_number;
                    $new->ID = $new->getHashId();
                    $new->form = $model->_meta->_doctype;
                    $new->save();
                    
                    foreach($model->_manhours AS $manhour) {
                    
                        $manhour->ID = NULL;
                        $manhour->ROWID = NULL;
                        $manhour->exists = false;
                        $manhour->_manhours_at_tickets = $new->getKey();
                        $manhour->form = \App\Models\PHPXPress\Forms::find("bdf23694c97afce98ac9fbe9788ad82b8bf5719f");
                        $manhour->save();
                    
                    }
                    
                    foreach($model->_material->sortBy('_material_at_tickets_order ') AS $item) {
                        
                        $item->ID = NULL;
                        $item->ROWID = NULL;
                        $item->exists = false;
                        $item->_material_at_tickets = $new->getKey();
                        $item->form = \App\Models\PHPXPress\Forms::find("f7978012a68047ec09fcafe66f8e7fff51be91fa");
                        //dd($item);
                        $item->save();
                    }
                });
                
                return response()->json($new);
            });
            
            Route::post('copyMaterial/{repository}/{row}', function($repository, $row) {
                $repository = \Runtime::make('hwplus_tickets');
                $model = $repository->find($row);
                
               
                if(isset(request()->data['copyFrom'])) {
                    
                    $copyFrom = $repository->find(request()->data['copyFrom'])->_material->sortBy('_material_at_tickets_order');
                    $order = $model->_material->count() + 1;
                    
                    \DB::transaction(function() use ($copyFrom, $order, $model) {
                        foreach($copyFrom AS $pos) {
                        
                            $pos->ID = NULL;
                            $pos->ROWID = NULL;
                            $pos->exists = false;
                            $pos->_material_at_tickets = $model->getKey();
                            $pos->form = \App\Models\PHPXPress\Forms::find("f7978012a68047ec09fcafe66f8e7fff51be91fa");
                            $pos->_material_at_tickets_order = $order;
                            $pos->save();
                            
                            $order++;
                        }
                    });
                }
                
                if(isset(request()->data['copyItems'])) {
                
                    $order = $model->_material->count() + 1;
                       
                    \DB::transaction(function() use ($order, $model) {
                        foreach(request()->data['copyItems'] AS $pos) {
                    
                            $item = \App\Models\PHPXPress\HwplusMaterial::where('ID', $pos)->first();
                            $item->_material_at_tickets_order = $order;
                            $item->ID = NULL;
                            $item->ROWID = NULL;
                            $item->exists = false;
                            $item->_material_at_tickets = $model->getKey();
                            $item->form = \App\Models\PHPXPress\Forms::find("f7978012a68047ec09fcafe66f8e7fff51be91fa");
                            $item->save();
                            
                            $order++;
                        }
                    });
                }
                
              
                

            });
            
            

            Route::post('settings', function(\App\Http\Requests\SettingsRequest $request) {
            
                $response = [];
            
                $editor = DotenvEditor::load(storage_path('app/settings.env'));
                
                if(1 == request('settings')) {

                    $editor->setKey('APP_TITLE', request('data')['app_title']);

                    $editor->setKey('COMPANY_NAME', request('data')['company_name']);
                    $editor->setKey('COMPANY_POSTCODE', request('data')['company_postcode']);
                    $editor->setKey('COMPANY_LOCATION', request('data')['company_location']);
                    $editor->setKey('COMPANY_STREETADDRESS', request('data')['company_streetaddress']);
                    $editor->setKey('COMPANY_HOUSENUMBER', request('data')['company_housenumber']);
                    $editor->setKey('COMPANY_COUNTRY', request('data')['company_country']);
                    $editor->setKey('COMPANY_EMAIL', request('data')['company_email']);
                    $editor->setKey('COMPANY_CONTACT_NAME', request('data')['company_contact_name']);
                    $editor->setKey('COMPANY_CONTACT_EMAIL', request('data')['company_contact_email']);
                    $editor->setKey('COMPANY_CONTACT_PHONE', request('data')['company_contact_phone']);
                    $editor->setKey('COMPANY_VA', request('data')['company_va']);
                    $editor->setKey('COMPANY_FA', request('data')['company_fa']);
                    $editor->setKey('COMPANY_SBLAW', isset(request('data')['company_sblaw']) ? 1 : 0);
                    $editor->setKey('COMPANY_IBAN', request('data')['company_iban']);


                    $file = request()->file('pdf_header');
                    if($file) {
                        request()->file('pdf_header')->storeAs(
                            'images', 'pdf_header.'. $file->getClientOriginalExtension(), 'public'
                        );
                        $editor->setKey('IMAGE_PDF_HEADER',  $file->getClientOriginalExtension());
                        $response[0]['pdf_header_image'] = 'pdf_header.'. $file->getClientOriginalExtension();
                    }

                    $file = request()->file('pdf_footer');
                    if($file) {
                        request()->file('pdf_footer')->storeAs(
                            'images', 'pdf_footer.'. $file->getClientOriginalExtension(), 'public'
                        );
                        $editor->setKey('IMAGE_PDF_FOOTER',  $file->getClientOriginalExtension());
                        $response[0]['pdf_footer_image'] = 'pdf_footer.'. $file->getClientOriginalExtension();
                    }



                    // Angebot
                    $editor->setKey('CC_OFFER', request('data')['cc_offer']);
                    file_put_contents(storage_path('app/email-subject-offer.txt'), request('data')['mailsubject_offer']);
                    file_put_contents(storage_path('app/email-body-offer.txt'), request('data')['mailbody_offer']);
                    file_put_contents(storage_path('app/offer-header.txt'), request('data')['offer_header']);
                    file_put_contents(storage_path('app/offer-footer.txt'), request('data')['offer_footer']);
                    file_put_contents(storage_path('app/filename-offer.txt'), request('data')['filename_offer']);

                    // Auftragsbestätigung
                    $editor->setKey('CC_CONFIRMATION', request('data')['cc_confirmation']);
                    file_put_contents(storage_path('app/email-subject-confirmation.txt'), request('data')['mailsubject_confirmation']);
                    file_put_contents(storage_path('app/email-body-confirmation.txt'), request('data')['mailbody_confirmation']);
                    file_put_contents(storage_path('app/confirmation-header.txt'), request('data')['confirmation_header']);
                    file_put_contents(storage_path('app/confirmation-footer.txt'), request('data')['confirmation_footer']);
                    file_put_contents(storage_path('app/filename-confirmation.txt'), request('data')['filename_confirmation']);

                    // Lieferschein
                    $editor->setKey('CC_SHIPPING_ORDER', request('data')['cc_shipping_order']);
                    file_put_contents(storage_path('app/email-subject-shipping-order.txt'), request('data')['mailsubject_shipping_order']);
                    file_put_contents(storage_path('app/email-body-shipping-order.txt'), request('data')['mailbody_shipping_order']);
                    file_put_contents(storage_path('app/shipping-order-header.txt'), request('data')['shipping_order_header']);
                    file_put_contents(storage_path('app/shipping-order-footer.txt'), request('data')['shipping_order_footer']);
                    file_put_contents(storage_path('app/filename-shipping-order.txt'), request('data')['filename_shipping_order']);

                    // Auftrag
                    $editor->setKey('CC_ORDER', request('data')['cc_order']);
                    file_put_contents(storage_path('app/email-subject-order.txt'), request('data')['mailsubject_order']);
                    file_put_contents(storage_path('app/email-body-order.txt'), request('data')['mailbody_order']);
                    file_put_contents(storage_path('app/order-header.txt'), request('data')['order_header']);
                    file_put_contents(storage_path('app/order-footer.txt'), request('data')['order_footer']);
                    file_put_contents(storage_path('app/filename-order.txt'), request('data')['filename_order']);

                    // Rechnung
                    $editor->setKey('CC_INVOICE', request('data')['cc_invoice']);
                    file_put_contents(storage_path('app/email-subject-invoice.txt'), request('data')['mailsubject_invoice']);
                    file_put_contents(storage_path('app/email-body-invoice.txt'), request('data')['mailbody_invoice']);
                    file_put_contents(storage_path('app/invoice-header.txt'), request('data')['invoice_header']);
                    file_put_contents(storage_path('app/bill-header.txt'), request('data')['bill_header']);
                    file_put_contents(storage_path('app/filename-invoice.txt'), request('data')['filename_invoice']);


                    // Dauerauftrag
                    $editor->setKey('CC_STANDING_ORDER', request('data')['cc_standing_order']);
                    file_put_contents(storage_path('app/email-subject-standing-order.txt'), request('data')['mailsubject_standing_order']);
                    file_put_contents(storage_path('app/email-body-standing-order.txt'), request('data')['mailbody_standing_order']);
                    file_put_contents(storage_path('app/standing-order-header.txt'), request('data')['standing_order_header']);
                    file_put_contents(storage_path('app/filename-standing-order.txt'), request('data')['filename_standing_order']);

                    // Mahnwesen
                    $editor->setKey('CC_DUNNING', request('data')['cc_dunning']);

                    // 1. Zahlungserinnerung

                    file_put_contents(storage_path('app/email-subject-dunning-reminder.txt'), request('data')['mailsubject_dunning_reminder']);
                    file_put_contents(storage_path('app/email-body-dunning-reminder.txt'), request('data')['mailbody_dunning_reminder']);
                    file_put_contents(storage_path('app/dunning-reminder-header.txt'), request('data')['dunning_reminder_header']);
                    file_put_contents(storage_path('app/filename-dunning-reminder.txt'), request('data')['filename_dunning_reminder']);

                    // 2. Zahlungsaufforderung

                    file_put_contents(storage_path('app/email-subject-dunning-demand.txt'), request('data')['mailsubject_dunning_demand']);
                    file_put_contents(storage_path('app/email-body-dunning-demand.txt'), request('data')['mailbody_dunning_demand']);
                    file_put_contents(storage_path('app/dunning-demand-header.txt'), request('data')['dunning_demand_header']);
                    file_put_contents(storage_path('app/filename-dunning-demand.txt'), request('data')['filename_dunning_demand']);

                    // 3. Mahnung

                    $editor->setKey('CC_DUNNING', request('data')['cc_dunning']);
                    file_put_contents(storage_path('app/email-subject-dunning-dun.txt'), request('data')['mailsubject_dunning_dun']);
                    file_put_contents(storage_path('app/email-body-dunning-dun.txt'), request('data')['mailbody_dunning_dun']);
                    file_put_contents(storage_path('app/dunning-dun-header.txt'), request('data')['dunning_dun_header']);
                    file_put_contents(storage_path('app/filename-dunning-dun.txt'), request('data')['filename_dunning_dun']);

                    $editor->save();
                    return response()->json($response);

                } elseif(1 == request('app')) {

                    $editor->setKey('PLUGIN_FARE', request('data.plugin_fare') ? 1 : 0);

                    $editor->save();
                    return response()->json($response);
                }

                

            });

            Route::get('create/{repository}/{form?}', 'Html\Autoflow\PHPXPress\FormsController@create');
            Route::get('edit/{repository}/{row}/{form?}', 'Html\Autoflow\PHPXPress\FormsController@edit');
            Route::get('{form}/{repository?}/{row?}', 'Html\Autoflow\PHPXPress\FormsController@show');

        });

endif;

#\Auth::routes();
