<?php

namespace App\Models\Warehouse;

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

class QualityInspectionChecklist extends Model
{
    use HasFactory;

    protected $fillable = [
        'checklist_name',
        'material_category',
        'inspection_criteria',
        'is_active',
        'is_mandatory',
        'instructions'
    ];

    protected $casts = [
        'inspection_criteria' => 'array',
        'is_active' => 'boolean',
        'is_mandatory' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Scope for active checklists
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope for mandatory checklists
     */
    public function scopeMandatory($query)
    {
        return $query->where('is_mandatory', true);
    }

    /**
     * Scope by material category
     */
    public function scopeForCategory($query, $category)
    {
        return $query->where('material_category', $category);
    }

    /**
     * Get checklist for material category
     */
    public static function getForCategory($category)
    {
        return static::active()
                    ->forCategory($category)
                    ->get();
    }

    /**
     * Get mandatory checklist for material category
     */
    public static function getMandatoryForCategory($category)
    {
        return static::active()
                    ->mandatory()
                    ->forCategory($category)
                    ->get();
    }

    /**
     * Validate inspection data against checklist
     */
    public function validateInspection($inspectionData)
    {
        $results = [];
        $passed = true;

        foreach ($this->inspection_criteria as $criterion) {
            $criterionId = $criterion['id'];
            $criterionName = $criterion['name'];
            $isRequired = $criterion['required'] ?? false;
            $type = $criterion['type'] ?? 'boolean'; // boolean, numeric, text, option

            if (!isset($inspectionData[$criterionId])) {
                if ($isRequired) {
                    $results[$criterionId] = [
                        'status' => 'failed',
                        'message' => "Required criterion '{$criterionName}' not provided"
                    ];
                    $passed = false;
                } else {
                    $results[$criterionId] = [
                        'status' => 'skipped',
                        'message' => "Optional criterion '{$criterionName}' not provided"
                    ];
                }
                continue;
            }

            $value = $inspectionData[$criterionId];
            $criterionPassed = $this->validateCriterion($criterion, $value);

            $results[$criterionId] = [
                'status' => $criterionPassed ? 'passed' : 'failed',
                'value' => $value,
                'message' => $criterionPassed ? 'Criterion met' : 'Criterion not met'
            ];

            if (!$criterionPassed && $isRequired) {
                $passed = false;
            }
        }

        return [
            'overall_status' => $passed ? 'passed' : 'failed',
            'criteria_results' => $results
        ];
    }

    /**
     * Validate individual criterion
     */
    protected function validateCriterion($criterion, $value)
    {
        $type = $criterion['type'] ?? 'boolean';
        $validation = $criterion['validation'] ?? [];

        switch ($type) {
            case 'boolean':
                return (bool) $value;

            case 'numeric':
                if (isset($validation['min']) && $value < $validation['min']) {
                    return false;
                }
                if (isset($validation['max']) && $value > $validation['max']) {
                    return false;
                }
                return true;

            case 'text':
                if (isset($validation['min_length']) && strlen($value) < $validation['min_length']) {
                    return false;
                }
                if (isset($validation['max_length']) && strlen($value) > $validation['max_length']) {
                    return false;
                }
                if (isset($validation['pattern']) && !preg_match($validation['pattern'], $value)) {
                    return false;
                }
                return true;

            case 'option':
                $allowedOptions = $validation['options'] ?? [];
                return in_array($value, $allowedOptions);

            default:
                return true;
        }
    }

    /**
     * Get default construction material checklists
     */
    public static function getConstructionDefaults()
    {
        return [
            [
                'checklist_name' => 'Structural Steel Inspection',
                'material_category' => 'structural_materials',
                'is_mandatory' => true,
                'inspection_criteria' => [
                    [
                        'id' => 'visual_inspection',
                        'name' => 'Visual Inspection',
                        'type' => 'boolean',
                        'required' => true,
                        'description' => 'Check for visible defects, corrosion, or damage'
                    ],
                    [
                        'id' => 'dimensional_check',
                        'name' => 'Dimensional Check',
                        'type' => 'boolean',
                        'required' => true,
                        'description' => 'Verify dimensions match specifications'
                    ],
                    [
                        'id' => 'material_certificate',
                        'name' => 'Material Certificate',
                        'type' => 'boolean',
                        'required' => true,
                        'description' => 'Mill test certificate provided and verified'
                    ],
                    [
                        'id' => 'surface_finish',
                        'name' => 'Surface Finish Quality',
                        'type' => 'option',
                        'required' => true,
                        'validation' => ['options' => ['excellent', 'good', 'acceptable', 'poor']],
                        'description' => 'Rate the surface finish quality'
                    ]
                ],
                'instructions' => 'Perform comprehensive inspection of structural steel components before acceptance.'
            ],
            [
                'checklist_name' => 'Electrical Components Inspection',
                'material_category' => 'electrical_supplies',
                'is_mandatory' => true,
                'inspection_criteria' => [
                    [
                        'id' => 'packaging_condition',
                        'name' => 'Packaging Condition',
                        'type' => 'boolean',
                        'required' => true,
                        'description' => 'Check if packaging is intact and undamaged'
                    ],
                    [
                        'id' => 'labeling_check',
                        'name' => 'Labeling and Marking',
                        'type' => 'boolean',
                        'required' => true,
                        'description' => 'Verify proper labeling and electrical ratings'
                    ],
                    [
                        'id' => 'compliance_certificate',
                        'name' => 'UAE Compliance Certificate',
                        'type' => 'boolean',
                        'required' => true,
                        'description' => 'Valid UAE ESMA certificate available'
                    ],
                    [
                        'id' => 'insulation_test',
                        'name' => 'Insulation Test (if applicable)',
                        'type' => 'boolean',
                        'required' => false,
                        'description' => 'Perform insulation resistance test for high voltage components'
                    ]
                ],
                'instructions' => 'Ensure electrical components meet UAE safety standards and regulations.'
            ],
            [
                'checklist_name' => 'Concrete Materials Inspection',
                'material_category' => 'structural_materials',
                'is_mandatory' => true,
                'inspection_criteria' => [
                    [
                        'id' => 'aggregate_grading',
                        'name' => 'Aggregate Grading',
                        'type' => 'boolean',
                        'required' => true,
                        'description' => 'Verify aggregate grading meets specifications'
                    ],
                    [
                        'id' => 'cement_quality',
                        'name' => 'Cement Quality Certificate',
                        'type' => 'boolean',
                        'required' => true,
                        'description' => 'Valid cement quality certificate provided'
                    ],
                    [
                        'id' => 'moisture_content',
                        'name' => 'Moisture Content Check',
                        'type' => 'numeric',
                        'required' => true,
                        'validation' => ['min' => 0, 'max' => 5],
                        'description' => 'Moisture content percentage (should be < 5%)'
                    ]
                ],
                'instructions' => 'Inspect concrete materials to ensure quality and compliance with mix design.'
            ]
        ];
    }
}