<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Voucher extends Model
{
    protected $fillable = [
        'code',
        'type',
        'value',
        'min_purchase',
        'max_discount',
        'max_usage',
        'used_count',
        'valid_from',
        'valid_until',
        'is_active',
        'description',
    ];

    protected $casts = [
        'valid_from' => 'datetime',
        'valid_until' => 'datetime',
        'is_active' => 'boolean',
        'value' => 'decimal:2',
    ];

    /**
     * Validate voucher
     */
    public function validate($totalAmount, $customerEmail = null)
    {
        // Check if active
        if (!$this->is_active) {
            return ['valid' => false, 'message' => 'Voucher tidak aktif'];
        }

        // Check date validity
        $now = Carbon::now();
        if ($this->valid_from && $now->lt($this->valid_from)) {
            return ['valid' => false, 'message' => 'Voucher belum berlaku'];
        }
        if ($this->valid_until && $now->gt($this->valid_until)) {
            return ['valid' => false, 'message' => 'Voucher sudah kadaluarsa'];
        }

        // Check minimum purchase
        if ($totalAmount < $this->min_purchase) {
            return [
                'valid' => false, 
                'message' => 'Minimum pembelian Rp ' . number_format($this->min_purchase, 0, ',', '.')
            ];
        }

        // Check usage limit
        if ($this->max_usage > 0 && $this->used_count >= $this->max_usage) {
            return ['valid' => false, 'message' => 'Voucher sudah mencapai batas penggunaan'];
        }

        return ['valid' => true, 'message' => 'Voucher valid'];
    }

    /**
     * Calculate discount amount
     */
    public function calculateDiscount($totalAmount)
    {
        if ($this->type === 'percentage') {
            $discount = ($totalAmount * $this->value) / 100;
            
            // Apply max discount if set
            if ($this->max_discount && $discount > $this->max_discount) {
                $discount = $this->max_discount;
            }
            
            return (int) $discount;
        } else {
            // Fixed amount
            return min($this->value, $totalAmount);
        }
    }

    /**
     * Apply voucher (increment usage)
     */
    public function apply($transactionId, $customerEmail, $discountAmount)
    {
        $this->increment('used_count');
        
        // Track usage
        \DB::table('voucher_usage')->insert([
            'voucher_id' => $this->id,
            'transaction_id' => $transactionId,
            'customer_email' => $customerEmail,
            'discount_amount' => $discountAmount,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    /**
     * Get usage history
     */
    public function usage()
    {
        return $this->hasMany(VoucherUsage::class);
    }

    /**
     * Scope: Active vouchers only
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true)
            ->where(function($q) {
                $q->whereNull('valid_from')
                  ->orWhere('valid_from', '<=', now());
            })
            ->where(function($q) {
                $q->whereNull('valid_until')
                  ->orWhere('valid_until', '>=', now());
            });
    }
}