<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Period extends Model
{
    use HasFactory;

    protected $table = 'm_periods';
    
    protected $fillable = [
        'code',
        'name',
        'description',
        'is_active',
        'delete_flag',
        'created_by',
        'updated_by'
    ];

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

    // Scope untuk data aktif
    public function scopeActive($query)
    {
        return $query->where('delete_flag', 0);
    }

    // Scope untuk data yang aktif dan enabled
    public function scopeEnabled($query)
    {
        return $query->where('delete_flag', 0)->where('is_active', 1);
    }

    // Relationship dengan raw materials
    public function rawMaterials()
    {
        return $this->hasMany(RawMaterial::class, 'period_id');
    }

    // Helper methods
    public function isEnabled()
    {
        return $this->is_active && !$this->delete_flag;
    }

    public function getStatusAttribute()
    {
        if ($this->delete_flag) {
            return 'Deleted';
        }
        return $this->is_active ? 'Active' : 'Inactive';
    }

    public function getStatusBadgeAttribute()
    {
        switch ($this->status) {
            case 'Active':
                return 'badge-success';
            case 'Inactive':
                return 'badge-secondary';
            case 'Deleted':
                return 'badge-danger';
            default:
                return 'badge-secondary';
        }
    }
}