<?php 
namespace PortalPeople\magento\models;

use common\components\cart\CartLineRecalculationTrait;
use common\components\cart\DeliveryLineSyncService;
use Yii;    
use backend\models\Cartsbe;
use PortalPeople\netsuite\components\NetSuite;
use yii\helpers\Inflector;

class Carts extends Cartsbe
{
    use CartLineRecalculationTrait;

    private const DELIVERY_PRODUCT_ID = '331D4D9B-7F11-9473-1279-CAFDA629360A';

    public function rules() : array
    {
        $rules = parent::rules();
        $rules[] = [['account_code'], 'default', 'value' => 'GAR001'];
        //$rules[] = [['paymentmethod'], 'default', 'value' => 'QVC'];
        $rules[] = [['data'], 'safe'];
        return $rules;
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $this->CreateDeliveryLines();
        if ($this->status == 'Paid') {
            Yii::$app->trigger('cart-order-sendtonetsuite', ($event = new \common\events\UserDataEvent(['model' => $this])));
        }
    }

    public function CreateDeliveryLines(): array
    {
        if ($this->status !== 'Paid' || is_object($this->shipment) !== true) {
            return [];
        }

        $shippingcosts = \PortalPeople\shippingcosts\models\Shippingcosts::costs($this->id);
        $shippingline = $this->shippingline;

        return DeliveryLineSyncService::syncByHaulier(
            $this,
            $shippingcosts,
            function ($cartline, $haulier, array $data, bool $isNew) use ($shippingline): array {
               $attributes = [
                    'haulierint' => $haulier,
                    'cost' => $data['cost'],
                    'costtotal' => $data['cost'],
                    'product_description' => $shippingline?->product_description,
                    'hidden_info' => $data['haulier'] . ' Delivery ' . Inflector::pluralize($data['pallets'] . ' Pallet'),
                ];

                if ($isNew) {
                    $attributes['requested_date'] = $shippingline?->requested_date;
                    $attributes['qty'] = 1;
                    $attributes['erpqty'] = 1;
                    $attributes['price'] = 0;
                    $attributes['linetotal'] = 0.00;
                    $attributes['paid'] = true;
                }

                return $attributes;
            },
            [
                'productId' => '331D4D9B-7F11-9473-1279-CAFDA629360A',
                'deleteMissing' => false,
            ]
        );
    }
    
    public static function NewMagentoOrder($data) {
        // Reject orders that have not been paid (e.g. invoice sent but awaiting payment)
        $paymentMethod = $data['payment']['method'] ?? null;
        if ($paymentMethod === 'stripe_payments_invoice') {
            Yii::warning('Order rejected: payment method stripe_payments_invoice is awaiting payment.', 'magento');
            return null;
        }

        $cartClass = Yii::$app->getModule('magento')->cartClass ?? self::class;
        $json = new yii\db\expression("json_value(data, '$.magento.orderid')"); 
        if ($cartClass::find()->where(['=', $json, $data['order']['id']])->exists()) {
            Yii::warning('Order rejected: order with Magento order ID ' . $data['order']['id'] . ' already exists.', 'magento');
            return null;
        }
        $model = new $cartClass();
        $model->sourceurl = 'www.gardoo.co.uk';
        $model->id = $model::tempId();
        $model->status = 'Paid';
        $model->dateordered = strtotime($data['order']['updated_at']);
        //$model->currency = $data['currency'];
        $model->email = $data['customer']['email'];
        $model->contact = $data['customer']['firstname'] . ' ' . $data['customer']['lastname'];
        $fulladdresses = $model->fulladdresses ?? [];
        //$model->telephone = $data['customer']['telephone'];
        $billingAddress = New \backend\models\Address();
        $billingAddress->address1 = $data['billing_address']['street'];
        $billingAddress->town = $data['billing_address']['city'];
        $billingAddress->postcode = $data['billing_address']['postcode'];
        $billingAddress->telephone = $data['billing_address']['telephone'];
        
        $shippingAddress = New \backend\models\Address();
        $shippingAddress->address1 = $data['shipping_address']['street'];
        $shippingAddress->town = $data['shipping_address']['city'];
        $shippingAddress->postcode = $data['shipping_address']['postcode'];
        $shippingAddress->telephone = $data['shipping_address']['telephone'];
        $fulladdresses['billing'] = $billingAddress;
        $fulladdresses['shipping'] = $shippingAddress;
        $model->fulladdresses = $fulladdresses;
        foreach ($data['items'] as $item) {
            $product = \backend\models\Productsbe::find()->where(['stock_code' => $item['sku']])->one();
            if ($product) {
                $cartline = new \backend\models\Cartlines();
                $cartline->basketid = $model->id;
                $cartline->productid = $product->id;
                $cartline->product_name = $product->data->magento->name ?? $item['name'] ?? $product->product_name;
                $cartline->product_description = $product->data->magento->description ?? $item['description'] ?? $product->product_description;
                $cartline->qty = $item['qty_ordered'];
                $cartline->price = $item['row_total_incl_tax'] / $item['qty_ordered'];
                $cartline->dispatch = 0;
                $cartline->requested_date = $data['shipping_fields']['shipping_date'] ?? null;
                if ($item['discount_amount'] > 0) {
                    $cartline->disc = $item['discount_amount'] / $item['qty_ordered'];
                }
                $cartline->save();
            }
        }
        $shippingDate = $data['shipping_fields']['shipping_date'] ?? null;
        $shippingW3w = $data['shipping_fields']['shipping_w3w'] ?? null;
        $shippingMessage = $data['shipping_fields']['shipping_message'] ?? null;
        $model->delivery_date = $shippingDate;
        $model->delivery_message = $shippingMessage;
        $magento = $model->data->magento ?? new \PortalPeople\magento\models\carts\Magento();
        $magento->orderid = $data['order']['id'];
        $magento->shipping_date = $shippingDate;
        $magento->shipping_w3w = $shippingW3w;
        $magento->shipping_message = $shippingMessage;
        //   $model->extended->OrderNo = $data['order']['id'];
        $cartsData = new \backend\models\CartsData();
        $cartsData->magento = $magento;
        $model->data = $cartsData;
        $shipment = new \backend\models\Shipment();
        $shipment->shipment_type = 0;
        $shipment->cart_id = $model->id;
        $shipment->delivery = $data['shipping_method']['description'] == 'Free Delivery (2 - 4 Working Days) - Fixed' ? 'ECO' : null;
        $shipment->shipment_date = $data['shipping_fields']['shipping_date'] ?? null;
        $shipment->save();
        if (array_key_exists('method', $data['payment'])) {
            $method = $data['payment']['method'];
        }
        if ($method == 'paypal_express') {
            /*
            $payment = [  
                'additional_information' => [
                    'paypal_express_checkout_shipping_overridden' => 1,
                    'paypal_express_checkout_shipping_method' => '',
                    'paypal_payer_id' => 'GGJBCYW29E7QJ',
                    'paypal_payer_email' => 'a.pickstock-buyer@chalvingtongroup.com',
                    'paypal_payer_status' => 'verified',
                    'paypal_address_status' => 'Confirmed',
                    'paypal_correlation_id' => '870eccb513950',
                    'paypal_express_checkout_payer_id' => 'GGJBCYW29E7QJ',
                    'paypal_express_checkout_token' => 'EC-7CW880928Y410140E',
                    'method_title' => 'PayPal Express Checkout',
                    'paypal_express_checkout_redirect_required' => null,
                    'paypal_protection_eligibility' => 'Eligible',
                    'paypal_payment_status' => 'pending',
                    'paypal_pending_reason' => 'authorization',
                ],
            ];*/
            if (array_key_exists('payment', $data) && array_key_exists('additional_information', $data['payment']) && array_key_exists('paypal_pending_reason', $data['payment']['additional_information'])) {
                $paymentStatus = $data['payment']['additional_information']['paypal_pending_reason'];
            }
            if (array_key_exists('payment', $data) && array_key_exists('additional_information', $data['payment']) && array_key_exists('paypal_transaction_id', $data['payment']['additional_information'])) {
                $paymentRef = $data['payment']['additional_information']['paypal_transaction_id'];
            }
            $pay = new \backend\models\Paymentresponsesbe();
            $pay->basketid = $model->id;
            $pay->paymentmethod = 'PayPal';
            $pay->status = $paymentStatus == 'authorization' ? 'Paid' : 'Pending';
            $pay->paymentref = $paymentRef;
            $pay->source = $data['order_source'];
            $pay->amount = $data['order']['grand_total'];
            $pay->save();
        } elseif (in_array($method, ['stripe_payments', 'stripe_payments_express'])) {
            $pay = new \backend\models\Paymentresponsesbe();
            $paymentRef = '';
            if (array_key_exists('payment', $data) && array_key_exists('additional_information', $data['payment']) && array_key_exists('is_transaction_pending', $data['payment']['additional_information'])) {
                $paymentStatus = $data['payment']['additional_information']['is_transaction_pending'] == false ? 'Paid' : 'Pending';
                if (array_key_exists('server_side_transaction_id', $data['payment']['additional_information'])) {
                    $paymentRef = $data['payment']['additional_information']['server_side_transaction_id'];
                }
            }
            if (array_key_exists('payment', $data) && array_key_exists('additional_information', $data['payment']) && array_key_exists('payment_intent_id', $data['payment']['additional_information'])) {
                $paymentRef = $data['payment']['additional_information']['payment_intent_id'];
            }
            $pay->basketid = $model->id;
            $pay->paymentmethod = 'Stripe';
            $pay->status = $paymentStatus;
            $pay->paymentref = $paymentRef;
            $pay->source = $data['order_source'];
            $pay->amount = $data['order']['grand_total'];
            $pay->save();
        
        } 
        if (isset($pay) && $pay->status == 'Paid') {
            $model->billingstatus = 'Paid';
        }
        $model->save();
        $model->refresh();
        $attributes = $model->attributes;
        $attributes['shipping_fields'] = [
            'shipping_date' => $shippingDate,
            'shipping_w3w' => $shippingW3w,
            'shipping_message' => $shippingMessage,
        ];

        return $attributes;
    }
}