<?php

namespace Soft_Tehnica\Freya_Sync_Service\Data;

use Soft_Tehnica\Freya_Sync_Service\Services\AddressService;
use Soft_Tehnica\Freya_Sync_Service\Services\SessionService;

if (!class_exists('FsShippingMethod')) {
    class FsShippingMethod extends \WC_Shipping_Method
    {
        public function __construct(int $instance_id = 0)
        {
            $this->id = 'fs_shipping_method';
            $this->method_title = 'Freya Sync - Livrare';
            $this->method_description = 'Aceasta este metoda de plată adaugată de Freya Sync pentru livrare';
            $this->supports = array('shipping-zones');
            $this->plugin_id = 'freya_sync_service_';

            $this->title = 'Livrare';

            parent::__construct($instance_id);
        }

        public function calculate_shipping($package = array()): void
        {
            if (SessionService::get()->isPickup()) {
                return;
            }

            $address = SessionService::get()->getAddress();
            $locationUid = SessionService::get()->getLocationUid();

            if (isset($address) && isset($locationUid)) {
                $data = makeHttpPost('api/wp/getLocationSettings', [
                    'lat' => $address->lat,
                    'lon' => $address->lon,
                    'locationUid' => $locationUid,
                    'companyUid' => $address->companyUid
                ]);
                if ($data->status) {
                    $taxData = json_decode(json_encode($data->payload->taxes), true);
                    AddressService::get()->saveTaxes($taxData);
                }
            }

            $taxData = SessionService::get()->getTax();

            if (!isset($taxData)) {
                return;
            }

            /** @var PromoFee|null $activePromo */
            $activePromo = null;

            if (count($taxData->promoFees) > 0) {
                usort($taxData->promoFees, function (PromoFee $a, PromoFee $b) {
                    return $a->threshold <=> $b->threshold;
                });

                foreach ($taxData->promoFees as $promo) {
                    $PROMO_GOOD = isset($activePromo)
                        ? $promo->fee < $activePromo->fee
                        : $promo->fee < $taxData->cost;

                    if ((float)$package['cart_subtotal'] >= $promo->threshold && $PROMO_GOOD) {
                        $activePromo = $promo;
                    }
                }
            }

            if (is_null($activePromo)) {
                $tax = $taxData->cost;
            } else {
                $tax = $activePromo->fee;
            }

            if ($tax === 0.) {
                $this->add_rate([
                    'id' => $this->id,
                    'label' => 'Livrare gratis',
                    'cost' => $tax,
                    'calc_tax' => 'per_order'
                ]);
                return;
            }

            $this->add_rate([
                'id' => $this->id,
                'label' => $this->title,
                'cost' => number_format($tax, 2, '.', ''),
                'taxes' => false,
            ]);
        }
    }
}
