<?php
/**
 * AUTO TESTER - Comprehensive Inspection API
 * Complete 200-point inspection system with auto-population and workflow
 */

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

class ComprehensiveInspections {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create comprehensive inspection request
     */
    public function createInspectionRequest($data) {
        try {
            // Validate required fields
            $required = ['customer_id', 'vehicle_id', 'inspection_type_id', 'requested_by'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Generate unique inspection number
            $inspectionNumber = $this->generateInspectionNumber();
            
            // Create inspection request
            $stmt = $this->db->prepare("
                INSERT INTO comprehensive_inspection_requests 
                (inspection_number, customer_id, vehicle_id, inspection_type_id, requested_by,
                 priority_level, special_instructions, customer_expected_price, scheduled_date, scheduled_time,
                 location, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $result = $stmt->execute([
                $inspectionNumber,
                $data['customer_id'],
                $data['vehicle_id'],
                $data['inspection_type_id'],
                $data['requested_by'],
                $data['priority_level'] ?? 'medium',
                $data['special_instructions'] ?? null,
                $data['customer_expected_price'] ?? null,
                $data['scheduled_date'] ?? null,
                $data['scheduled_time'] ?? null,
                $data['location'] ?? null
            ]);
            
            if ($result) {
                $inspectionId = $this->db->lastInsertId();
                
                // Initialize inspection points and workflow
                $this->initializeInspectionPoints($inspectionId);
                $this->initializeWorkflowStages($inspectionId);
                
                // Add timeline event
                $this->addTimelineEvent($inspectionId, 'request_created', 
                    'Inspection request created', 'Inspection request created', 
                    $data['requested_by'], ['inspection_number' => $inspectionNumber]);
                
                // Notify inspector
                $this->notifyInspector($data['requested_by'], $inspectionId);
                
                return [
                    'success' => true,
                    'message' => 'Comprehensive inspection request created successfully',
                    'inspection_id' => $inspectionId,
                    'inspection_number' => $inspectionNumber
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to create inspection request'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Initialize inspection points for new request
     */
    private function initializeInspectionPoints($inspectionId) {
        // Get all active inspection points
        $stmt = $this->db->prepare("
            SELECT id, point_number, point_name_ar, point_name_en, section_id, 
                   point_type, pass_fail_type, weight_in_section, is_critical,
                   requires_photo, estimated_time_seconds
            FROM comprehensive_inspection_points 
            WHERE is_active = TRUE 
            ORDER BY section_id, point_order
        ");
        $stmt->execute();
        $points = $stmt->fetchAll();
        
        // Insert all points for this inspection
        foreach ($points as $point) {
            $stmt = $this->db->prepare("
                INSERT INTO comprehensive_inspection_results 
                (inspection_request_id, point_id, inspector_id, result_status, created_at)
                VALUES (?, ?, NULL, 'not_inspected', NOW())
            ");
            $stmt->execute([$inspectionId, $point['id']]);
        }
        
        // Initialize section summaries
        $stmt = $this->db->prepare("
            SELECT DISTINCT section_id, COUNT(*) as total_points
            FROM comprehensive_inspection_points 
            WHERE is_active = TRUE 
            GROUP BY section_id
        ");
        $stmt->execute();
        $sections = $stmt->fetchAll();
        
        foreach ($sections as $section) {
            $stmt = $this->db->prepare("
                INSERT INTO comprehensive_section_results 
                (inspection_request_id, section_id, total_points_in_section, 
                 points_inspected, points_passed, points_failed, points_not_applicable, created_at)
                VALUES (?, ?, ?, 0, 0, 0, 0, NOW())
            ");
            $stmt->execute([$inspectionId, $section['section_id'], $section['total_points']]);
        }
    }
    
    /**
     * Initialize workflow stages
     */
    private function initializeWorkflowStages($inspectionId) {
        $stages = [
            ['preparation', 'Preparation Stage'],
            ['inspection', 'Inspection Stage'],
            ['documentation', 'Documentation Stage'],
            ['review', 'Review Stage'],
            ['completion', 'Completion Stage']
        ];
        
        foreach ($stages as $stage) {
            $stmt = $this->db->prepare("
                INSERT INTO comprehensive_inspection_workflow 
                (inspection_request_id, stage_name, stage_type, stage_status, created_at)
                VALUES (?, ?, ?, 'not_started', NOW())
            ");
            $stmt->execute([$inspectionId, $stage[1], $stage[0]]);
        }
    }
    
    /**
     * Get comprehensive inspection details
     */
    public function getInspectionDetails($inspectionId) {
        try {
            $stmt = $this->db->prepare("
                SELECT cir.*, 
                       u.full_name as customer_name, u.phone as customer_phone,
                       v.make, v.model, v.year, v.plate_number, v.vin,
                       ins.full_name as inspector_name, ins.phone as inspector_phone,
                       sup.full_name as supervisor_name,
                       it.type_name_ar, it.type_name_en
                FROM comprehensive_inspection_requests cir
                JOIN users u ON cir.customer_id = u.id
                JOIN vehicles v ON cir.vehicle_id = v.id
                JOIN users ins ON cir.inspector_id = ins.id
                LEFT JOIN users sup ON cir.supervisor_id = sup.id
                JOIN inspection_types it ON cir.inspection_type_id = it.id
                WHERE cir.id = ?
            ");
            $stmt->execute([$inspectionId]);
            $inspection = $stmt->fetch();
            
            if (!$inspection) {
                return ['success' => false, 'message' => 'Inspection not found'];
            }
            
            // Get sections with progress
            $stmt = $this->db->prepare("
                SELECT csr.*, cis.section_name_ar, cis.section_name_en, 
                       cis.section_code, cis.section_category
                FROM comprehensive_section_results csr
                JOIN comprehensive_inspection_sections cis ON csr.section_id = cis.id
                WHERE csr.inspection_request_id = ?
                ORDER BY cis.section_order
            ");
            $stmt->execute([$inspectionId]);
            $inspection['sections'] = $stmt->fetchAll();
            
            // Get points for each section
            foreach ($inspection['sections'] as &$section) {
                $stmt = $this->db->prepare("
                    SELECT cir.*, cip.point_number, cip.point_name_ar, cip.point_name_en,
                           cip.point_description_ar, cip.point_description_en,
                           cip.inspection_method_ar, cip.inspection_method_en,
                           cip.acceptance_criteria_ar, cip.acceptance_criteria_en,
                           cip.point_type, cip.pass_fail_type, cip.measurement_unit,
                           cip.min_acceptable_value, cip.max_acceptable_value,
                           cip.is_critical, cip.requires_photo, cip.requires_measurement,
                           cip.estimated_time_seconds, cip.notes_template_ar, cip.notes_template_en
                    FROM comprehensive_inspection_results cir
                    JOIN comprehensive_inspection_points cip ON cir.point_id = cip.id
                    WHERE cir.inspection_request_id = ? AND cip.section_id = ?
                    ORDER BY cip.point_order
                ");
                $stmt->execute([$inspectionId, $section['section_id']]);
                $section['points'] = $stmt->fetchAll();
            }
            
            // Get workflow stages
            $stmt = $this->db->prepare("
                SELECT ciw.*, u.full_name as assigned_name
                FROM comprehensive_inspection_workflow ciw
                LEFT JOIN users u ON ciw.assigned_to = u.id
                WHERE ciw.inspection_request_id = ?
                ORDER BY ciw.id
            ");
            $stmt->execute([$inspectionId]);
            $inspection['workflow'] = $stmt->fetchAll();
            
            // Get timeline events
            $stmt = $this->db->prepare("
                SELECT cit.*, u.full_name as performer_name
                FROM comprehensive_inspection_timeline cit
                JOIN users u ON cit.performed_by = u.id
                WHERE cit.inspection_request_id = ?
                ORDER BY cit.event_timestamp DESC
                LIMIT 50
            ");
            $stmt->execute([$inspectionId]);
            $inspection['timeline'] = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $inspection];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update inspection point result
     */
    public function updatePointResult($data) {
        try {
            // Validate required fields
            $required = ['inspection_request_id', 'point_id', 'inspector_id', 'result_status'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Validate result status
            $validStatuses = ['pass', 'fail', 'not_applicable', 'not_inspected'];
            if (!in_array($data['result_status'], $validStatuses)) {
                return ['success' => false, 'message' => 'Invalid result status'];
            }
            
            // Update point result
            $stmt = $this->db->prepare("
                UPDATE comprehensive_inspection_results 
                SET result_status = ?, result_value = ?, result_grade = ?, 
                    notes_ar = ?, notes_en = ?, findings_ar = ?, findings_en = ?,
                    recommendations_ar = ?, recommendations_en = ?, photo_evidence = ?,
                    measurement_data = ?, tool_used = ?, time_taken_seconds = ?,
                    confidence_level = ?, requires_follow_up = ?, follow_up_priority = ?,
                    is_critical_finding = ?, updated_at = NOW()
                WHERE inspection_request_id = ? AND point_id = ? AND inspector_id = ?
            ");
            
            $result = $stmt->execute([
                $data['result_status'],
                $data['result_value'] ?? null,
                $data['result_grade'] ?? null,
                $data['notes_ar'] ?? null,
                $data['notes_en'] ?? null,
                $data['findings_ar'] ?? null,
                $data['findings_en'] ?? null,
                $data['recommendations_ar'] ?? null,
                $data['recommendations_en'] ?? null,
                json_encode($data['photo_evidence'] ?? []),
                json_encode($data['measurement_data'] ?? []),
                $data['tool_used'] ?? null,
                $data['time_taken_seconds'] ?? null,
                $data['confidence_level'] ?? 'high',
                $data['requires_follow_up'] ?? false,
                $data['follow_up_priority'] ?? 'medium',
                $data['is_critical_finding'] ?? false,
                $data['inspection_request_id'],
                $data['point_id'],
                $data['inspector_id']
            ]);
            
            if ($result) {
                // Add timeline event
                $this->addTimelineEvent($data['inspection_request_id'], 'point_inspected',
                    'Point inspected and result recorded', 'Point inspected and result recorded',
                    $data['inspector_id'], [
                        'point_id' => $data['point_id'],
                        'result_status' => $data['result_status'],
                        'is_critical_finding' => $data['is_critical_finding'] ?? false
                    ]);
                
                // Update inspection status if starting
                $this->updateInspectionStatus($data['inspection_request_id']);
                
                return ['success' => true, 'message' => 'Point result updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update point result'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update inspection status based on progress
     */
    private function updateInspectionStatus($inspectionId) {
        // Check if inspection should be marked as in progress
        $stmt = $this->db->prepare("
            SELECT status, start_time FROM comprehensive_inspection_requests WHERE id = ?
        ");
        $stmt->execute([$inspectionId]);
        $inspection = $stmt->fetch();
        
        if ($inspection && $inspection['status'] === 'assigned' && !$inspection['start_time']) {
            // Start inspection
            $stmt = $this->db->prepare("
                UPDATE comprehensive_inspection_requests 
                SET status = 'in_progress', start_time = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$inspectionId]);
            
            // Update workflow stage
            $stmt = $this->db->prepare("
                UPDATE comprehensive_inspection_workflow 
                SET stage_status = 'in_progress', started_at = NOW()
                WHERE inspection_request_id = ? AND stage_type = 'inspection'
            ");
            $stmt->execute([$inspectionId]);
        }
        
        // Check if inspection is complete
        $stmt = $this->db->prepare("
            SELECT 
                COUNT(*) as total_points,
                SUM(CASE WHEN result_status != 'not_inspected' THEN 1 ELSE 0 END) as inspected_points,
                SUM(CASE WHEN result_status = 'pass' THEN 1 ELSE 0 END) as passed_points,
                SUM(CASE WHEN result_status = 'fail' THEN 1 ELSE 0 END) as failed_points
            FROM comprehensive_inspection_results 
            WHERE inspection_request_id = ?
        ");
        $stmt->execute([$inspectionId]);
        $progress = $stmt->fetch();
        
        if ($progress && $progress['inspected_points'] == $progress['total_points']) {
            // Calculate final scores and complete inspection
            $this->calculateFinalScores($inspectionId);
            
            $stmt = $this->db->prepare("
                UPDATE comprehensive_inspection_requests 
                SET status = 'completed', completion_time = NOW(),
                    actual_duration_minutes = TIMESTAMPDIFF(MINUTE, start_time, NOW()),
                    completed_points = ?, overall_score = ?, grade = ?, pass_fail_status = ?
                WHERE id = ?
            ");
            
            $finalData = $this->calculateFinalScores($inspectionId);
            $stmt->execute([
                $progress['inspected_points'],
                $finalData['overall_score'],
                $finalData['grade'],
                $finalData['pass_fail_status'],
                $inspectionId
            ]);
            
            // Update workflow stage
            $stmt = $this->db->prepare("
                UPDATE comprehensive_inspection_workflow 
                SET stage_status = 'completed', completed_at = NOW()
                WHERE inspection_request_id = ? AND stage_type = 'inspection'
            ");
            $stmt->execute([$inspectionId]);
        }
    }
    
    /**
     * Calculate final scores and grades
     */
    private function calculateFinalScores($inspectionId) {
        // Get section results
        $stmt = $this->db->prepare("
            SELECT csr.*, cis.weight_percentage
            FROM comprehensive_section_results csr
            JOIN comprehensive_inspection_sections cis ON csr.section_id = cis.id
            WHERE csr.inspection_request_id = ?
        ");
        $stmt->execute([$inspectionId]);
        $sections = $stmt->fetchAll();
        
        $totalWeightedScore = 0;
        $totalWeight = 0;
        
        foreach ($sections as $section) {
            if ($section['points_inspected'] > 0) {
                $sectionScore = ($section['points_passed'] / $section['points_inspected']) * 100;
                $weightedScore = ($sectionScore / 100) * $section['weight_percentage'];
                $totalWeightedScore += $weightedScore;
                $totalWeight += $section['weight_percentage'];
                
                // Update section score
                $sectionGrade = $this->calculateGrade($sectionScore);
                $sectionStatus = $sectionScore >= 70 ? 'pass' : 'fail';
                
                $stmt = $this->db->prepare("
                    UPDATE comprehensive_section_results 
                    SET section_score = ?, section_grade = ?, section_status = ?
                    WHERE inspection_request_id = ? AND section_id = ?
                ");
                $stmt->execute([$sectionScore, $sectionGrade, $sectionStatus, $inspectionId, $section['section_id']]);
            }
        }
        
        // Calculate overall score
        $overallScore = $totalWeight > 0 ? ($totalWeightedScore / $totalWeight) * 100 : 0;
        $grade = $this->calculateGrade($overallScore);
        $passFailStatus = $overallScore >= 70 ? 'pass' : 'fail';
        
        return [
            'overall_score' => round($overallScore, 2),
            'grade' => $grade,
            'pass_fail_status' => $passFailStatus
        ];
    }
    
    /**
     * Calculate grade based on score
     */
    private function calculateGrade($score) {
        if ($score >= 95) return 'A+';
        if ($score >= 90) return 'A';
        if ($score >= 85) return 'B+';
        if ($score >= 80) return 'B';
        if ($score >= 75) return 'C+';
        if ($score >= 70) return 'C';
        if ($score >= 60) return 'D';
        return 'F';
    }
    
    /**
     * Get inspection sections and points
     */
    public function getInspectionStructure() {
        try {
            $stmt = $this->db->prepare("
                SELECT cis.*, 
                       (SELECT COUNT(*) FROM comprehensive_inspection_points cip 
                        WHERE cip.section_id = cis.id AND cip.is_active = TRUE) as point_count
                FROM comprehensive_inspection_sections cis
                WHERE cis.is_active = TRUE
                ORDER BY cis.section_order
            ");
            $stmt->execute();
            $sections = $stmt->fetchAll();
            
            foreach ($sections as &$section) {
                $stmt = $this->db->prepare("
                    SELECT * FROM comprehensive_inspection_points 
                    WHERE section_id = ? AND is_active = TRUE 
                    ORDER BY point_order
                ");
                $stmt->execute([$section['id']]);
                $section['points'] = $stmt->fetchAll();
            }
            
            return ['success' => true, 'data' => $sections];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Generate inspection report
     */
    public function generateReport($inspectionId, $reportType = 'final') {
        try {
            // Get inspection details
            $inspection = $this->getInspectionDetails($inspectionId);
            if (!$inspection['success']) {
                return $inspection;
            }
            
            $data = $inspection['data'];
            
            // Generate report number
            $reportNumber = 'RPT-' . $data['inspection_number'] . '-' . strtoupper($reportType);
            
            // Create report record
            $stmt = $this->db->prepare("
                INSERT INTO comprehensive_inspection_reports 
                (inspection_request_id, report_number, report_type, report_format,
                 generated_by, report_data, is_final_report, generation_date)
                VALUES (?, ?, ?, 'json', ?, ?, ?, NOW())
            ");
            
            $reportData = [
                'inspection' => $data,
                'report_type' => $reportType,
                'generated_at' => date('Y-m-d H:i:s'),
                'summary' => $this->generateReportSummary($data)
            ];
            
            $result = $stmt->execute([
                $inspectionId,
                $reportNumber,
                $reportType,
                1, // Current user ID (should be passed as parameter)
                json_encode($reportData),
                $reportType === 'final'
            ]);
            
            if ($result) {
                $reportId = $this->db->lastInsertId();
                
                // Add timeline event
                $this->addTimelineEvent($inspectionId, 'report_generated',
                    'Inspection report generated', 'Inspection report generated',
                    1, ['report_type' => $reportType, 'report_number' => $reportNumber]);
                
                return [
                    'success' => true,
                    'message' => 'Report generated successfully',
                    'report_id' => $reportId,
                    'report_number' => $reportNumber,
                    'report_data' => $reportData
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to generate report'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Generate report summary
     */
    private function generateReportSummary($data) {
        $totalPoints = $data['total_points'];
        $completedPoints = $data['completed_points'];
        $passedPoints = 0;
        $failedPoints = 0;
        $criticalIssues = 0;
        
        foreach ($data['sections'] as $section) {
            $passedPoints += $section['points_passed'];
            $failedPoints += $section['points_failed'];
        }
        
        $summary = [
            'total_points' => $totalPoints,
            'completed_points' => $completedPoints,
            'passed_points' => $passedPoints,
            'failed_points' => $failedPoints,
            'pass_rate' => $completedPoints > 0 ? round(($passedPoints / $completedPoints) * 100, 2) : 0,
            'overall_score' => $data['overall_score'],
            'grade' => $data['grade'],
            'pass_fail_status' => $data['pass_fail_status'],
            'critical_issues_count' => $criticalIssues,
            'inspection_duration' => $data['actual_duration_minutes']
        ];
        
        // Add vehicle evaluation data if available
        $evaluationData = $this->getVehicleEvaluationForInspection($data['id']);
        if ($evaluationData['success']) {
            $summary['vehicle_evaluation'] = [
                'final_value' => $evaluationData['data']['final_value'],
                'value_range_min' => $evaluationData['data']['value_range_min'],
                'value_range_max' => $evaluationData['data']['value_range_max'],
                'confidence_score' => $evaluationData['data']['confidence_score'],
                'evaluation_provider' => $evaluationData['data']['evaluation_provider'],
                'key_highlights_ar' => $evaluationData['data']['key_highlights_ar'],
                'key_highlights_en' => $evaluationData['data']['key_highlights_en'],
                'value_factors_ar' => $evaluationData['data']['value_factors_ar'],
                'value_factors_en' => $evaluationData['data']['value_factors_en'],
                'recommendations_ar' => $evaluationData['data']['recommendations_ar'],
                'recommendations_en' => $evaluationData['data']['recommendations_en']
            ];
        }
        
        return $summary;
    }
    
    /**
     * Get vehicle evaluation for inspection
     */
    private function getVehicleEvaluationForInspection($inspectionId) {
        try {
            // Include vehicle evaluation API
            require_once __DIR__ . '/vehicle-evaluation.php';
            $vehicleEvaluation = new VehicleEvaluation();
            return $vehicleEvaluation->getEvaluationForInspection($inspectionId);
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Evaluation data not available'];
        }
    }
    
    /**
     * Generate unique inspection number
     */
    private function generateInspectionNumber() {
        $prefix = 'COMP';
        $date = date('Ym');
        $sequence = 1;
        
        $stmt = $this->db->prepare("
            SELECT inspection_number FROM comprehensive_inspection_requests 
            WHERE inspection_number LIKE ? 
            ORDER BY id DESC LIMIT 1
        ");
        $stmt->execute(["{$prefix}{$date}%"]);
        $lastInspection = $stmt->fetch();
        
        if ($lastInspection) {
            $lastSequence = intval(substr($lastInspection['inspection_number'], -4));
            $sequence = $lastSequence + 1;
        }
        
        return $prefix . $date . str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }
    
    /**
     * Add timeline event
     */
    private function addTimelineEvent($inspectionId, $eventType, $descriptionAr, $descriptionEn, $performedBy, $eventData = []) {
        $stmt = $this->db->prepare("
            INSERT INTO comprehensive_inspection_timeline 
            (inspection_request_id, event_type, event_description_ar, event_description_en,
             event_data, performed_by, event_timestamp)
            VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $inspectionId,
            $eventType,
            $descriptionAr,
            $descriptionEn,
            json_encode($eventData),
            $performedBy
        ]);
    }
    
    /**
     * Notify inspector
     */
    private function notifyInspector($inspectorId, $inspectionId) {
        $stmt = $this->db->prepare("
            INSERT INTO workflow_notifications 
            (inspection_request_id, notification_type, recipient_id, recipient_role,
             title_ar, title_en, message_ar, message_en, channels, priority, requires_action, created_at)
            VALUES (?, 'inspection_assigned', ?, 'inspector', ?, ?, ?, ?, 'in_app', 'high', 1, NOW())
        ");
        
        $stmt->execute([
            $inspectionId,
            $inspectorId,
            'Comprehensive Inspection Assigned',
            'Comprehensive Inspection Assigned',
            'You have been assigned a comprehensive 200-point inspection. Please review the details and begin the inspection process.',
            'You have been assigned a comprehensive 200-point inspection. Please review the details and begin the inspection process.'
        ]);
    }
}

// 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);
}

$comprehensiveInspections = new ComprehensiveInspections();
$endpoint = $_GET['endpoint'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($endpoint) {
        case 'requests':
            if ($method === 'GET') {
                $inspectionId = $_GET['id'] ?? null;
                if ($inspectionId) {
                    echo json_encode($comprehensiveInspections->getInspectionDetails($inspectionId));
                } else {
                    echo json_encode(['success' => false, 'message' => 'Inspection ID required']);
                }
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($comprehensiveInspections->createInspectionRequest($data));
            }
            break;
            
        case 'points':
            if ($method === 'PUT') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($comprehensiveInspections->updatePointResult($data));
            }
            break;
            
        case 'structure':
            if ($method === 'GET') {
                echo json_encode($comprehensiveInspections->getInspectionStructure());
            }
            break;
            
        case 'reports':
            if ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                $inspectionId = $data['inspection_id'] ?? null;
                $reportType = $data['report_type'] ?? 'final';
                if ($inspectionId) {
                    echo json_encode($comprehensiveInspections->generateReport($inspectionId, $reportType));
                } else {
                    echo json_encode(['success' => false, 'message' => 'Inspection ID required']);
                }
            }
            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()]);
}
?>
