85 lines
2.0 KiB
PHP
85 lines
2.0 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace Modules\Frontend\Models;
|
||
|
|
|
||
|
|
use Illuminate\Database\Eloquent\Model;
|
||
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||
|
|
use Modules\Authentication\Models\User;
|
||
|
|
|
||
|
|
class Coupon extends Model
|
||
|
|
{
|
||
|
|
protected $fillable = [
|
||
|
|
'restaurant_id',
|
||
|
|
'user_id',
|
||
|
|
'name',
|
||
|
|
'added_by',
|
||
|
|
'discount_type',
|
||
|
|
'coupon_type',
|
||
|
|
'amount',
|
||
|
|
'valid_from',
|
||
|
|
'valid_to',
|
||
|
|
'usage_limit',
|
||
|
|
'max_uses_per_customer',
|
||
|
|
'min_order_amount',
|
||
|
|
'image',
|
||
|
|
'source',
|
||
|
|
'status',
|
||
|
|
'created_at',
|
||
|
|
'updated_at',
|
||
|
|
'deleted_at',
|
||
|
|
];
|
||
|
|
|
||
|
|
protected $casts = [
|
||
|
|
'amount' => 'decimal:2',
|
||
|
|
'min_order_amount' => 'decimal:2',
|
||
|
|
'valid_from' => 'datetime',
|
||
|
|
'valid_to' => 'datetime',
|
||
|
|
'status' => 'integer',
|
||
|
|
];
|
||
|
|
|
||
|
|
public const TABLE_NAME = 'coupons';
|
||
|
|
|
||
|
|
protected $table = self::TABLE_NAME;
|
||
|
|
|
||
|
|
public function user(): BelongsTo
|
||
|
|
{
|
||
|
|
return $this->belongsTo(User::class, 'user_id');
|
||
|
|
}
|
||
|
|
|
||
|
|
public function usages(): HasMany
|
||
|
|
{
|
||
|
|
return $this->hasMany(CouponUsage::class, 'coupon_id');
|
||
|
|
}
|
||
|
|
|
||
|
|
// Scopes
|
||
|
|
public function scopeActive($query): mixed
|
||
|
|
{
|
||
|
|
return $query->where('status', 1)
|
||
|
|
->where(function ($q) {
|
||
|
|
$q->whereNull('valid_from')->orWhere('valid_from', '<=', now());
|
||
|
|
})
|
||
|
|
->where(function ($q) {
|
||
|
|
$q->whereNull('valid_to')->orWhere('valid_to', '>=', now());
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
// Helper: Calculate discount for an order
|
||
|
|
public function calculateDiscount(float $orderTotal): float
|
||
|
|
{
|
||
|
|
if ($this->discount_type === 'fixed') {
|
||
|
|
return min($this->amount, $orderTotal);
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($this->discount_type === 'percentage') {
|
||
|
|
return round($orderTotal * ($this->amount / 100), 2);
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($this->discount_type === 'free_delivery') {
|
||
|
|
return 0; // discount only applies to delivery
|
||
|
|
}
|
||
|
|
|
||
|
|
return 0;
|
||
|
|
}
|
||
|
|
}
|