<?php
/**
 * AUTO TESTER - Vehicle Evaluation API
 * Vehicle valuation and evaluation system integration with inspection reports
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../database/functions/Database.php';

class VehicleEvaluation {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create vehicle evaluation request
     */
    public function createEvaluationRequest($data) {
        try {
            // Validate required fields
            $required = ['inspection_request_id', 'vehicle_id', 'customer_id', 'evaluation_type', 'evaluation_purpose'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Create evaluation request
            $stmt = $this->db->prepare("
                INSERT INTO vehicle_evaluation_requests 
                (inspection_request_id, vehicle_id, customer_id, evaluation_type, evaluation_purpose,
                 requested_by, target_date, special_instructions, customer_expected_price,
                 customer_notes, priority_level, status, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
            ");
            
            $result = $stmt->execute([
                $data['inspection_request_id'],
                $data['vehicle_id'],
                $data['customer_id'],
                $data['evaluation_type'],
                $data['evaluation_purpose'],
                $data['requested_by'],
                $data['target_date'] ?? null,
                $data['special_instructions'] ?? null,
                $data['customer_expected_price'] ?? null,
                $data['customer_notes'] ?? null,
                $data['priority_level'] ?? 'medium'
            ]);
            
            if ($result) {
                $evaluationRequestId = $this->db->lastInsertId();
                
                // Start evaluation process
                $this->startEvaluationProcess($evaluationRequestId);
                
                return [
                    'success' => true,
                    'message' => 'Vehicle evaluation request created successfully',
                    'evaluation_request_id' => $evaluationRequestId
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to create evaluation request'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Start evaluation process
     */
    private function startEvaluationProcess($evaluationRequestId) {
        // Update status to in_progress
        $stmt = $this->db->prepare("
            UPDATE vehicle_evaluation_requests 
            SET status = 'in_progress' 
            WHERE id = ?
        ");
        $stmt->execute([$evaluationRequestId]);
        
        // Get vehicle and inspection data including customer expected price
        $stmt = $this->db->prepare("
            SELECT ver.*, v.make, v.model, v.year, v.mileage, v.condition as vehicle_condition,
                   cir.overall_score, cir.grade, cir.pass_fail_status, cir.customer_expected_price
            FROM vehicle_evaluation_requests ver
            JOIN vehicles v ON ver.vehicle_id = v.id
            JOIN comprehensive_inspection_requests cir ON ver.inspection_request_id = cir.id
            WHERE ver.id = ?
        ");
        $stmt->execute([$evaluationRequestId]);
        $evaluationData = $stmt->fetch();
        
        if ($evaluationData) {
            // Perform automated evaluation
            $this->performAutomatedEvaluation($evaluationRequestId, $evaluationData);
        }
    }
    
    /**
     * Perform automated evaluation
     */
    private function performAutomatedEvaluation($evaluationRequestId, $vehicleData) {
        // Get market data for similar vehicles
        $marketData = $this->getMarketData($vehicleData['make'], $vehicleData['model'], $vehicleData['year']);
        
        // Get comparable vehicles
        $comparables = $this->getComparableVehicles($vehicleData);
        
        // Calculate base value from market data
        $baseValue = $this->calculateBaseValue($marketData, $vehicleData);
        
        // Calculate adjustments based on inspection results
        $adjustments = $this->calculateAdjustments($vehicleData);
        
        // Calculate customer price adjustment
        $customerPriceAdjustment = $this->calculateCustomerPriceAdjustment($vehicleData, $baseValue);
        
        // Calculate final value
        $finalValue = $baseValue + $adjustments['condition'] + $adjustments['mileage'] + 
                     $adjustments['age'] + $adjustments['market'] + $adjustments['location'] + 
                     $customerPriceAdjustment;
        
        // Calculate confidence score
        $confidenceScore = $this->calculateConfidenceScore($marketData, $comparables, $vehicleData);
        
        // Save evaluation results
        $this->saveEvaluationResults($evaluationRequestId, [
            'base_value' => $baseValue,
            'condition_adjustment' => $adjustments['condition'],
            'mileage_adjustment' => $adjustments['mileage'],
            'age_adjustment' => $adjustments['age'],
            'market_adjustment' => $adjustments['market'],
            'location_adjustment' => $adjustments['location'],
            'customer_price_adjustment' => $customerPriceAdjustment,
            'customer_expected_price' => $vehicleData['customer_expected_price'],
            'final_value' => $finalValue,
            'value_range_min' => $finalValue * 0.9,
            'value_range_max' => $finalValue * 1.1,
            'confidence_score' => $confidenceScore,
            'market_data' => $marketData,
            'comparables' => $comparables,
            'key_factors' => $this->extractKeyFactors($vehicleData, $adjustments, $customerPriceAdjustment)
        ]);
        
        // Create condition factors
        $this->createConditionFactors($evaluationRequestId, $vehicleData, $adjustments);
        
        // Update request status
        $stmt = $this->db->prepare("
            UPDATE vehicle_evaluation_requests 
            SET status = 'completed' 
            WHERE id = ?
        ");
        $stmt->execute([$evaluationRequestId]);
        
        // Generate report summaries
        $this->generateReportSummaries($evaluationRequestId, $vehicleData, $finalValue);
    }
    
    /**
     * Get market data for vehicle
     */
    private function getMarketData($make, $model, $year) {
        $stmt = $this->db->prepare("
            SELECT * FROM vehicle_market_data 
            WHERE make = ? AND model = ? AND year = ? AND region = 'Egypt'
            ORDER BY data_date DESC LIMIT 1
        ");
        $stmt->execute([$make, $model, $year]);
        return $stmt->fetch();
    }
    
    /**
     * Get comparable vehicles
     */
    private function getComparableVehicles($vehicleData) {
        $stmt = $this->db->prepare("
            SELECT * FROM vehicle_market_data 
            WHERE make = ? AND model = ? AND year BETWEEN ? AND ?
            AND region = 'Egypt'
            ORDER BY ABS(year - ?), sample_size DESC
            LIMIT 5
        ");
        $stmt->execute([
            $vehicleData['make'], 
            $vehicleData['model'], 
            $vehicleData['year'] - 2, 
            $vehicleData['year'] + 2,
            $vehicleData['year']
        ]);
        return $stmt->fetchAll();
    }
    
    /**
     * Calculate base value
     */
    private function calculateBaseValue($marketData, $vehicleData) {
        if ($marketData) {
            $baseValue = $marketData['average_price'];
            
            // Adjust for trim level if available
            if (isset($vehicleData['trim_level']) && $vehicleData['trim_level']) {
                // Premium trims typically add 10-20% to base value
                if (stripos($vehicleData['trim_level'], 'limited') !== false || 
                    stripos($vehicleData['trim_level'], 'premium') !== false ||
                    stripos($vehicleData['trim_level'], 'sport') !== false) {
                    $baseValue *= 1.15;
                }
            }
            
            return $baseValue;
        }
        
        // Fallback calculation based on vehicle age and type
        $age = date('Y') - $vehicleData['year'];
        $baseValue = 500000; // Base value for recent vehicles
        
        // Adjust for age
        if ($age <= 1) $baseValue *= 1.0;
        elseif ($age <= 3) $baseValue *= 0.85;
        elseif ($age <= 5) $baseValue *= 0.70;
        elseif ($age <= 8) $baseValue *= 0.55;
        else $baseValue *= 0.40;
        
        // Adjust for make (premium brands)
        $premiumMakes = ['Mercedes', 'BMW', 'Audi', 'Lexus', 'Infiniti'];
        if (in_array($vehicleData['make'], $premiumMakes)) {
            $baseValue *= 1.5;
        }
        
        return $baseValue;
    }
    
    /**
     * Calculate adjustments based on inspection results
     */
    private function calculateAdjustments($vehicleData) {
        $adjustments = [
            'condition' => 0,
            'mileage' => 0,
            'age' => 0,
            'market' => 0,
            'location' => 0
        ];
        
        // Condition adjustment based on inspection score
        if ($vehicleData['overall_score']) {
            $score = $vehicleData['overall_score'];
            if ($score >= 95) {
                $adjustments['condition'] = 0.10; // +10%
            } elseif ($score >= 90) {
                $adjustments['condition'] = 0.05; // +5%
            } elseif ($score >= 85) {
                $adjustments['condition'] = 0; // No adjustment
            } elseif ($score >= 80) {
                $adjustments['condition'] = -0.05; // -5%
            } elseif ($score >= 70) {
                $adjustments['condition'] = -0.10; // -10%
            } else {
                $adjustments['condition'] = -0.20; // -20%
            }
        }
        
        // Mileage adjustment
        if ($vehicleData['mileage']) {
            $mileage = $vehicleData['mileage'];
            $age = date('Y') - $vehicleData['year'];
            $expectedMileage = $age * 15000; // 15,000 km per year average
            
            if ($mileage < $expectedMileage * 0.5) {
                $adjustments['mileage'] = 0.05; // +5% for low mileage
            } elseif ($mileage > $expectedMileage * 1.5) {
                $adjustments['mileage'] = -0.10; // -10% for high mileage
            } elseif ($mileage > $expectedMileage * 2) {
                $adjustments['mileage'] = -0.20; // -20% for very high mileage
            }
        }
        
        // Age adjustment (additional to base calculation)
        $age = date('Y') - $vehicleData['year'];
        if ($age <= 1) {
            $adjustments['age'] = 0.05; // +5% for new cars
        } elseif ($age >= 10) {
            $adjustments['age'] = -0.10; // -10% for old cars
        }
        
        // Market adjustment (based on market conditions)
        $adjustments['market'] = 0; // Can be updated based on market trends
        
        // Location adjustment (Cairo typically has higher prices)
        $adjustments['location'] = 0.02; // +2% for Cairo market
        
        return $adjustments;
    }
    
    /**
     * Calculate confidence score
     */
    private function calculateConfidenceScore($marketData, $comparables, $vehicleData) {
        $score = 50; // Base score
        
        // Market data availability
        if ($marketData) {
            $score += 20;
            if ($marketData['sample_size'] >= 10) $score += 10;
            if ($marketData['confidence_level'] >= 80) $score += 10;
        }
        
        // Comparables availability
        if (count($comparables) >= 3) {
            $score += 15;
        } elseif (count($comparables) >= 1) {
            $score += 8;
        }
        
        // Inspection data quality
        if ($vehicleData['overall_score']) {
            $score += 15;
        }
        
        return min(100, $score);
    }
    
    /**
     * Save evaluation results
     */
    private function saveEvaluationResults($evaluationRequestId, $results) {
        $stmt = $this->db->prepare("
            INSERT INTO vehicle_evaluation_results 
            (evaluation_request_id, evaluation_provider, evaluation_method, evaluation_date,
             base_value, condition_adjustment, mileage_adjustment, age_adjustment,
             market_adjustment, location_adjustment, final_value, value_range_min,
             value_range_max, confidence_score, evaluation_data, key_factors,
             comparable_vehicles, market_trends, is_primary_evaluation)
            VALUES (?, 'AUTO TESTER', 'automated', NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE)
        ");
        
        $stmt->execute([
            $evaluationRequestId,
            $results['base_value'],
            $results['condition_adjustment'],
            $results['mileage_adjustment'],
            $results['age_adjustment'],
            $results['market_adjustment'],
            $results['location_adjustment'],
            $results['final_value'],
            $results['value_range_min'],
            $results['value_range_max'],
            $results['confidence_score'],
            json_encode([
                'vehicle_data' => $results['vehicle_data'] ?? null,
                'calculation_details' => $results
            ]),
            json_encode($results['key_factors']),
            json_encode($results['comparables']),
            json_encode([
                'market_condition' => 'stable',
                'demand_level' => 'medium',
                'seasonal_trend' => 'neutral'
            ])
        ]);
    }
    
    /**
     * Create condition factors
     */
    private function createConditionFactors($evaluationRequestId, $vehicleData, $adjustments) {
        $factors = [
            [
                'category' => 'mechanical',
                'name_ar' => 'condition',
                'name_en' => 'Overall Condition',
                'impact' => $adjustments['condition'] >= 0 ? 'positive' : 'negative',
                'weight' => 2.0,
                'score' => $vehicleData['overall_score'] ?? 70,
                'value_impact' => $adjustments['condition'],
                'description_ar' => 'Based on comprehensive 200-point inspection results',
                'description_en' => 'Based on comprehensive 200-point inspection results',
                'is_critical' => true
            ],
            [
                'category' => 'mechanical',
                'name_ar' => 'mileage',
                'name_en' => 'Mileage',
                'impact' => $adjustments['mileage'] >= 0 ? 'positive' : 'negative',
                'weight' => 1.5,
                'score' => max(0, 100 - ($vehicleData['mileage'] / 1000)),
                'value_impact' => $adjustments['mileage'],
                'description_ar' => 'Vehicle mileage compared to expected average',
                'description_en' => 'Vehicle mileage compared to expected average',
                'is_critical' => false
            ],
            [
                'category' => 'documentation',
                'name_ar' => 'age',
                'name_en' => 'Vehicle Age',
                'impact' => $adjustments['age'] >= 0 ? 'positive' : 'negative',
                'weight' => 1.0,
                'score' => max(0, 100 - (date('Y') - $vehicleData['year']) * 5),
                'value_impact' => $adjustments['age'],
                'description_ar' => 'Vehicle age and model year',
                'description_en' => 'Vehicle age and model year',
                'is_critical' => false
            ]
        ];
        
        foreach ($factors as $factor) {
            $stmt = $this->db->prepare("
                INSERT INTO vehicle_condition_factors 
                (evaluation_request_id, factor_category, factor_name_ar, factor_name_en,
                 factor_impact, impact_weight, condition_score, value_impact,
                 description_ar, description_en, is_critical)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $evaluationRequestId,
                $factor['category'],
                $factor['name_ar'],
                $factor['name_en'],
                $factor['impact'],
                $factor['weight'],
                $factor['score'],
                $factor['value_impact'],
                $factor['description_ar'],
                $factor['description_en'],
                $factor['is_critical']
            ]);
        }
    }
    
    /**
     * Generate report summaries
     */
    private function generateReportSummaries($evaluationRequestId, $vehicleData, $finalValue) {
        $summaries = [
            [
                'type' => 'executive',
                'highlights_ar' => 'Vehicle valuation completed with high confidence. Market conditions favorable.',
                'highlights_en' => 'Vehicle valuation completed with high confidence. Market conditions favorable.',
                'factors_ar' => 'Excellent condition, low mileage, high demand in market',
                'factors_en' => 'Excellent condition, low mileage, high demand in market',
                'recommendations_ar' => 'Vehicle is priced competitively. Recommended for quick sale.',
                'recommendations_en' => 'Vehicle is priced competitively. Recommended for quick sale.',
                'next_steps_ar' => 'Consider listing in major markets for best exposure.',
                'next_steps_en' => 'Consider listing in major markets for best exposure.'
            ],
            [
                'type' => 'customer',
                'highlights_ar' => 'Based on comprehensive inspection and market analysis',
                'highlights_en' => 'Based on comprehensive inspection and market analysis',
                'factors_ar' => 'Vehicle condition and market demand considered',
                'factors_en' => 'Vehicle condition and market demand considered',
                'recommendations_ar' => 'Fair market value determined for your vehicle',
                'recommendations_en' => 'Fair market value determined for your vehicle',
                'next_steps_ar' => 'Use this valuation for insurance or sale purposes',
                'next_steps_en' => 'Use this valuation for insurance or sale purposes'
            ],
            [
                'type' => 'detailed',
                'highlights_ar' => 'Comprehensive evaluation with multiple data sources',
                'highlights_en' => 'Comprehensive evaluation with multiple data sources',
                'factors_ar' => 'All vehicle systems and market factors analyzed',
                'factors_en' => 'All vehicle systems and market factors analyzed',
                'recommendations_ar' => 'Detailed breakdown available in full report',
                'recommendations_en' => 'Detailed breakdown available in full report',
                'next_steps_ar' => 'Review complete evaluation report for details',
                'next_steps_en' => 'Review complete evaluation report for details'
            ]
        ];
        
        foreach ($summaries as $summary) {
            $stmt = $this->db->prepare("
                INSERT INTO valuation_report_summaries 
                (evaluation_request_id, inspection_request_id, summary_type,
                 primary_value, value_range_min, value_range_max, market_trend,
                 confidence_level, key_highlights_ar, key_highlights_en,
                 value_factors_ar, value_factors_en, recommendations_ar,
                 recommendations_en, next_steps_ar, next_steps_en, summary_data)
                VALUES (?, ?, ?, ?, ?, ?, 'stable', 'medium', ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $evaluationRequestId,
                $vehicleData['inspection_request_id'],
                $summary['type'],
                $finalValue,
                $finalValue * 0.9,
                $finalValue * 1.1,
                $summary['highlights_ar'],
                $summary['highlights_en'],
                $summary['factors_ar'],
                $summary['factors_en'],
                $summary['recommendations_ar'],
                $summary['recommendations_en'],
                $summary['next_steps_ar'],
                $summary['next_steps_en'],
                json_encode([
                    'vehicle_info' => $vehicleData,
                    'evaluation_date' => date('Y-m-d H:i:s'),
                    'data_sources' => ['AUTO TESTER Database', 'Market Analysis', 'Inspection Results']
                ])
            ]);
        }
    }
    
    /**
     * Calculate customer price adjustment
     */
    private function calculateCustomerPriceAdjustment($vehicleData, $baseValue) {
        $customerExpectedPrice = $vehicleData['customer_expected_price'] ?? 0;
        
        if ($customerExpectedPrice <= 0) {
            return 0; // No adjustment if customer didn't provide expected price
        }
        
        $priceDifference = $customerExpectedPrice - $baseValue;
        $percentageDifference = ($priceDifference / $baseValue) * 100;
        
        // Apply adjustment based on how realistic the customer's price is
        if (abs($percentageDifference) <= 10) {
            // Customer price is very close to market value (+/-10%)
            return $priceDifference * 0.3; // Small influence (30%)
        } elseif (abs($percentageDifference) <= 25) {
            // Customer price is somewhat reasonable (+/-25%)
            return $priceDifference * 0.2; // Moderate influence (20%)
        } elseif (abs($percentageDifference) <= 50) {
            // Customer price is somewhat unrealistic (+/-50%)
            return $priceDifference * 0.1; // Small influence (10%)
        } else {
            // Customer price is very unrealistic (>50% difference)
            return 0; // No influence
        }
    }
    
    /**
     * Extract key factors
     */
    private function extractKeyFactors($vehicleData, $adjustments, $customerPriceAdjustment = 0) {
        $factors = [];
        
        foreach ($adjustments as $type => $value) {
            if ($value != 0) {
                $factors[] = [
                    'factor' => ucfirst(str_replace('_', ' ', $type)),
                    'impact' => $value > 0 ? 'positive' : 'negative',
                    'percentage' => abs($value) * 100,
                    'value' => $value
                ];
            }
        }
        
        // Add customer price factor if applicable
        if ($customerPriceAdjustment != 0 && isset($vehicleData['customer_expected_price'])) {
            $factors[] = [
                'factor' => 'Customer Expected Price',
                'impact' => $customerPriceAdjustment > 0 ? 'positive' : 'negative',
                'percentage' => abs($customerPriceAdjustment / $vehicleData['customer_expected_price']) * 100,
                'value' => $customerPriceAdjustment,
                'customer_price' => $vehicleData['customer_expected_price']
            ];
        }
        
        return $factors;
    }
    
    /**
     * Get evaluation details
     */
    public function getEvaluationDetails($evaluationRequestId) {
        try {
            $stmt = $this->db->prepare("
                SELECT ver.*, v.make, v.model, v.year, v.plate_number, v.mileage,
                       u.full_name as customer_name, ins.full_name as inspector_name,
                       vr.final_value, vr.value_range_min, vr.value_range_max,
                       vr.confidence_score, vr.evaluation_provider, vr.evaluation_method,
                       vr.evaluation_date, vr.base_value, vr.condition_adjustment,
                       vr.mileage_adjustment, vr.age_adjustment, vr.market_adjustment,
                       vr.location_adjustment, vr.key_factors, vr.comparable_vehicles
                FROM vehicle_evaluation_requests ver
                JOIN vehicles v ON ver.vehicle_id = v.id
                JOIN users u ON ver.customer_id = u.id
                LEFT JOIN users ins ON ver.requested_by = ins.id
                LEFT JOIN vehicle_evaluation_results vr ON ver.id = vr.evaluation_request_id AND vr.is_primary_evaluation = TRUE
                WHERE ver.id = ?
            ");
            $stmt->execute([$evaluationRequestId]);
            $evaluation = $stmt->fetch();
            
            if (!$evaluation) {
                return ['success' => false, 'message' => 'Evaluation not found'];
            }
            
            // Get condition factors
            $stmt = $this->db->prepare("
                SELECT * FROM vehicle_condition_factors 
                WHERE evaluation_request_id = ?
                ORDER BY factor_category, is_critical DESC, impact_weight DESC
            ");
            $stmt->execute([$evaluationRequestId]);
            $evaluation['condition_factors'] = $stmt->fetchAll();
            
            // Get report summaries
            $stmt = $this->db->prepare("
                SELECT * FROM valuation_report_summaries 
                WHERE evaluation_request_id = ?
                ORDER BY summary_type
            ");
            $stmt->execute([$evaluationRequestId]);
            $evaluation['report_summaries'] = $stmt->fetchAll();
            
            // Get comparable vehicles
            if ($evaluation['comparable_vehicles']) {
                $evaluation['comparable_vehicles'] = json_decode($evaluation['comparable_vehicles'], true);
            }
            
            // Get key factors
            if ($evaluation['key_factors']) {
                $evaluation['key_factors'] = json_decode($evaluation['key_factors'], true);
            }
            
            return ['success' => true, 'data' => $evaluation];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get evaluation for inspection report
     */
    public function getEvaluationForInspection($inspectionRequestId) {
        try {
            $stmt = $this->db->prepare("
                SELECT ver.id as evaluation_request_id, ver.evaluation_type, ver.status,
                       vr.final_value, vr.value_range_min, vr.value_range_max,
                       vr.confidence_score, vr.evaluation_date, vr.evaluation_provider,
                       vrs.key_highlights_ar, vrs.key_highlights_en,
                       vrs.value_factors_ar, vrs.value_factors_en,
                       vrs.recommendations_ar, vrs.recommendations_en
                FROM vehicle_evaluation_requests ver
                LEFT JOIN vehicle_evaluation_results vr ON ver.id = vr.evaluation_request_id AND vr.is_primary_evaluation = TRUE
                LEFT JOIN valuation_report_summaries vrs ON ver.id = vrs.evaluation_request_id AND vrs.summary_type = 'customer'
                WHERE ver.inspection_request_id = ? AND ver.status = 'completed'
                ORDER BY ver.id DESC LIMIT 1
            ");
            $stmt->execute([$inspectionRequestId]);
            $evaluation = $stmt->fetch();
            
            if ($evaluation) {
                return ['success' => true, 'data' => $evaluation];
            } else {
                return ['success' => false, 'message' => 'No evaluation found for this inspection'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Quick valuation for customer widget
     */
    public function quickValuation($data) {
        try {
            // Validate required fields
            $required = ['make', 'model', 'year', 'mileage', 'condition'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Get market data
            $marketData = $this->getMarketData($data['make'], $data['model'], $data['year']);
            
            // Calculate base value
            $baseValue = $this->calculateBaseValue($marketData, $data);
            
            // Calculate adjustments
            $adjustments = $this->calculateQuickAdjustments($data);
            
            // Calculate final value
            $finalValue = $baseValue + $adjustments['condition'] + $adjustments['mileage'] + $adjustments['age'];
            
            // Calculate confidence score
            $confidenceScore = $this->calculateQuickConfidence($marketData, $data);
            
            // Generate key factors
            $keyFactors = [
                [
                    'name' => 'Market Base Value',
                    'impact' => 'neutral',
                    'percentage' => 0,
                    'value' => $baseValue
                ],
                [
                    'name' => 'Condition Adjustment',
                    'impact' => $adjustments['condition'] >= 0 ? 'positive' : 'negative',
                    'percentage' => abs($adjustments['condition'] / $baseValue * 100),
                    'value' => $adjustments['condition']
                ],
                [
                    'name' => 'Mileage Adjustment',
                    'impact' => $adjustments['mileage'] >= 0 ? 'positive' : 'negative',
                    'percentage' => abs($adjustments['mileage'] / $baseValue * 100),
                    'value' => $adjustments['mileage']
                ],
                [
                    'name' => 'Age Adjustment',
                    'impact' => $adjustments['age'] >= 0 ? 'positive' : 'negative',
                    'percentage' => abs($adjustments['age'] / $baseValue * 100),
                    'value' => $adjustments['age']
                ]
            ];
            
            return [
                'success' => true,
                'message' => 'Quick valuation calculated successfully',
                'data' => [
                    'final_value' => round($finalValue),
                    'value_range_min' => round($finalValue * 0.9),
                    'value_range_max' => round($finalValue * 1.1),
                    'confidence_score' => $confidenceScore,
                    'base_value' => round($baseValue),
                    'key_factors' => $keyFactors,
                    'market_data_available' => !empty($marketData),
                    'calculation_date' => date('Y-m-d H:i:s')
                ]
            ];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Calculate quick adjustments for customer valuation
     */
    private function calculateQuickAdjustments($data) {
        $adjustments = [
            'condition' => 0,
            'mileage' => 0,
            'age' => 0
        ];
        
        // Condition adjustment
        switch ($data['condition']) {
            case 'excellent':
                $adjustments['condition'] = 0.15; // +15%
                break;
            case 'good':
                $adjustments['condition'] = 0.05; // +5%
                break;
            case 'fair':
                $adjustments['condition'] = -0.05; // -5%
                break;
            case 'poor':
                $adjustments['condition'] = -0.20; // -20%
                break;
        }
        
        // Mileage adjustment
        $age = date('Y') - $data['year'];
        $expectedMileage = $age * 15000;
        $actualMileage = $data['mileage'];
        
        if ($actualMileage < $expectedMileage * 0.5) {
            $adjustments['mileage'] = 0.08; // +8% for low mileage
        } elseif ($actualMileage > $expectedMileage * 1.5) {
            $adjustments['mileage'] = -0.12; // -12% for high mileage
        } elseif ($actualMileage > $expectedMileage * 2) {
            $adjustments['mileage'] = -0.25; // -25% for very high mileage
        }
        
        // Age adjustment
        if ($age <= 1) {
            $adjustments['age'] = 0.05; // +5% for new cars
        } elseif ($age >= 10) {
            $adjustments['age'] = -0.15; // -15% for old cars
        } elseif ($age >= 15) {
            $adjustments['age'] = -0.25; // -25% for very old cars
        }
        
        return $adjustments;
    }
    
    /**
     * Calculate quick confidence score
     */
    private function calculateQuickConfidence($marketData, $data) {
        $score = 50; // Base score
        
        // Market data availability
        if ($marketData) {
            $score += 25;
            if ($marketData['sample_size'] >= 5) $score += 10;
        }
        
        // Data completeness
        if (isset($data['trim']) && $data['trim']) $score += 5;
        if (isset($data['fuelType']) && $data['fuelType']) $score += 5;
        if (isset($data['transmission']) && $data['transmission']) $score += 5;
        
        return min(100, $score);
    }
    
    /**
     * Save customer valuation
     */
    public function saveCustomerValuation($data) {
        try {
            // Validate required fields
            $required = ['user_id', 'valuation_data', 'vehicle_info'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Create valuation record
            $stmt = $this->db->prepare("
                INSERT INTO customer_valuations 
                (user_id, vehicle_make, vehicle_model, vehicle_year, vehicle_condition,
                 mileage, trim_level, fuel_type, transmission, body_type,
                 valuation_value, value_range_min, value_range_max, confidence_score,
                 valuation_data, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $result = $stmt->execute([
                $data['user_id'],
                $data['vehicle_info']['make'],
                $data['vehicle_info']['model'],
                $data['vehicle_info']['year'],
                $data['vehicle_info']['condition'],
                $data['valuation_data']['final_value'],
                $data['valuation_data']['value_range_min'],
                $data['valuation_data']['value_range_max'],
                $data['valuation_data']['confidence_score'],
                json_encode($data['valuation_data'])
            ]);
            
            if ($result) {
                return [
                    'success' => true,
                    'message' => 'Valuation saved successfully',
                    'valuation_id' => $this->db->lastInsertId()
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to save valuation'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update market data
     */
    public function updateMarketData($data) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO vehicle_market_data 
                (make, model, year, trim_level, body_type, fuel_type, transmission, engine_size,
                 region, average_price, price_range_min, price_range_max, sample_size,
                 data_source, data_date, market_condition, demand_level, confidence_level, notes)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                average_price = VALUES(average_price),
                price_range_min = VALUES(price_range_min),
                price_range_max = VALUES(price_range_max),
                sample_size = VALUES(sample_size),
                market_condition = VALUES(market_condition),
                demand_level = VALUES(demand_level),
                confidence_level = VALUES(confidence_level),
                notes = VALUES(notes),
                updated_at = NOW()
            ");
            
            $result = $stmt->execute([
                $data['make'],
                $data['model'],
                $data['year'],
                $data['trim_level'] ?? null,
                $data['body_type'] ?? null,
                $data['fuel_type'] ?? null,
                $data['transmission'] ?? null,
                $data['engine_size'] ?? null,
                $data['region'] ?? 'Egypt',
                $data['average_price'],
                $data['price_range_min'],
                $data['price_range_max'],
                $data['sample_size'] ?? 1,
                $data['data_source'],
                $data['data_date'],
                $data['market_condition'] ?? 'good',
                $data['demand_level'] ?? 'medium',
                $data['confidence_level'] ?? 80,
                $data['notes'] ?? null
            ]);
            
            if ($result) {
                return ['success' => true, 'message' => 'Market data updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update market data'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
}

// API Endpoint Handler
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$vehicleEvaluation = new VehicleEvaluation();
$endpoint = $_GET['endpoint'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($endpoint) {
        case 'requests':
            if ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($vehicleEvaluation->createEvaluationRequest($data));
            } elseif ($method === 'GET') {
                $evaluationRequestId = $_GET['id'] ?? null;
                if ($evaluationRequestId) {
                    echo json_encode($vehicleEvaluation->getEvaluationDetails($evaluationRequestId));
                } else {
                    echo json_encode(['success' => false, 'message' => 'Evaluation ID required']);
                }
            }
            break;
            
        case 'inspection':
            if ($method === 'GET') {
                $inspectionRequestId = $_GET['inspection_id'] ?? null;
                if ($inspectionRequestId) {
                    echo json_encode($vehicleEvaluation->getEvaluationForInspection($inspectionRequestId));
                } else {
                    echo json_encode(['success' => false, 'message' => 'Inspection ID required']);
                }
            }
            break;
            
        case 'market-data':
            if ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($vehicleEvaluation->updateMarketData($data));
            }
            break;
            
        case 'quick-valuation':
            if ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($vehicleEvaluation->quickValuation($data));
            }
            break;
            
        case 'save-valuation':
            if ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($vehicleEvaluation->saveCustomerValuation($data));
            }
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}
?>
