<?php

namespace App\Models\PHPXPress;

use App\Models\Model;
use App\Models\NestedModel;
use Jackiedo\DotenvEditor\Facades\DotenvEditor;
use App\Custom\Models\PHPXPress AS Custom;

class HwplusTickets extends Model {


    use Custom\HwplusTickets;

    protected $table = 'hwplus_tickets';
    protected $connection = 'phpxpress';
    public $timestamps = false;
    protected $primaryKey = 'ID';
    protected $fillable = [];
    public static $id = 'afe4f16263308b092d15e04719f202efe1326813';
    public $incrementing = false;


    public function _invoice() {

        // Funktioniert nicht, deshalb überall manuess setzen wenn benötigt

        return $this->belongsTo(\App\Models\PHPXPress\HwplusInvoices::class, 'ID', '_ticket');
        return $this->belongsTo(\App\Models\PHPXPress\HwplusInvoices::class, 'IDs', '_tickets');
    }

    public function getAdjustedOfferAttribute($value) {

        if($value) return $this->findOrFail($value);
        else return false;
    }

    public function getAdjustedOfferAtHwplusTicketsAttribute() {

        if($offer = $this->where('_adjusted_offer', $this->getKey())->first()) return $offer;
        else return false;
    }

    public function getShortNameAttribute() {

        switch($this->descriptor) {

            case "Lieferschein": return "LS"; break;
            case "Auftrag": return "AU"; break;
            case "Angebot": return "AN"; break;
            case "Materialangebot": return "MA"; break;
            default: throw new \Exception('invalid document type');

        }


    }
    
    public function createJobNumber() {

        if($this->job_number) return $this->job_number;

        // Strommichel
        return $this->createCustomJobNumber();

        return "Fehler";
        
        // 20250001
        $max = \App\Models\PHPXPress\HwplusTickets::where('descriptor', $this->descriptor)->max('job_number');
        $year = date('Y');
        $maxYear = substr($max, 0, 4);
        if($year == $maxYear) return $max + 1;
        if($year > $maxYear) return (int) str_pad($year,  8, "0") + 1;
        throw new \Exception('have a look');
    }
    
        
    public function prepareBladeData() {
        $data = $this->getAttributes();
        $data['_offer'] = $this->_offer;
        $data['sum'] = number_format((float) str_replace(',', '.', $this->sum), 2, ',', '');
        $data['gross'] = number_format((float) str_replace(',', '.', $this->gross), 2, ',', '');
        $data['date'] = (new \Carbon\Carbon($this->date))->format('d.m.Y');


        $this->date_accept_order ? $data['date_accept_order'] = (new \Carbon\Carbon($this->date_accept_order))->format('d.m.Y') : "";
        $this->date_valid_to ? $data['date_valid_to'] = (new \Carbon\Carbon($this->date_valid_to))->format('d.m.Y') : "";
        $this->date_confirmation ? $data['date_confirmation'] = (new \Carbon\Carbon($this->date_confirmation))->format('d.m.Y') : "";

        if($this->_offer) {
            $data['_offer']->date = (new \Carbon\Carbon($this->_offer->date))->format('d.m.Y');
            $this->_offer->date_accept_order ? $data['_offer']->date_accept_order = (new \Carbon\Carbon($this->_offer->date_accept_order))->format('d.m.Y') : "";
            $this->_offer->date_valid_to ? $data['_offer']->date_valid_to = (new \Carbon\Carbon($this->_offer->date_valid_to))->format('d.m.Y') : "";
            $this->_offer->date_confirmation ? $data['_offer']->date_confirmation = (new \Carbon\Carbon($this->_offer->date_confirmation))->format('d.m.Y') : "";
        }
        if(!$this->job_number) $data['job_number'] = "[". $this->createJobNumber() . ']';
        return $data;
    
    }
    
    public function createInvoice($billing_address, $flagForceNewInvoice=false) {

        if(!$this->job_number) throw new \Exception('Ungültiger Vorgang');
        if($this->_invoice AND !$flagForceNewInvoice) throw new \Exception('Rechnung vorhanden. Es kann keine weitere Rechnung erstellt werden.');
        if($this->_offer_at_hwplus_tickets->first()) throw new \Exception('Ungültiger Vorgang');
        #if($this->_ticket_at_hwplus_standing_orders) throw new \Exception('Ungültiger Vorgang');
            
        $client = \Runtime::make('hwplus_clients')->findOrFail($billing_address);
        
        $inv = new \App\Models\PHPXPress\HwplusInvoices();

        $inv->form = \Runtime::make('forms')->findOrFail('5dfe19c87715ed4ca89abb9f4eb4da4dc060c8bd');
        
        \DB::transaction(function() use ($inv, $client) {
        
            $inv->descriptor = "Rechnung";
            $inv->customer_id = $client->customer_id;
            $inv->_client = $client->getKey();
            $inv->client = $client->descriptor;
            $inv->firstname = $client->firstname;
            $inv->surname = $client->surname;
            $inv->streetadress = $client->streetadress;
            $inv->housenumber = $client->housenumber;
            $inv->postcode = $client->postcode;
            $inv->location = $client->location;
            $inv->email = $client->email;
            $inv->date = date('Y-m-d');
            $inv->service_date = $this->date;
            $inv->commission_number = $this->commission_number;
            $inv->order_number = $this->order_number;
            $inv->note = $this->note;
            $inv->assignment = $this->assignment;
            $inv->_ticket = $this->getKey();
            $inv->_premium_charge = $this->_premium_charge;
                            
            $inv->ID = $inv->getHashId();  
            $inv->save();
            

            $editor = \DotenvEditor::load(storage_path('app/settings.env'));
            #$vat = $editor->getValue('COMPANY_SBLAW') ? 0 : \Runtime::make('hwplus_vat_rates')->where('flag_default', 1)->first()->rate;
            
            $order = 1;
            $form = \Runtime::make('forms')->findOrFail('cba3def15e0e6c1151fe202c8b00c2a0c1951909');
            

            // Arbeitsstunden abrechnen

            foreach(\App\Models\PHPXPress\HwplusStaff::get() AS $staff) {
            
                $whs = $this->_manhours->where('_staff', $staff->getKey())->sortBy('date');
                
                foreach($whs AS $wh) {

                    #dd($wh);

                    $item = new \App\Models\PHPXPress\HwplusInvoiceItems();
                    $item->form = $form;
                    $item->_items_at_hwplus_invoices = $inv->getKey();
                    $item->_items_at_hwplus_invoices_order = $order;
                    $item->descriptor = $wh->descriptor . ' am ' . (new \Carbon\Carbon($wh->date))->format('d.m.Y') . ' durch '. $staff->descriptor;
                    $item->unit = "Std.";
                    $item->amount = $wh->workinghours;
                    $item->netprice = $wh->netprice;
                    $item->vat = $wh->vat ? : 19;
                    $item->sort_order = $order;
                    $item->save();
                
                    $order++;
                }
            }
            
            
            // Nebenleistungen wie Fahrtkosten berechnen
            
            $form = \Runtime::make('forms')->findOrFail('050b070c151f8f0b9d76589922f58a908e67535f');

            if('shipping_order' == $this->_meta->_doctype->identifier) {


                if(!$this->fare);
                else {

                    $item = new \App\Models\PHPXPress\HwplusInvoiceItems();
                    $item->form = $form;
                    $item->_items_at_hwplus_invoices = $inv->getKey();
                    $item->_items_at_hwplus_invoices_order = $order;
                    $item->descriptor = "Lieferpauschale";
                    $item->unit = "Pauschale";
                    $item->amount = $this->fare;
                    #$item->netprice = (float) str_replace(',', '.', $client->fare_rate);
                    $item->netprice = $this->fare_rate;
                    $item->vat = $this->fare_rate_vat;
                    $item->sort_order = $order;
                    $item->save();

                    $order++;

                };


            }

            elseif($amount = $this->_manhours->where('fare', 1)->count()) {

                if($amount) {

                    $item = new \App\Models\PHPXPress\HwplusInvoiceItems();
                    $item->form = $form;
                    $item->_items_at_hwplus_invoices = $inv->getKey();
                    $item->_items_at_hwplus_invoices_order = $order;
                    $item->descriptor = "Fahrtkostenpauschale";
                    $item->unit = "Pauschale";
                    $item->amount = $amount;
                    #$item->netprice = (float) str_replace(',', '.', $client->fare_rate);
                    $item->netprice = $this->fare_rate;
                    $item->vat = $this->fare_rate_vat;
                    $item->sort_order = $order;
                    $item->save();

                    $order++;

                }


            }

            $fareCharges = $this->_fare_charges;

            foreach($fareCharges AS $fareCharge) {

                $item = new \App\Models\PHPXPress\HwplusInvoiceItems();
                $item->form = $form;
                $item->_items_at_hwplus_invoices = $inv->getKey();
                $item->_items_at_hwplus_invoices_order = $order;
                $item->descriptor = $fareCharge->descriptor;
                $item->unit = $fareCharge->_unit->descriptor;
                $item->amount = $fareCharge->amount;
                #$item->netprice = (float) str_replace(',', '.', $client->fare_rate);
                $item->netprice = $fareCharge->netprice;
                $item->vat = $fareCharge->vat;
                $item->sort_order = $order;
                $item->save();

                $order++;

            }

            // Dienstleistungen berechnen

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


            $services = $this->_services;

            foreach($services AS $service) {

                $item = new \App\Models\PHPXPress\HwplusInvoiceItems();
                $item->form = $form;
                $item->_items_at_hwplus_invoices = $inv->getKey();
                $item->_items_at_hwplus_invoices_order = $order;
                $item->descriptor = $service->descriptor;
                $item->unit = $service->_unit->descriptor;
                $item->amount = $service->amount;
                #$item->netprice = (float) str_replace(',', '.', $client->fare_rate);
                $item->netprice = $service->netprice;
                $item->vat = $service->vat;
                $item->sort_order = $order;
                $item->save();

                $order++;

            }


            // Material berechnen

            $form = \Runtime::make('forms')->findOrFail('854cbb63e8c1319f02330c2e61e7b93bf4682cc2');
                            
            foreach($this->_material->sortBy('_material_at_tickets_order') AS $posten) {

                $item = new \App\Models\PHPXPress\HwplusInvoiceItems();
                $item->form = $form;
                $item->_items_at_hwplus_invoices = $inv->getKey();
                $item->_items_at_hwplus_invoices_order = $order;
                $item->descriptor = $posten->descriptor;
                $item->unit = $posten->unit;
                $item->amount = (float) str_replace(',', '.', $posten->amount);
                $item->netprice =  (float) str_replace(',', '.', $posten->netprice);
                $item->vat = $posten->vat;
                $item->sort_order = $order;
                $item->save();
                

                $order++;
                
            }

            #$inv->save();

            $inv = $inv->refresh();

            if((float) str_replace(',', '.', $this->sum) != (float) str_replace(',', '.', $inv->net)) throw new \Exception('Nettobeträge nicht identisch ' . $this->sum . ' --> ' . $inv->net);
            if((float) str_replace(',', '.', $this->gross) != (float) str_replace(',', '.', $inv->gross)) throw new \Exception('Bruttobeträge nicht identisch ' . $this->sum . ' --> ' . $inv->net);


        });
    
        return $inv;
    
    }

}
