<?php

namespace App\Models\OrderManagement;

use App\Models\Traits\Activable;
use App\Models\Traits\Bootables\Auditable;
use Axn\EloquentAuthorable\AuthorableTrait;
use Carbon\Carbon;
use Database\Factories\CouponFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Nicolaslopezj\Searchable\SearchableTrait;

class Coupon extends Model{
    use HasFactory, SearchableTrait,Activable,AuthorableTrait,Auditable;

    protected $table = "order_mgt__coupons";
    protected $guarded = [];

    protected $searchable = [
        'columns' => [
            'coupons.code' => 10,
            'coupons.description' => 10
        ],
    ];


    protected $dates = ['start_date', 'expire_date'];

    protected static function newFactory(){
        return CouponFactory::new();
    }


    public function getIsPublicAttribute(){
        return (!$this->attributes['is_public']) ? __('Private') : __('Public');
    }


    public function scopePublic($query){
        return $query->whereIsPublic(true);
    }

    public function discount($total){
        if (!$this->checkDate() || !$this->checkUsedTimes()) {
            return 0;
        }
        return $this->checkGreaterThan($total) ? $this->doProcess($total) : 0;
    }

    protected function checkDate(){
        if (filled($this->expire_date)) {
            return Carbon::now()->between($this->start_date, $this->expire_date, true);
        }
        return true;
    }

    protected function checkUsedTimes(){
        if (filled($this->use_times)) {
            return $this->use_times > $this->used_times;
        }
        return true;
    }

    protected function checkGreaterThan($total){
        if (filled($this->greater_than)) {
            return $this->greater_than <= $total;
        }
        return true;
    }

    protected function doProcess($total){
        switch ($this->type) {
            case 'fixed':
                return $this->value;
            case 'percentage':
                return ($this->value / 100) * $total;
            default:
                return 0;
        }
    }
}
