<?php

namespace App\Models;

use App\Models\Traits\HasAuditFields;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class QualityControl extends Model
{
    use HasFactory, SoftDeletes, HasAuditFields;

    protected $table = 'quality_controls';

    /**
     * Status constants
     */
    public const STATUS_PENDING = 'pending';
    public const STATUS_IN_PROGRESS = 'in_progress';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_APPROVED = 'approved';
    public const STATUS_REJECTED = 'rejected';

    /**
     * Result constants
     */
    public const RESULT_PASS = 'pass';
    public const RESULT_FAIL = 'fail';
    public const RESULT_CONDITIONAL = 'conditional';

    protected $fillable = [
        'process_id',
        'route_card_id',
        'customer',
        'project_no',
        'material_no',
        'part_no',
        'drawing_certification',
        'document_type',
        'document_value',
        'revision',
        'sl_no',
        'drawing_position',
        'parameter',
        'description',
        'drawing_value',
        'tolerance',
        'measurement_value1',
        'measurement_value2',
        'remarks',
        'status',
        'result',
        'inspected_by',
        'inspected_at',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'sl_no' => 'integer',
        'inspected_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    // ──────────────────────────────────────────────────────────────────────────
    // RELATIONSHIPS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get the route card process this QC belongs to.
     */
    public function routeCardProcess()
    {
        return $this->belongsTo(RouteCardProcess::class, 'process_id');
    }

    /**
     * Get the route card directly (if linked)
     */
    public function routeCard()
    {
        return $this->belongsTo(RouteCard::class, 'route_card_id');
    }

    /**
     * Get the user who created this QC record.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the user who inspected this QC.
     */
    public function inspector()
    {
        return $this->belongsTo(User::class, 'inspected_by');
    }

    // ──────────────────────────────────────────────────────────────────────────
    // SCOPES
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Filter by pending status
     */
    public function scopePending(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_PENDING);
    }

    /**
     * Filter by in progress status
     */
    public function scopeInProgress(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_IN_PROGRESS);
    }

    /**
     * Filter by completed status
     */
    public function scopeCompleted(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_COMPLETED);
    }

    /**
     * Filter by approved status
     */
    public function scopeApproved(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_APPROVED);
    }

    /**
     * Filter by rejected status
     */
    public function scopeRejected(Builder $query): Builder
    {
        return $query->where('status', self::STATUS_REJECTED);
    }

    /**
     * Filter by pass result
     */
    public function scopePassed(Builder $query): Builder
    {
        return $query->where('result', self::RESULT_PASS);
    }

    /**
     * Filter by fail result
     */
    public function scopeFailed(Builder $query): Builder
    {
        return $query->where('result', self::RESULT_FAIL);
    }

    /**
     * Filter by route card
     */
    public function scopeForRouteCard(Builder $query, int $routeCardId): Builder
    {
        return $query->where('route_card_id', $routeCardId);
    }

    /**
     * Filter by process
     */
    public function scopeForProcess(Builder $query, int $processId): Builder
    {
        return $query->where('process_id', $processId);
    }

    /**
     * Filter by part number
     */
    public function scopeForPart(Builder $query, string $partNo): Builder
    {
        return $query->where('part_no', $partNo);
    }

    // ──────────────────────────────────────────────────────────────────────────
    // ACCESSORS & HELPERS
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Get all valid statuses
     */
    public static function getStatuses(): array
    {
        return [
            self::STATUS_PENDING,
            self::STATUS_IN_PROGRESS,
            self::STATUS_COMPLETED,
            self::STATUS_APPROVED,
            self::STATUS_REJECTED,
        ];
    }

    /**
     * Get all valid results
     */
    public static function getResults(): array
    {
        return [
            self::RESULT_PASS,
            self::RESULT_FAIL,
            self::RESULT_CONDITIONAL,
        ];
    }

    /**
     * Check if QC is within tolerance
     */
    public function isWithinTolerance(): bool
    {
        if (!$this->tolerance || !$this->measurement_value1) {
            return true;
        }

        // Parse tolerance (e.g., "±0.5" or "0.5")
        $toleranceValue = (float) preg_replace('/[^\d.]/', '', $this->tolerance);
        $drawingValue = (float) $this->drawing_value;
        $measurementValue = (float) $this->measurement_value1;

        $deviation = abs($measurementValue - $drawingValue);
        return $deviation <= $toleranceValue;
    }

    /**
     * Check if QC is pending
     */
    public function isPending(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    /**
     * Check if QC passed
     */
    public function hasPassed(): bool
    {
        return $this->result === self::RESULT_PASS;
    }

    /**
     * Check if QC failed
     */
    public function hasFailed(): bool
    {
        return $this->result === self::RESULT_FAIL;
    }
}
