<?php

namespace App\Services;

/**
 * Service for managing vehicle inspection checklists and quality control
 */
class InspectionChecklistService
{
    /**
     * Get standardized inspection checklist items
     */
    public function getStandardChecklistItems(): array
    {
        return [
            'engine' => [
                'oil_level' => ['label' => 'Oil Level', 'type' => 'select', 'options' => ['full', 'low', 'empty'], 'required' => true],
                'coolant_level' => ['label' => 'Coolant Level', 'type' => 'select', 'options' => ['full', 'low', 'empty'], 'required' => true],
                'air_filter' => ['label' => 'Air Filter Condition', 'type' => 'select', 'options' => ['clean', 'dirty', 'needs_replacement'], 'required' => true],
                'battery' => ['label' => 'Battery Condition', 'type' => 'select', 'options' => ['excellent', 'good', 'fair', 'poor'], 'required' => true],
                'belts_hoses' => ['label' => 'Belts and Hoses', 'type' => 'select', 'options' => ['excellent', 'good', 'fair', 'poor'], 'required' => true],
            ],
            'brakes' => [
                'brake_pads' => ['label' => 'Brake Pad Condition', 'type' => 'select', 'options' => ['excellent', 'good', 'fair', 'poor'], 'required' => true],
                'brake_fluid' => ['label' => 'Brake Fluid Level', 'type' => 'select', 'options' => ['full', 'low', 'empty'], 'required' => true],
                'brake_feel' => ['label' => 'Brake Pedal Feel', 'type' => 'select', 'options' => ['firm', 'soft', 'spongy'], 'required' => true],
            ],
            'tires' => [
                'tire_condition' => ['label' => 'Tire Condition', 'type' => 'select', 'options' => ['excellent', 'good', 'fair', 'poor'], 'required' => true],
                'tire_pressure' => ['label' => 'Tire Pressure', 'type' => 'select', 'options' => ['correct', 'low', 'high'], 'required' => true],
                'tread_depth' => ['label' => 'Tread Depth', 'type' => 'select', 'options' => ['good', 'marginal', 'poor'], 'required' => true],
            ],
        ];
    }

    /**
     * Compare incoming and outgoing inspections
     */
    public function compareInspections(array $incomingInspection, array $outgoingInspection): array
    {
        $improvements = [];
        $discrepancies = [];
        $maintained = [];

        foreach ($incomingInspection as $category => $incomingValue) {
            if (!isset($outgoingInspection[$category])) {
                continue;
            }

            $outgoingValue = $outgoingInspection[$category];

            if ($this->isImprovement($incomingValue, $outgoingValue)) {
                $improvements[] = $category;
            } elseif ($this->isDiscrepancy($incomingValue, $outgoingValue)) {
                $discrepancies[] = $category;
            } else {
                $maintained[] = $category;
            }
        }

        return [
            'improvements' => $improvements,
            'discrepancies' => $discrepancies,
            'maintained' => $maintained,
            'overall_quality_score' => $this->calculateQualityScore($improvements, $discrepancies, $maintained),
        ];
    }

    /**
     * Generate quality alert based on inspection comparison
     */
    public function generateQualityAlert(array $comparison): ?string
    {
        if (count($comparison['discrepancies']) > 0) {
            return 'Quality Alert: Vehicle condition has deteriorated in the following areas: ' . 
                   implode(', ', $comparison['discrepancies']);
        }

        if ($comparison['overall_quality_score'] < 0.7) {
            return 'Quality Alert: Overall quality score is below acceptable threshold.';
        }

        return null;
    }

    /**
     * Check if outgoing value is an improvement over incoming
     */
    private function isImprovement(string $incoming, string $outgoing): bool
    {
        $qualityOrder = ['poor', 'fair', 'good', 'excellent'];
        $incomingIndex = array_search($incoming, $qualityOrder);
        $outgoingIndex = array_search($outgoing, $qualityOrder);

        return $outgoingIndex !== false && $incomingIndex !== false && $outgoingIndex > $incomingIndex;
    }

    /**
     * Check if outgoing value is worse than incoming (discrepancy)
     */
    private function isDiscrepancy(string $incoming, string $outgoing): bool
    {
        $qualityOrder = ['poor', 'fair', 'good', 'excellent'];
        $incomingIndex = array_search($incoming, $qualityOrder);
        $outgoingIndex = array_search($outgoing, $qualityOrder);

        return $outgoingIndex !== false && $incomingIndex !== false && $outgoingIndex < $incomingIndex;
    }

    /**
     * Calculate overall quality score
     */
    private function calculateQualityScore(array $improvements, array $discrepancies, array $maintained): float
    {
        $totalItems = count($improvements) + count($discrepancies) + count($maintained);
        
        if ($totalItems === 0) {
            return 1.0;
        }

        $improvementScore = count($improvements) * 1.2;
        $maintainedScore = count($maintained) * 1.0;
        $discrepancyScore = count($discrepancies) * 0.3;

        return min(1.0, ($improvementScore + $maintainedScore + $discrepancyScore) / $totalItems);
    }
}
