<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Builder;

class QualityCheck extends Model
{
    use LogsActivity;

    protected $table = 'quality_checks';

    protected $fillable = [
        'context',
        'context_id',
        'item_id',
        'lot_no',
        'result',
        'attributes',
        'checked_by_id'
    ];

    protected $casts = [
        'attributes' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    // Context constants
    const CONTEXT_GRN = 'grn';
    const CONTEXT_WO_INPROCESS = 'wo_inprocess';
    const CONTEXT_WO_FINAL = 'wo_final';

    // Result constants
    const RESULT_PASS = 'pass';
    const RESULT_FAIL = 'fail';
    const RESULT_REWORK = 'rework';

    // Relationships
    public function item()
    {
        return $this->belongsTo(Item::class);
    }

    public function checkedBy()
    {
        return $this->belongsTo(User::class, 'checked_by_id');
    }



    // Polymorphic relationships based on context
    public function contextable()
    {
        return $this->morphTo('context', 'context_id');
    }

    // Scopes
    public function scopeByContext(Builder $query, string $context): void
    {
        $query->where('context', $context);
    }

    public function scopeByResult(Builder $query, string $result): void
    {
        $query->where('result', $result);
    }

    public function scopeByItem(Builder $query, int $itemId): void
    {
        $query->where('item_id', $itemId);
    }

    public function scopeByDateRange(Builder $query, string $fromDate, string $toDate): void
    {
        $query->whereBetween('created_at', [$fromDate, $toDate]);
    }

    // Helper methods
    public function getResultBadgeAttribute(): string
    {
        $badges = [
            self::RESULT_PASS => 'badge-success',
            self::RESULT_FAIL => 'badge-danger',
            self::RESULT_REWORK => 'badge-warning'
        ];

        return $badges[$this->result] ?? 'badge-secondary';
    }

    public function isPassed(): bool
    {
        return $this->result === self::RESULT_PASS;
    }

    public function isFailed(): bool
    {
        return $this->result === self::RESULT_FAIL;
    }

    public function isRework(): bool
    {
        return $this->result === self::RESULT_REWORK;
    }

    public function getContextNameAttribute(): string
    {
        $contexts = [
            self::CONTEXT_GRN => 'GRN',
            self::CONTEXT_WO_INPROCESS => 'WO In-Process',
            self::CONTEXT_WO_FINAL => 'WO Final'
        ];

        return $contexts[$this->context] ?? $this->context;
    }

    // Activity Log
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['context', 'context_id', 'item_id', 'lot_no', 'result', 'attributes', 'checked_by_id'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs()
            ->setDescriptionForEvent(fn(string $eventName) => "Quality Check {$eventName}")
            ->useLogName('quality_check');
    }
}
