50 lines
1.4 KiB
PHP
50 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Traits\Order;
|
|
|
|
use App\Enums\VoucherType;
|
|
use App\Models\Voucher;
|
|
|
|
trait WithDiscount
|
|
{
|
|
public function updatedFormDiscount(string $value): void
|
|
{
|
|
$this->total = $this->getTotal();
|
|
}
|
|
|
|
public function calculateDiscount(int $subtotal, string $voucherId): array|int
|
|
{
|
|
$voucher = Voucher::find($voucherId);
|
|
$discount = 0;
|
|
|
|
if ($voucher) {
|
|
// Check minimum purchase
|
|
if ($voucher->min_purchase && $subtotal < $voucher->min_purchase) {
|
|
$this->discount = 0;
|
|
|
|
return [
|
|
'status' => false,
|
|
'message' => 'Minimal pembelian harus sebesar '.formatCurrencyNumber($voucher->min_purchase, 'Rp').' untuk menggunakan voucher ini.',
|
|
];
|
|
}
|
|
|
|
// Calculate discount based on voucher type
|
|
if ($voucher->type === VoucherType::PERCENTAGE) {
|
|
$discount = ($subtotal * $voucher->discount_amount) / 100;
|
|
|
|
// Apply maximum discount limit
|
|
if ($voucher->max_discount && $discount > $voucher->max_discount) {
|
|
$discount = $voucher->max_discount;
|
|
}
|
|
} else {
|
|
$discount = $voucher->discount_amount;
|
|
}
|
|
|
|
// Ensure discount does not exceed subtotal
|
|
$discount = min($discount, $subtotal);
|
|
}
|
|
|
|
return $discount;
|
|
}
|
|
}
|