<?php

namespace Hilco\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Class PromotionShippingAction
 * @package Hilco\Models
 * @property integer $deliverymethod_id
 * @property integer $deliveryterm_id
 * @property float $discount_percentage
 * @property boolean $use_rewardsexcluded_list
 */
class PromotionShippingAction extends PromotionActionDetails {
    protected $table = "PromotionShippingActions";
    protected $fillable = ['deliverymethod_id', 'deliveryterm_id', 'discount_percentage', 'use_rewardsexcluded_list'];
    protected $casts = ['use_rewardsexcluded_list' => 'boolean'];

    /**
     * TODO - TEMPORARY MEASURE TO ENSURE ALL SHIPPING ACTIONS ONLY USE U03 DELIVERY METHOD FOR NOW
     */
    public static function boot() {
        parent::boot();

        static::created(function (PromotionShippingAction $shippingAction) {
            $shippingAction->deliverymethod_id = DeliveryMethod::where('delivery_method_code', 'U03')->first()->id;
            $shippingAction->save();
        });
    }

    public function getDiscountPercentage() {
        return $this->discount_percentage;
    }

    public function shouldUseRewardsExcludedList(): bool {
        return $this->use_rewardsexcluded_list;
    }

    public function deliveryMethod(): BelongsTo {
        return $this->belongsTo(DeliveryMethod::class, 'deliverymethod_id');
    }

    public function calculateShippingDiscountAmount ($rate) {
        return round(($rate * $this->getDiscountPercentage() / 100), 2);
    }

    /**
     * @param $carrierName
     * @param $rate
     * @param $discAmt
     * @return array
     */
    public function createShipViaArray ($carrierName, $rate, $discAmt): array {
        if ($rate == $discAmt) {
            $term = 'F00';
        } else {
            $term = 'D00';
        }
        if ($this->shouldUseRewardsExcludedList()) {
            $desc = 'Rewards Discounted Freight';
        } else {
            $desc = 'Promotional Shipping';
        }
        return [
            'carrier_name' => $carrierName,
            'api_code' => null,
            'carrier_desc' => $desc,
            'rate' => $rate,
            'discounted_rate' => $discAmt,
            'delivery_datetime' => null,
            'delivery_method' => $this->deliveryMethod->getDeliveryMethodCode(),
            'delivery_term' => $term,
            'is_default' => false,
        ];
    }

    public function takeAction(Customer $soldToCustomer, $webCartItems, &$status)
    {
        // TODO: Implement takeAction() method.
    }
}