<?php

namespace PortalPeople\shippingcosts\models;

use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "sys_shipping_setting".
 *
 * @property string $id id
 * @property string $language language
 * @property string $created_by Created By
 * @property string $updated_by Updated By
 * @property string $deleted_by Deleted By
 * @property string $relatedid Related ID
 * @property string $centerid Center ID
 * @property int $created_at Created At
 * @property int $updated_at Updated At
 * @property int $deleted_at Deleted At
 * @property string $status Status
 * @property string $title Title
 * @property string $max_shipping_cost Maximun Shipping Cost
 * @property string $shipping_promotion Free Shippimg Promotion Text
 * @property string $zero_cost_shipping Zero Cost Shipping Text
 * @property string $handling_fee Zero Cost Shipping Text
 * @property string $countries Ship to Specific Countries
 * @property string $error_message Displayed Error Message
 * @property string $totaling_algo Totaling Algorithm
 * @property int $shipping_group Shipping Group
 * @property int $applicable_countries Ship to Applicable Countries
 * @property int $enabled "0"=>"no","1"=>"yes"
 * @property int $package_id "0"=>"no","1"=>"yes"
 * @property int $post_code_range "0"=>"no","1"=>"yes"
 * @property int $uk_post_code "0"=>"no","1"=>"yes"
 * @property int $discount_price "0"=>"no","1"=>"yes"
 * @property int $exclude_fornt_price "0"=>"no","1"=>"yes"
 * @property int $cal_handling_fee "0"=>"no","1"=>"yes"
 * @property int $apply_handling_fee "0"=>"no","1"=>"yes"
 * @property int $show_ship_status Show Shipping Status on Frontend
 * @property int $default_ship_status Default Shipping Status
 */
class SysShippingSetting extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'sys_shipping_setting';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [[
                'title',
                'centerid',
                'enabled',
                'shipping_group',
                'applicable_countries',
                'apply_handling_fee',
                'show_ship_status',
            ], 'required'],
            [[
                'created_at',
                'updated_at',
                'deleted_at',
                'applicable_countries',
                'enabled',
                'package_id',
                'post_code_range',
                'uk_post_code',
                'discount_price',
                'cal_handling_fee',
                'apply_handling_fee',
                'show_ship_status',
            ], 'integer'],
            [[
                'id',
                'created_by',
                'updated_by',
                'deleted_by',
                'relatedid',
                'centerid',
                'totaling_algo',
                'shipping_group',
                'default_ship_status',
            ], 'string', 'max' => 36],
            [['language'], 'string', 'max' => 10],
            ['exclude_fornt_price', 'boolean'],
            [['status', 'title', 'shipping_promotion', 'error_message', ], 'string', 'max' => 255],
            [['id', 'language'], 'unique', 'targetAttribute' => ['id', 'language']],
            [
                ['max_shipping_cost', 'handling_fee', 'zero_cost_shipping'],
                'number',
                'numberPattern' => '/^\s*[-+]?[0-9]*[.,]?[0-9]+([eE][-+]?[0-9]+)?\s*$/',
            ],
            [['countries'], 'safe'],
            [['centerid'], 'unique', 'message' => '{attribute} should be unique.'],
            [[ 'default_ship_status'], 'required',
                'when' => function ($model) {
                    return $model->show_ship_status == true ? true : false;
                },
                'whenClient' => "function (attribute, value) {
			        return $('#sysshippingsetting-show_ship_status').val() == '1';
			    }"
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'language' => 'Language',
            'created_by' => 'Created By',
            'updated_by' => 'Updated By',
            'deleted_by' => 'Deleted By',
            'relatedid' => 'Relatedid',
            'centerid' => 'Store',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'deleted_at' => 'Deleted At',
            'status' => 'Status',
            'title' => 'Title',
            'max_shipping_cost' => 'Max Shipping Cost',
            'shipping_promotion' => 'Shipping Promotion',
            'zero_cost_shipping' => 'Zero Cost Shipping',
            'handling_fee' => 'Handling Fee',
            'countries' => 'Countries',
            'error_message' => 'Error Message',
            'totaling_algo' => 'Totaling Algo',
            'shipping_group' => 'Shipping Group',
            'applicable_countries' => 'Applicable Countries',
            'enabled' => 'Enabled',
            'package_id' => 'Package ID',
            'post_code_range' => 'Use Post Code To / From Range',
            'uk_post_code' => 'UK Post Code',
            'discount_price' => 'Discount Price',
            'exclude_fornt_price' => 'Exclude Front Price',
            'cal_handling_fee' => 'Calculate Handling Fee',
            'apply_handling_fee' => 'Apply Handling Fee on zero shipping',
            'show_ship_status' => 'Show Shipping Status on Frontend',
            'default_ship_status' => 'Default Shipping Status',
        ];
    }

    public function behaviors()
    {
        return [ TimestampBehavior::class, BlameableBehavior::class, ];
    }

    public function beforeSave($insert)
    {
        $this->default_ship_status = $this->show_ship_status == true  ? $this->default_ship_status : '';
        $this->countries = is_array($this->countries) ? implode(',', $this->countries) : $this->countries;
        return parent::beforeSave($insert);
    }

    public function afterFind()
    {
        $this->countries = str_contains($this->countries, ',') ? explode(",", $this->countries) : $this->countries;
        return parent::afterFind();
    }

    public static function getActiveCountries()
    {
        $model = self::find()->where(['enabled' => 1])->one();

        if (!$model) {
            $country = \backend\models\SysCountry::find()->where(['status' => "Active"])->asArray()->all();
        } else {
            if ($model->applicable_countries == 1) {
                $country = \backend\models\SysCountry::find()->where(['status' => "Active"])->asArray()->all();
            } elseif ($model->applicable_countries == 2) {
                $setting_countries = explode(",", $model->countries);
                $country = \backend\models\SysCountry::find()
                    ->where(["IN", "alpha_3", $setting_countries])
                    ->asArray()
                    ->all();
            }
        }

        return $country;
    }

    public function getStorename()
    {
        $getstores = \backend\models\Settings::find()->where(['id' => $this->centerid])->one();
        return $getstores ? $getstores->storeid : '';
    }

    public function getShipname()
    {
        $getship = \backend\models\Shipgroup::find()->where(['id' => $this->shipping_group])->one();
        return $getship ? $getship->name : '';
    }

    public function getAlgoname()
    {
        $algos = \common\components\ClassifyProductsSettings::getTotallingAlgo();
        return $this->totaling_algo ? $algos[$this->totaling_algo] : '';
    }

    /**
     * Calculate Delivery charges if Zero shipping handling fee is set to Yes in
     * shipping settings.
     */
    public function getDeliveryCharge($delivery_charge, $subtotal)
    {
        $store_id       = Yii::$app->id;
        $settings       = self::find()->where(['centerid' => $store_id])->one();

        if ($settings->apply_handling_fee == "1" && $delivery_charge == "0.00") {
            if ($settings->cal_handling_fee == "1") { // calculation for Fixed Price handeliing fee
                $delivery_charge = $settings->handling_fee;
            } elseif ($settings->cal_handling_fee == "0") {
                // calculation for % handeliing fee : % on total cart amount
                $amount = ($subtotal * $settings->handling_fee) / 100;
                $delivery_charge = $amount;
            }
        }

        return $delivery_charge;
    }

    public function getCreatedby()
    {
        return $this->hasOne(\backend\models\User::class, ['id' => 'created_by']);
    }

    public function getUpdatedby()
    {
        return $this->hasOne(\backend\models\User::class, ['id' => 'updated_by']);
    }

    public function getDeletedby()
    {
        return $this->hasOne(\backend\models\User::class, ['id' => 'deleted_by']);
    }
}
