<?php

namespace App\Repositories;

use PDF;
use Storage;
use App\Services\Credit;
use App\Services\MyPDFMerger;
use App\Services\UserMarign;
use App\Models\UserCredit;

use App\User;

class CreditRepository extends BaseRepository {

    public function __construct(User $model)
    {
        $this->model = $model;
    }

    public function create($request = [])
    {
        //need invoice $data
        $credit_number = isset($request['credit_number']) ? $request['credit_number'] :  Credit::getCreditNumber();
        $credit_date = isset($request['credit_date']) ? $request['credit_date'] : \Carbon::now()->format("d.m.Y");
        $credit_send_mail = isset($request['credit_send_mail']) ? true: false;
        $credit_number = Credit::createCreditNumber($credit_number, $credit_date);

        $user_credits = $this->makeUserCredit();

        $data = [
            'user' => $this->model,
            'credit_date' => $credit_date,
            'credit_number' => $credit_number,
            'user_credits' => $user_credits,
        ];

        $pdf = PDF::loadView('pdf.credit', $data);
        $pdf->setPaper('A4', 'portrait');

        $dir = Credit::getCreditStorageDir($credit_date);

        if(!Storage::disk('public')->exists( $dir )){
            Storage::disk('public')->makeDirectory($dir); //creates directory
        }
        $path = Storage::disk('public')->path('');
        $filename = Credit::makeCreditFilename($credit_number);

        $pdf->save($path.$dir.$filename);
        
        $pdfMerger = new MyPDFMerger();
        $pdfMerger->addPDF($path.$dir.$filename);
        $file = $pdfMerger->myMerge('string', $filename, 'template_invoice_de');
        Storage::disk('public')->put($dir.$filename, $file);


        $credit_file = [
                'filename' => $filename,
                'dir' => $dir,
                'disk' => 'public',
                'credit_number' => $credit_number,
                'credit_date' => $credit_date,
        ];
        $user_credit = UserCredit::create([
            'auth_user_id' => $this->model->id,
            'credit_number' => $credit_number,
            'net' => $user_credits->net,
            'tax_rate' => $user_credits->tax_rate,
            'tax' => $user_credits->tax,
            'total' => $user_credits->total,
            'date' => $credit_date,
            'credit' => $credit_file,
            'user_margins' => $user_credits->margins,
            'user_credits' => $user_credits->credits,
        ]);

       

        if($credit_send_mail){
            Credit::sendCreditMail($user_credit);
        }
        $this->finishUserCredit($user_credit);
        return true;
    }

    //beendet die Gutschrift
    private function finishUserCredit($user_credit){
        //next number
        Credit::makeNextCreditNumber();
        //Partner Provision shopping order margin   
        $ShoppingOrderMargins = UserMarign::getPartnerCommissionItems($this->model->id, false);
        foreach($ShoppingOrderMargins as $ShoppingOrderMargin){
            $ShoppingOrderMargin->partner_commission_paid = true;
            $ShoppingOrderMargin->out_paid = true;
            $ShoppingOrderMargin->user_credit_id = $user_credit->id;
            $ShoppingOrderMargin->save();
        }

         //Shop Provision  shopping order margin
         $ShoppingOrderMargins = UserMarign::getShopCommissionItems($this->model->id, false);
         foreach($ShoppingOrderMargins as $ShoppingOrderMargin){
             $ShoppingOrderMargin->margin_paid = true;
             $ShoppingOrderMargin->out_paid = true;
             $ShoppingOrderMargin->user_credit_id = $user_credit->id;
             $ShoppingOrderMargin->save();
         }

        //Hinzugefügte Provision user credit margin
        $UserCreditMargins = UserMarign::getUserCreditMarginByUserID($this->model->id);
        foreach($UserCreditMargins as $UserCreditMargin){
            $UserCreditMargin->paid = true; //wurde ausgezahlt
            $UserCreditMargin->user_credit_id = $user_credit->id;
            $UserCreditMargin->save();
        }
    }

    //erstellt der Gutschrift
    private function makeUserCredit(){
     
        $ret = new \stdClass();
        $ret->net = 0;
        $ret->margins = [];
        $ret->credits = [];

        //Partner Provision
        $ShoppingOrderMargins = UserMarign::getPartnerCommissionItems($this->model->id, false);
        foreach($ShoppingOrderMargins as $ShoppingOrderMargin){
            $margin = new \stdClass();
            $margin->id = $ShoppingOrderMargin->id;
            $margin->net = $ShoppingOrderMargin->net_partner_commission;
            $margin->reference = $ShoppingOrderMargin->shopping_order->getLastShoppingPayment('reference');
            $margin->firstname = $ShoppingOrderMargin->shopping_order->shopping_user->billing_firstname;
            $margin->lastname = $ShoppingOrderMargin->shopping_order->shopping_user->billing_lastname;
            $margin->created_at = $ShoppingOrderMargin->shopping_order->created_at->format("d.m.Y"); 
            $ret->margins[] = $margin;
            $ret->net += $ShoppingOrderMargin->net_partner_commission;
        }

        //Shop Provision
        $ShoppingOrderMargins = UserMarign::getShopCommissionItems($this->model->id, false);
        foreach($ShoppingOrderMargins as $ShoppingOrderMargin){
            $margin = new \stdClass();
            $margin->id = $ShoppingOrderMargin->id;
            $margin->net = $ShoppingOrderMargin->net_discount;
            $margin->reference = $ShoppingOrderMargin->shopping_order->getLastShoppingPayment('reference');
            $margin->firstname = $ShoppingOrderMargin->shopping_order->shopping_user->billing_firstname;
            $margin->lastname = $ShoppingOrderMargin->shopping_order->shopping_user->billing_lastname;
            $margin->created_at = $ShoppingOrderMargin->shopping_order->created_at->format("d.m.Y"); 
            $ret->margins[] = $margin;
            $ret->net += $ShoppingOrderMargin->net_discount;
        }

        //Hinzugefügte Provision
        $UserCreditMargins = UserMarign::getUserCreditMarginByUserID($this->model->id);
        foreach($UserCreditMargins as $UserCreditMargin){
            $credit = new \stdClass();
            $credit->id = $UserCreditMargin->id;
            $credit->net = $UserCreditMargin->credit;
            $credit->message = $UserCreditMargin->message;
            $credit->created_at = $UserCreditMargin->created_at->format("d.m.Y"); 
            $ret->credits[] = $credit;
            $ret->net += $UserCreditMargin->credit;
        }

        /* taxable_sales  //user tax
        1 //umsatzsteuerpflichtig
        2 // nicht umsatzsteuerpflichtig
        */
        if($this->model->account){
            $ret->taxable = $this->model->account->taxable_sales == 2 ? false : true;
            if($ret->taxable){
                $ret->tax_rate = config('app.main_tax_rate');
                $ret->total = round($ret->net * config('app.main_tax'), 2);
                $ret->tax = $ret->total - $ret->net;

            }else{
                $ret->tax_rate = 0;
                $ret->total = $ret->net;
                $ret->tax = 0;
            }
        }

       return $ret;
    }
}