<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @property mixed category_id
 * @property mixed user_id
 * @mixin  Builder
 */
class Coupon extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'user_id',
        'code',
        'available_users',
        'used_count',
        'discount_type',
        'discount_amount',
        'marketer_percentage',
        'start_date',
        'end_date',
        'service_type',
        'status',
    ];


    public function user()
    {
        return $this->belongsTo(User::class)->where('role', 'user');
    }

    public static function checkCoupon($code, $price = null, $serviceType = null)
    {
        $coupon = self::where('code', $code)
            ->whereIn('service_type', ['all', $serviceType])->first();

        if (!$coupon){
            return ['errors' => __('coupons.coupon_not_valid_for_service')];
        }

        if (
            !$coupon->status ||
            $coupon->start_date > date('Y-m-d') ||
            $coupon->end_date < date('Y-m-d') ||
            $coupon->available_users == 0

        ){
            return ['errors' => __('coupons.invalid_coupon')];
        }

        $addedValue = settings('added_value');
        $total = 0;
        $couponDiscount = 0; // Discount by value or percentage
        $couponDiscountAmount = 0; // Discount amount
        $discountType = 0; // Discount type [percentage or value]

        if ($coupon->discount_type == 'percentage'){
            $couponDiscountAmount =  ($price*$coupon->discount_amount)/100;
            $price = $price-$couponDiscountAmount;
            $addedValueAmount = ($price*$addedValue)/100;
            $total = $price+$addedValueAmount;
            $couponDiscount = $coupon->discount_amount.'%';
            $discountType = 'percentage';
        }
        if ($coupon->discount_type == 'value'){
            $couponDiscountAmount =  $coupon->discount_amount;
            $price = $price-$couponDiscountAmount;
            $addedValueAmount = ($price*$addedValue)/100;
            $total = $price+$addedValueAmount;
            $couponDiscount = $coupon->discount_amount;
            $discountType = 'value';
        }

        return [
            'errors' => false,
            'total' => round($total),
            'coupon_discount_amount' => $couponDiscountAmount,
            'coupon_discount' => $couponDiscount,
            'discount_type' => $discountType,
            'coupon_id' => $coupon->id,
            'coupon' => $coupon,
        ];

    }

}
