<?php

namespace App\Traits\Order;

use App\Enums\VoucherType;
use App\Models\Voucher;

trait WithDiscount
{
    public function updatedFormDiscount(string $value)
    {
        $total = $this->getTotal();
        $discount = replaceCurrency($value);

        $this->total = $total - $discount;
    }

    public function calculateDiscount(int $subtotal)
    {
        $voucher = Voucher::find($this->voucher_id);
        $discount = 0;

        if ($voucher) {
            // Check minimum purchase
            if ($voucher->min_purchase && $subtotal < $voucher->min_purchase) {
                $this->discount = 0;

                return [
                    'status' => false,
                    'message' => 'Minimum pembelian harus sebesar '.currency($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;
    }
}
