<?php

namespace App\Models\PHPXPress;

use App\Models\Model;
use App\Models\NestedModel;
use Laravel\Scout\Searchable;
use App\Custom\Models\PHPXPress AS Custom;

class HwplusInvoices extends Model {


    use Searchable;
    use Custom\HwplusInvoices;

    protected $table = 'hwplus_invoices';
    protected $connection = 'phpxpress';
    public $timestamps = false;
    protected $primaryKey = 'ID';
    protected $fillable = [];
    public static $id = '27b96af59ee924f9ec98cf9c44b54e06219636c1';
    public $incrementing = false;

    protected $appends = [
        'short_name',
        'remind_level'
    ];

    public function toSearchableArray()
    {
        return [
            'commission_number' => '',
            'descriptor' => '',
            'invoice_number' => ''
            //'hwplus_invoice_items.descriptor' => '',
        ];
    }

    public function getTicketAttribute($ticket) {
        if(!$ticket) return new \App\Models\PHPXPress\HwplusInvoices;
        return \Runtime::make('hwplus_tickets')->findOrFail($ticket);
    
    }

    public function getShortNameAttribute() {
        switch($this->descriptor) {

            case "Rechnung":
                if($this->_reverse_invoice) return "RG (S)";
                elseif($this->_adjusted_invoice) return "RG (K)";
                else return "RG";
                break;
            case "Stornorechnung": return "SRG"; break;
            case "Korrekturrechnung": return "KRG"; break;
            default: throw new \Exception('invalid document type');
        }
    }

    public function getRemindLevelAttribute() {
        if($this->date_dunning_letter) {

            $level = 3 ;

        } elseif($this->date_demand_for_payment ) {

            $level = 2;

        } elseif($this->date_payment_reminder) {

            $level = 1;

        } else {

            $level = 0;

        }

        return $level;
    }
    
    public function createInvoiceNumber() {



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

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

        
        // 20250001
        $max = \App\Models\PHPXPress\HwplusInvoices::max('invoice_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['_client'] = $this->_client;
        $data['date'] = (new \Carbon\Carbon($this->date))->format('d.m.Y');
        $data['service_date'] = (new \Carbon\Carbon($this->service_date))->format('d.m.Y');

        $data['date_payment_reminder'] =  (new \Carbon\Carbon($this->date_payment_reminder))->format('d.m.Y');
        $data['date_demand_for_payment'] =  (new \Carbon\Carbon($this->date_demand_for_payment))->format('d.m.Y');
        $data['date_dunning_letter'] =  (new \Carbon\Carbon($this->date_dunning_letter))->format('d.m.Y');



        $data['net'] = str_replace('.', ',', $this->net);
        $data['gross'] = str_replace('.', ',', $this->gross);

        if($data['_ticket'] = $this->_ticket) {

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


        }

        if('Stornorechnung' == $this->descriptor) {
        
            $data['_reverse_invoice'] = \Runtime::make('hwplus_invoices')->where('_reverse_invoice', $this->getKey())->first();
            $data['_reverse_invoice']->date = (new \Carbon\Carbon($data['_reverse_invoice']->date))->format('d.m.Y');
        }
        
        $customer = \App\Models\PHPXPress\HwplusClients::with('_payment_term')
            ->whereHas('_meta._doctype', function($query) {
                $query->where('identifier', 'new_client');
            })
            ->where('customer_id', $this->customer_id)
            ->first();
        
        $data['due_date'] = (new \Carbon\Carbon($this->date))->addDays($customer->_payment_term->due_date)->format('d.m.Y');
        $data['date_to_remind'] = (new \Carbon\Carbon($this->date))->addDays($customer->_payment_term->days_to_remind)->format('d.m.Y');
        $data['date_to_demand'] = (new \Carbon\Carbon($this->date))->addDays($customer->_payment_term->days_to_demand)->format('d.m.Y');
        $data['date_to_dun'] = (new \Carbon\Carbon($this->date))->addDays($customer->_payment_term->days_to_dunning_letter)->format('d.m.Y');
        $data['date_to_cashing'] = (new \Carbon\Carbon($this->date))->addDays($customer->_payment_term->days_to_cashing)->format('d.m.Y');

        if(!$this->invoice_number) $data['invoice_number'] = "[". $this->createInvoiceNumber() . ']';
        
        $data['current_billing_interval'] = function() {
            $start  = \Carbon\Carbon::parse($this->_ticket->date_accept_order);
            $end    = now();
            $period = \Carbon\CarbonPeriod::create($start, $this->billing_rotation, $end);
            
            return $period->last()->format('d.m.Y') . ' - ' . $period->last()->add($this->billing_rotation)->format('d.m.Y');
        };

        return $data;
    
    }

}
