<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CustomDiscount extends Model
{
    protected $table = 'custom_discounts';
    
    protected $fillable = [
        'couponName',
        'logo',
        'couponCode',
        'applyDate',
        'endDate',
        'isDisabled',
        'isPrimary',
        'discountType',
        'filter',
        'discount',
        'discountValue',
        'minBuyQty',
        'maxBuyQty',
        'freeQty',
        'useLimit',
        'setPriority',
        'getYproductId',
        'allRuleMatch',
        'rulesOnCart',
        'rulesOnPurchaseHistory',
        'rulesOnShipping',
        'rulesOnCustomer',
        'isLifeCycleCoupon',
        'couponLife',
        'custom_meta'
    ];

    protected $casts = [
        'isDisabled' => 'boolean',
        'isPrimary' => 'boolean',
        'isLifeCycleCoupon' => 'boolean',
        'filter' => 'array',
        'discount' => 'array',
        'custom_meta' => 'array',
        'applyDate' => 'date',
        'endDate' => 'date'
    ];

    public function scopeActive($query)
    {
        return $query->where('isDisabled', false);
    }

    public function scopePrimary($query)
    {
        return $query->where('isPrimary', true);
    }

    public function scopeValid($query)
    {
        $now = now();
        return $query->where(function($q) use ($now) {
            $q->whereNull('applyDate')
              ->orWhere('applyDate', '<=', $now);
        })->where(function($q) use ($now) {
            $q->whereNull('endDate')
              ->orWhere('endDate', '>=', $now);
        });
    }
} 