<?php

namespace App\Models\Courses;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;


class CourseCoupon extends Model
{
    protected $fillable = [
        'course_id', 'code', 'discount_type', 'discount_amount',
        'usage_limit', 'usage_count', 'expires_at', 'is_active'
    ];

    protected $casts = [
        'expires_at' => 'datetime',
        'is_active' => 'boolean',
    ];

    public function course()
    {
        return $this->belongsTo(Course::class);
    }

    public function isValid()
    {
        if (!$this->is_active) {
            return false;
        }
        
        if ($this->expires_at && $this->expires_at < now()) {
            return false;
        }
        
        if ($this->usage_limit && $this->usage_count >= $this->usage_limit) {
            return false;
        }
        
        return true;
    }

    public function calculateDiscount($price)
    {
        if (!$this->isValid()) {
            return 0;
        }
        
        if ($this->discount_type == 'percentage') {
            return ($price * $this->discount_amount) / 100;
        }
        
        return min($this->discount_amount, $price);
    }

    public function incrementUsage()
    {
        $this->usage_count++;
        $this->save();
    }
}