<?php
namespace App\Services;


use App\User;
use App\Models\Product;
use App\Mail\MailCheckout;
use App\Models\ProductBuy;
use App\Models\ShoppingOrder;
use App\Models\UserPayCredit;
use App\Models\ShoppingPayment;
use App\Models\UserCreditMargin;
use App\Models\PromotionUserOrder;
use Illuminate\Support\Facades\Mail;

class Payment
{

    public static $txaction_text = [
        'paid' => "bezahlt",
        'open' => "offen",
        'appointed' => "offen (appointed)",
        'failed' => "abbruch",
        'extern' => "extern",
        'invoice_open' => "Re. offen",
        'invoice_paid' => "Re. bezahlt",
        'invoice_non' => "Re. keine Zahlung",
        'non' => "keine Zahlung (non)",
        'NULL' => 'keine Zahlung',
        'prev' => "keine Zahlung (prev)",
    ];

    public static $txaction_invoice = [
        'open' => "offen",
        'paid' => "bezahlt",
        'non' => "keine Zahlung",
        /*'open_vor' => "Vorkasse offen",
        'paid_vor' => "Vorkasse bezahlt",
        'non_vor' => "Vorkasse keine Zahlung",
        'invoice_open' => "Rechung offen",
        'invoice_paid' => "Rechung bezahlt",
        'invoice_non' => 'Rechung keine Zahlung',*/

    ];

    public static $txaction_color = [
        'appointed' => "warning",
        'failed' => "danger",
        'extern' => "success",
        'open' => "warning",
        'paid' => "success",
        'non' => "danger",
        'open_vor' => "warning",
        'paid_vor' => "success",
        'non_vor' => "danger",
        'invoice_open' => "warning",
        'invoice_paid' => "success",
        'invoice_non' => "danger",
        'prev' => "warning",
    ];

  
    public static function getFormattedTxaction($txaction){
        if($txaction && isset(self::$txaction_text[$txaction])){
            return self::$txaction_text[$txaction];
        }
        return self::$txaction_text['NULL'];
    }

    public static function getFormattedTxactionColor($txaction){
        if($txaction && isset(self::$txaction_color[$txaction])){
            return self::$txaction_color[$txaction];
        }
        return "warning";
    }
    public static function generateNextInvoiceNumber(){
        $invoice_number = \App\Models\Setting::getContentBySlug('invoice-number');
        return $invoice_number;

    }

    public static function getShoppingOrderBadge(ShoppingOrder $shopping_order){
        if($shopping_order->mode === 'test'){
            return '<span class="badge badge-pill badge-default">'.strtoupper($shopping_order->mode).' - '.self::getFormattedTxaction($shopping_order->txaction).'</span>';
        }
        if($shopping_order->mode === 'dev'){
            return '<span class="badge badge-pill badge-info">'.strtoupper($shopping_order->mode).' - '.self::getFormattedTxaction($shopping_order->txaction).'</span>';
        }
        return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_order->txaction).'">'.self::getFormattedTxaction($shopping_order->txaction).'</span>';
    }

    public static function getPaymentForTypeBadge(ShoppingOrder $shopping_order){
        return '<span class="badge badge-pill badge-'.$shopping_order->getPaymentForColor().'">'.$shopping_order->getPaymentForType().'</span>';

    }

    public static function getShoppingPaymentBadge(ShoppingPayment $shopping_payment){
        if($shopping_payment->mode === 'test'){
            return '<span class="badge badge-pill badge-default">'.strtoupper($shopping_payment->mode).' - '.self::getFormattedTxaction($shopping_payment->txaction).'</span>';
        }
        return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_payment->txaction).'">'.self::getFormattedTxaction($shopping_payment->txaction).'</span>';
    }

    public static function addUserPayCredits(User $user, $credit, $status, $message, $shopping_order_id = null){
            UserPayCredit::create([
                'user_id' => $user->id,
                'credit' => $credit,
                'old_credit_total' => $user->payment_credit,
                'new_credit_total' => $user->payment_credit + $credit,
                'message' => $message,
                'status' => $status,
                'shopping_order_id' => $shopping_order_id,
            ]);
            $user->payment_credit = $user->payment_credit + $credit;
            $user->save();
    }


    public static function addUserCreditMargin(User $user, $credit, $status, $message){
        UserCreditMargin::create([
            'user_id' => $user->id,
            'credit' => $credit,
            'message' => $message,
            'status' => $status,
        ]);
    }

    public static function addProductBuy(User $user, Product $product){

        if($product->max_buy && $product->max_buy_num > 0){
            $ProductBuy = ProductBuy::where('auth_user_id', $user->id)->where('product_id', $product->id)->first();
            if(!$ProductBuy){
                ProductBuy::create([
                    'auth_user_id' => $user->id,
                    'product_id' => $product->id,
                    'num' => 1,
                ]);
            }else{
                $ProductBuy->num = $ProductBuy->num+1;
                $ProductBuy->save();
            }
        }
    }
    /**/
    public static function paymentStatusPaidAction(ShoppingOrder $shopping_order, $paid){
        $send_link = false;

        $shopping_order->setUserHistoryValue(['status' => 8]);
        Shop::userOrders();
        $shopping_order->paid = $paid;
        $shopping_order->save();

        //if product has actions
        if($shopping_order->shopping_order_items && $shopping_order->auth_user_id){
            foreach($shopping_order->shopping_order_items as $shopping_order_item){
                if($shopping_order_item->product){
                    //add product when buy
                    $user = User::findOrFail($shopping_order->auth_user_id);

                    if($shopping_order_item->product->max_buy && $shopping_order_item->product->max_buy_num > 0){
                        self::addProductBuy($user, $shopping_order_item->product);
                    }
                    //product action
                    if($shopping_order_item->product->action){
                        $user->save();
                        $send_link = true;
                        //new date
                        $date = \Carbon::now()->modify('1 year');
                        if($user->payment_account && $user->daysActiveAccount()>0){
                            $date = \Carbon::parse($user->payment_account)->modify('1 year');
                        }
                        foreach ($shopping_order_item->product->action as $do){
                            if($shopping_order_item->product->getActionName($do) === 'payment_for_account' && !$shopping_order_item->handle){
                               // $user->payment_order_id = $shopping_order_item->product->id; //34
                                $user->payment_account = $date;
                                $user->wizard = 100;
                                $user->save();
                                self::addUserPayCredits($user, $shopping_order_item->product->price, 1, 'payment_for_account', $shopping_order->id);     
                                $shopping_order_item->handle = true;        
                                $shopping_order_item->save();           
                                $shopping_order->setUserHistoryValue(['status' => 9]);
                                
                            }
                            if($shopping_order_item->product->getActionName($do) === 'charging_credits' && !$shopping_order_item->handle){                        
                                 self::addUserPayCredits($user, ($shopping_order_item->product->price * $shopping_order_item->qty), 7, 'charging_credits_add', $shopping_order->id);       
                                 $shopping_order_item->handle = true;        
                                 $shopping_order_item->save();                                
                                 $shopping_order->setUserHistoryValue(['status' => 9]);
                             }
                            
                            /*if($shopping_order_item->product->getActionName($do) === 'payment_for_shop'){
                                $user->payment_order_id = $shopping_order_item->product->id; //35
                                $user->payment_shop = $date;
                                $user->wizard = 100;
                                $shopping_order->setUserHistoryValue(['status' => 9]);
                            }
                            if($shopping_order_item->product->getActionName($do) === 'payment_for_shop_upgrade'){
                                if($shopping_order_item->product->upgrade_to_id){
                                    $user->payment_order_id = $shopping_order_item->product->upgrade_to_id;
                                }
                                $user->payment_shop = $user->payment_account; //same Date, is upgrade
                                $shopping_order->setUserHistoryValue(['status' => 9]);
                            }
                            if($shopping_order_item->product->getActionName($do) === 'payment_for_lead_upgrade'){
                                if($shopping_order_item->product->upgrade_to_id){
                                    $user->m_level = $shopping_order_item->product->upgrade_to_id;
                                }
                            }*/
                            //$user->save();
                        }
                    }
                }

            }
        }
         //if the order has action
         if(($shopping_order->shopping_user->is_from === 'user_order' || $shopping_order->shopping_user->is_from === 'shopping') && $shopping_order->shopping_order_margin){
             //is margin -> set paid
             $shopping_order->shopping_order_margin->order_paid = true;
             $shopping_order->shopping_order_margin->save();
         }
        return $send_link;
    }

    public static function handelPromotionProduct(ShoppingOrder $shopping_order){
        //add the Promotion Product to Order
        $shopping_order = ShoppingOrder::find($shopping_order->id);
        foreach($shopping_order->shopping_order_items as $shopping_order_item){
            if($shopping_order_item->isFreeProduct()){
                if($promotion_user_product = $shopping_order_item->promotion_user_product){
                    $promotion_admin_product = $promotion_user_product->promotion_admin_product;
                    $PromotionUserOrder = PromotionUserOrder::create([
                        'promotion_admin_id' => $promotion_user_product->promotion_admin_id,
                        'promotion_user_id' => $shopping_order->promotion_user_id,
                        'promotion_user_product_id' => $promotion_user_product->id,
                        'product_id' => $promotion_user_product->product_id,
                        'shopping_order_item_id' => $shopping_order_item->id,
                        'shopping_order_id' => $shopping_order->id,
                        'shopping_user_id' => $shopping_order->shopping_user_id,
                        'qty' => $shopping_order_item->qty,
                        'price' => $promotion_admin_product->getPriceWith(false),
                        'price_net' => $promotion_admin_product->getPriceWith(true),
                        'tax_rate' => $promotion_admin_product->product->tax,
                        'status' => 0,
                        'pick_up' => $shopping_order->isPickUp()
                    ]);

                    $promotion_user_product->open_items -= $PromotionUserOrder->qty;
                    $promotion_user_product->sell_items += $PromotionUserOrder->qty;
                    $promotion_user_product->used_budget_total += $PromotionUserOrder->price;
                    $promotion_user_product->save();
            
                    //Guthaben abziehen wenn nicht abholung
                    if(!$shopping_order->isPickUp()){
                        self::addUserPayCredits($promotion_user_product->promotion_user->user, ($PromotionUserOrder->price*-1), 5, 'promotion_order_deduction', $shopping_order->id);                            
                    }
                }
            }
        }
    }
    
     //remove or add form credit, is from Charging credits, handle is true (by paymentStatusPaidAction first action by paid)
    public static function handelUserPayChargingCredits(ShoppingOrder $shopping_order, $action){
        //only from cr <- credit Charging 
        if($shopping_order->shopping_user->is_for !== 'cr'){
            return;
        }
        if($shopping_order->shopping_order_items && $shopping_order->auth_user_id){
            foreach($shopping_order->shopping_order_items as $shopping_order_item){
                if($shopping_order_item->product){
                    $user = User::findOrFail($shopping_order->auth_user_id);
                    //product action
                    if($shopping_order_item->product->action){                       
                        foreach ($shopping_order_item->product->action as $do){
                            if($shopping_order_item->product->getActionName($do) === 'charging_credits' && $shopping_order_item->handle){         
                                if($action === 'remove'){
                                    self::addUserPayCredits($user, ($shopping_order_item->product->price*-1), 8, 'charging_credits_remove', $shopping_order->id);       
                                }
                                if($action === 'add'){
                                    self::addUserPayCredits($user, $shopping_order_item->product->price, 7, 'charging_credits_add', $shopping_order->id);       
                                } 
                             }
                        }
                    }
                }
            }
        }
    }

    //remove form credit, every sale fnc / vor / etc from CheckoutController
    //when done, put it back SalesController
    public static function handelUserPayCredits(ShoppingOrder $shopping_order, $do){
        //is payment credit, deduction or  return
        if(!$shopping_order->shopping_order_margin){
            return;
        }
        if($do === 'deduction'){
            if($shopping_order->shopping_order_margin->from_payment_credit > 0){
                $credit = $shopping_order->shopping_order_margin->from_payment_credit * -1;
                self::addUserPayCredits($shopping_order->auth_user, $credit, 2, 'user_order_deduction', $shopping_order->id);                            
            }
        }
        if($do === 'return'){
            if($shopping_order->shopping_order_margin->from_payment_credit > 0){
                $credit = $shopping_order->shopping_order_margin->from_payment_credit;
                self::addUserPayCredits($shopping_order->auth_user, $credit, 4, 'user_order_return', $shopping_order->id);                            
            }
        } 
    }

    public static function handelUserPromotionOrder(ShoppingOrder $shopping_order){
        //no user promotion
        if($shopping_order->payment_for !== 7 || !$shopping_order->promotion_user){
            return;
        }
        if($shopping_order->promotion_user->promotion_user_orders){
            foreach($shopping_order->promotion_user->getPromotionUserOrders($shopping_order->id) as $promotion_user_order){
                $promotion_user_order->setStatusShipped($shopping_order->getAPIShippedType());
                if(!$promotion_user_order->pick_up){ // keine abholung handel credit
                    $last_UserPayCredit = UserPayCredit::where('shopping_order_id', $shopping_order->id)->whereIn('status', [5, 6])->orderBy('id', 'DESC')->first();
                    if($last_UserPayCredit && $promotion_user_order->status === 10 && $last_UserPayCredit->status === 5){
                        Payment::handelUserPayCreditsPromotion($promotion_user_order, 'return');
                    }
                    //Status Zahlung, voher gab es eine Storno, Guthaben abziehen wenn status 6 / return from order
                    if($last_UserPayCredit && $promotion_user_order->status === 0 && $last_UserPayCredit->status === 6){
                        Payment::handelUserPayCreditsPromotion($promotion_user_order, 'deduction');
                    }
                }
            }
        }
    }

    public static function handelUserShopOrder(ShoppingOrder $shopping_order){
        //no user shop
        if($shopping_order->payment_for !== 8 || !$shopping_order->user_shop){
            return;
        }
        // need something to do?
    }

     //add or remove form credit, 
    //when done, put it back SalesController
    public static function handelUserPayCreditsPromotion(PromotionUserOrder $promotion_user_order, $do){
        //is promotion pick up, dont
        if($promotion_user_order->pick_up){
            return;
        }
        if($do === 'deduction'){
            if($promotion_user_order->price > 0){
                $credit = $promotion_user_order->price * -1;
                self::addUserPayCredits($promotion_user_order->promotion_user->user, $credit, 5, 'promotion_order_deduction', $promotion_user_order->shopping_order->id);                            
            }
        }
        if($do === 'return'){
            if($promotion_user_order->price > 0){
                $credit = $promotion_user_order->price;
                self::addUserPayCredits($promotion_user_order->promotion_user->user, $credit, 6, 'promotion_order_return', $promotion_user_order->shopping_order->id);                            
            }
        }
    
    }

    public static function paymentStatusSendMail(ShoppingOrder $shopping_order, $shopping_payment, $data)
    {
        $billing_email = self::determineBillingEmail($shopping_order, $data);
        $bcc = self::determineBccRecipients($shopping_order, $data);

        try {
            Mail::to($billing_email)
                ->bcc($bcc)
                ->send(new MailCheckout(
                    $data['txaction'], 
                    $shopping_order, 
                    $shopping_payment, 
                    $data['send_link'], 
                    $data['mode']
                ));
        } catch (\Exception $e) {
            \Log::error('Fehler beim E-Mail-Versand: ' . $e->getMessage());
        }
    }

    private static function determineBillingEmail($shopping_order, $data)
    {
        if (Util::isTestSystem()) {
            return config('app.checkout_test_mail');
        }

        $billing_email = $shopping_order->shopping_user->billing_email;
        if (!$billing_email) {
            return $data['mode'] === 'test' 
                ? config('app.checkout_test_mail')
                : config('app.checkout_mail');
        }

        return $billing_email;
    }

    private static function determineBccRecipients($shopping_order, $data) 
    {
        $bcc = [];
        
        // Add checkout email to BCC
        $bcc[] = $data['mode'] === 'test'
            ? config('app.checkout_test_mail')
            : config('app.checkout_mail');

        // Add member email to BCC if applicable
        if ($data['mode'] !== 'test' 
            && !Util::isTestSystem()
            && !$shopping_order->shopping_user->is_like 
            && $shopping_order->shopping_user->member
        ) {
            $bcc[] = $shopping_order->shopping_user->member->email;
        }

        return $bcc;
    }
}
