<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class Voucher extends Model
{
    use HasFactory;
    use SoftDeletes;
    use LogsActivity;

    protected $fillable = [
        'code',
        'type',
        'value',
        'min_order',
        'max_discount',
        'quota',
        'used_count',
        'valid_from',
        'valid_until',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'value'        => 'decimal:2',
            'min_order'    => 'decimal:2',
            'max_discount' => 'decimal:2',
            'quota'        => 'integer',
            'used_count'   => 'integer',
            'valid_from'   => 'date',
            'valid_until'  => 'date',
            'is_active'    => 'boolean',
        ];
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['code', 'is_active', 'used_count'])
            ->logOnlyDirty()
            ->useLogName('voucher');
    }

    // ── Relationships ─────────────────────────────────────────────────────

    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }

    // ── Business Logic ────────────────────────────────────────────────────

    /**
     * Cek apakah voucher dapat digunakan saat ini.
     */
    public function isUsable(): bool
    {
        if (! $this->is_active) {
            return false;
        }

        $today = now()->toDateString();

        if ($this->valid_from && $this->valid_from->gt($today)) {
            return false;
        }

        if ($this->valid_until && $this->valid_until->lt($today)) {
            return false;
        }

        if ($this->quota !== null && $this->used_count >= $this->quota) {
            return false;
        }

        return true;
    }

    /**
     * Hitung nominal diskon untuk subtotal tertentu.
     *
     * @param  float $subtotal Subtotal order (sebelum diskon + ongkir)
     * @return float Nominal diskon
     */
    public function calculateDiscount(float $subtotal): float
    {
        if ($subtotal < $this->min_order) {
            return 0;
        }

        if ($this->type === 'percent') {
            $discount = $subtotal * $this->value / 100;

            if ($this->max_discount !== null) {
                $discount = min($discount, $this->max_discount);
            }

            return round($discount, 2);
        }

        // Fixed: diskon tidak boleh lebih dari subtotal
        return min($this->value, $subtotal);
    }

    // ── Scopes ────────────────────────────────────────────────────────────

    public function scopeUsable($query)
    {
        return $query
            ->where('is_active', true)
            ->where(fn ($q) => $q->whereNull('valid_from')->orWhereDate('valid_from', '<=', now()))
            ->where(fn ($q) => $q->whereNull('valid_until')->orWhereDate('valid_until', '>=', now()))
            ->where(fn ($q) => $q->whereNull('quota')->orWhereColumn('used_count', '<', 'quota'));
    }
}
