<?php
/**
 * AUTO TESTER - Inspection Workflow API
 * Handles all inspection workflow operations including requests, stages, and notifications
 */

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

class InspectionWorkflow {
    private $db;
    private $currentUser;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->currentUser = $this->getCurrentUser();
    }
    
    /**
     * Get current authenticated user
     */
    private function getCurrentUser() {
        $headers = getallheaders();
        $token = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (empty($token)) {
            return null;
        }
        
        $token = str_replace('Bearer ', '', $token);
        
        try {
            $stmt = $this->db->prepare("
                SELECT id, role, permissions, full_name, email, status 
                FROM users 
                WHERE api_token = ? AND status = 'active'
            ");
            $stmt->execute([$token]);
            return $stmt->fetch();
        } catch (Exception $e) {
            return null;
        }
    }
    
    /**
     * Check if user has permission for workflow action
     */
    private function hasPermission($permission) {
        if (!$this->currentUser) {
            return false;
        }
        
        $role = $this->currentUser['role'];
        
        switch ($permission) {
            case 'view_requests':
                return in_array($role, ['admin', 'supervisor', 'inspector']);
            case 'manage_requests':
                return in_array($role, ['admin', 'supervisor']);
            case 'execute_inspection':
                return $role === 'inspector';
            case 'approve_requests':
                return in_array($role, ['admin', 'supervisor']);
            case 'view_reports':
                return in_array($role, ['admin', 'supervisor', 'inspector']);
            default:
                return false;
        }
    }
    
    /**
     * Get inspection types
     */
    public function getInspectionTypes($includeInactive = false) {
        if (!$this->hasPermission('view_requests')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $activeCondition = $includeInactive ? '' : 'AND is_active = 1';
            
            $stmt = $this->db->prepare("
                SELECT * FROM inspection_types 
                WHERE 1=1 $activeCondition
                ORDER BY sort_order, type_name_ar
            ");
            $stmt->execute();
            $types = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $types];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get inspection points for a type
     */
    public function getInspectionPoints($typeId) {
        if (!$this->hasPermission('view_requests')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM inspection_points 
                WHERE inspection_type_id = ? AND is_active = 1
                ORDER BY point_category, point_order
            ");
            $stmt->execute([$typeId]);
            $points = $stmt->fetchAll();
            
            // Group by category
            $groupedPoints = [];
            foreach ($points as $point) {
                $groupedPoints[$point['point_category']][] = $point;
            }
            
            return ['success' => true, 'data' => $groupedPoints];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Create inspection request
     */
    public function createInspectionRequest($data) {
        if (!$this->hasPermission('manage_requests') && $this->currentUser['role'] !== 'customer') {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Validate required fields
            $required = ['inspection_type_id', 'vehicle_make', 'vehicle_model', 'vehicle_year'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Generate unique request number
            $requestNumber = $this->generateRequestNumber();
            
            // Insert inspection request
            $stmt = $this->db->prepare("
                INSERT INTO inspection_requests_enhanced 
                (request_number, customer_id, inspection_type_id, vehicle_make, vehicle_model,
                 vehicle_year, vehicle_color, vehicle_vin, vehicle_plate_number, vehicle_mileage,
                 vehicle_engine_type, vehicle_transmission, preferred_date, preferred_time,
                 location_type, mobile_address, special_instructions, urgency_level,
                 quoted_price, current_stage, current_status, source, ip_address, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'registration', 'draft', ?, ?, NOW())
            ");
            
            $result = $stmt->execute([
                $requestNumber,
                $data['customer_id'] ?? $this->currentUser['id'],
                $data['inspection_type_id'],
                $data['vehicle_make'],
                $data['vehicle_model'],
                $data['vehicle_year'],
                $data['vehicle_color'] ?? '',
                $data['vehicle_vin'] ?? '',
                $data['vehicle_plate_number'] ?? '',
                $data['vehicle_mileage'] ?? 0,
                $data['vehicle_engine_type'] ?? 'gasoline',
                $data['vehicle_transmission'] ?? 'manual',
                $data['preferred_date'] ?? null,
                $data['preferred_time'] ?? null,
                $data['location_type'] ?? 'center',
                $data['mobile_address'] ?? '',
                $data['special_instructions'] ?? '',
                $data['urgency_level'] ?? 'normal',
                $data['quoted_price'] ?? 0,
                $data['source'] ?? 'web',
                $_SERVER['REMOTE_ADDR'] ?? ''
            ]);
            
            if ($result) {
                $requestId = $this->db->lastInsertId();
                
                // Send notification to supervisors
                $this->sendWorkflowNotification($requestId, 'stage_change', 'supervisor', 
                    'New inspection request submitted', 'A new inspection request has been submitted and requires your review');
                
                return [
                    'success' => true, 
                    'message' => 'Inspection request created successfully',
                    'request_id' => $requestId,
                    'request_number' => $requestNumber
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to create inspection request'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get inspection requests
     */
    public function getInspectionRequests($status = 'all', $role = null) {
        if (!$this->hasPermission('view_requests')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $whereConditions = [];
            $params = [];
            
            // Filter by status
            if ($status !== 'all') {
                $whereConditions[] = "ire.current_status = ?";
                $params[] = $status;
            }
            
            // Filter by user role
            if ($role === 'customer') {
                $whereConditions[] = "ire.customer_id = ?";
                $params[] = $this->currentUser['id'];
            } elseif ($role === 'inspector') {
                $whereConditions[] = "ire.assigned_inspector_id = ?";
                $params[] = $this->currentUser['id'];
            } elseif ($role === 'supervisor') {
                $whereConditions[] = "ire.assigned_supervisor_id = ? OR ire.assigned_supervisor_id IS NULL";
                $params[] = $this->currentUser['id'];
            }
            
            $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
            
            $stmt = $this->db->prepare("
                SELECT 
                    ire.*,
                    it.type_name_ar,
                    it.type_name_en,
                    it.estimated_duration_minutes,
                    it.base_price,
                    u.full_name as customer_name,
                    u.phone as customer_phone,
                    u.email as customer_email,
                    insp.full_name as inspector_name,
                    sup.full_name as supervisor_name,
                    ws.stage_name_ar as current_stage_name,
                    ws.stage_name_en as current_stage_name_en
                FROM inspection_requests_enhanced ire
                JOIN inspection_types it ON ire.inspection_type_id = it.id
                JOIN users u ON ire.customer_id = u.id
                LEFT JOIN users insp ON ire.assigned_inspector_id = insp.id
                LEFT JOIN users sup ON ire.assigned_supervisor_id = sup.id
                LEFT JOIN inspection_workflow_stages ws ON ire.current_stage = ws.stage_code
                $whereClause
                ORDER BY ire.created_at DESC
            ");
            
            $stmt->execute($params);
            $requests = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $requests];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update inspection request status
     */
    public function updateRequestStatus($requestId, $data) {
        if (!$this->hasPermission('manage_requests')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Get current request
            $stmt = $this->db->prepare("SELECT * FROM inspection_requests_enhanced WHERE id = ?");
            $stmt->execute([$requestId]);
            $currentRequest = $stmt->fetch();
            
            if (!$currentRequest) {
                return ['success' => false, 'message' => 'Inspection request not found'];
            }
            
            // Update status
            $updateFields = [];
            $updateValues = [];
            
            if (isset($data['current_status'])) {
                $updateFields[] = "current_status = ?";
                $updateValues[] = $data['current_status'];
                
                // Update timestamps based on status
                if ($data['current_status'] === 'submitted' && !$currentRequest['submitted_at']) {
                    $updateFields[] = "submitted_at = NOW()";
                } elseif ($data['current_status'] === 'approved' && !$currentRequest['approved_at']) {
                    $updateFields[] = "approved_at = NOW()";
                } elseif ($data['current_status'] === 'completed' && !$currentRequest['completed_at']) {
                    $updateFields[] = "completed_at = NOW()";
                }
            }
            
            if (isset($data['current_stage'])) {
                $updateFields[] = "current_stage = ?";
                $updateValues[] = $data['current_stage'];
            }
            
            if (isset($data['assigned_inspector_id'])) {
                $updateFields[] = "assigned_inspector_id = ?";
                $updateValues[] = $data['assigned_inspector_id'];
                $updateFields[] = "assigned_at = NOW()";
            }
            
            if (isset($data['assigned_supervisor_id'])) {
                $updateFields[] = "assigned_supervisor_id = ?";
                $updateValues[] = $data['assigned_supervisor_id'];
            }
            
            if (isset($data['priority_level'])) {
                $updateFields[] = "priority_level = ?";
                $updateValues[] = $data['priority_level'];
            }
            
            if (empty($updateFields)) {
                return ['success' => false, 'message' => 'No valid fields to update'];
            }
            
            $updateFields[] = "updated_at = NOW()";
            $updateValues[] = $requestId;
            
            $sql = "UPDATE inspection_requests_enhanced SET " . implode(', ', $updateFields) . " WHERE id = ?";
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute($updateValues);
            
            if ($result) {
                // Send notifications based on status change
                if (isset($data['current_status']) && $data['current_status'] !== $currentRequest['current_status']) {
                    $this->sendStatusChangeNotifications($requestId, $data['current_status'], $currentRequest);
                }
                
                return ['success' => true, 'message' => 'Request status updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update request status'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Submit inspection results
     */
    public function submitInspectionResults($requestId, $results) {
        if (!$this->hasPermission('execute_inspection')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Validate request belongs to current inspector
            $stmt = $this->db->prepare("
                SELECT * FROM inspection_requests_enhanced 
                WHERE id = ? AND assigned_inspector_id = ? AND current_status = 'in_progress'
            ");
            $stmt->execute([$requestId, $this->currentUser['id']]);
            $request = $stmt->fetch();
            
            if (!$request) {
                return ['success' => false, 'message' => 'Invalid request or not assigned to you'];
            }
            
            // Start transaction
            $this->db->beginTransaction();
            
            try {
                // Insert/update results for each point
                foreach ($results as $result) {
                    $stmt = $this->db->prepare("
                        INSERT INTO inspection_results 
                        (inspection_request_id, inspection_point_id, inspector_id,
                         result_value, result_numeric, result_text, result_score,
                         photo_evidence, video_evidence, document_evidence,
                         measurement_data, confidence_level, compliance_status, risk_level,
                         inspected_at, time_taken_seconds, device_used, gps_coordinates,
                         weather_conditions, lighting_conditions)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ON DUPLICATE KEY UPDATE
                        result_value = VALUES(result_value),
                        result_numeric = VALUES(result_numeric),
                        result_text = VALUES(result_text),
                        result_score = VALUES(result_score),
                        photo_evidence = VALUES(photo_evidence),
                        video_evidence = VALUES(video_evidence),
                        document_evidence = VALUES(document_evidence),
                        measurement_data = VALUES(measurement_data),
                        confidence_level = VALUES(confidence_level),
                        compliance_status = VALUES(compliance_status),
                        risk_level = VALUES(risk_level),
                        inspected_at = VALUES(inspected_at),
                        time_taken_seconds = VALUES(time_taken_seconds),
                        device_used = VALUES(device_used),
                        gps_coordinates = VALUES(gps_coordinates),
                        weather_conditions = VALUES(weather_conditions),
                        lighting_conditions = VALUES(lighting_conditions)
                    ");
                    
                    $stmt->execute([
                        $requestId,
                        $result['inspection_point_id'],
                        $this->currentUser['id'],
                        $result['result_value'] ?? '',
                        $result['result_numeric'] ?? null,
                        $result['result_text'] ?? '',
                        $result['result_score'] ?? 0,
                        json_encode($result['photo_evidence'] ?? []),
                        json_encode($result['video_evidence'] ?? []),
                        json_encode($result['document_evidence'] ?? []),
                        json_encode($result['measurement_data'] ?? []),
                        $result['confidence_level'] ?? 'medium',
                        $result['compliance_status'] ?? 'compliant',
                        $result['risk_level'] ?? 'low',
                        $result['inspected_at'] ?? date('Y-m-d H:i:s'),
                        $result['time_taken_seconds'] ?? 0,
                        $result['device_used'] ?? '',
                        $result['gps_coordinates'] ?? null,
                        $result['weather_conditions'] ?? '',
                        $result['lighting_conditions'] ?? ''
                    ]);
                }
                
                // Update request status to completed
                $stmt = $this->db->prepare("
                    UPDATE inspection_requests_enhanced 
                    SET current_status = 'completed', 
                        completed_at = NOW(),
                        current_stage = 'report_generation'
                    WHERE id = ?
                ");
                $stmt->execute([$requestId]);
                
                // Calculate overall score
                $this->calculateInspectionScore($requestId);
                
                // Generate report
                $this->generateInspectionReport($requestId);
                
                // Send notification to supervisor
                $this->sendWorkflowNotification($requestId, 'completion', 'supervisor', 
                    'Inspection completed', 'Inspection has been completed and requires your review');
                
                $this->db->commit();
                
                return ['success' => true, 'message' => 'Inspection results submitted successfully'];
                
            } catch (Exception $e) {
                $this->db->rollback();
                throw $e;
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get inspection results
     */
    public function getInspectionResults($requestId) {
        if (!$this->hasPermission('view_reports')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Check if user has access to this request
            $stmt = $this->db->prepare("
                SELECT * FROM inspection_requests_enhanced 
                WHERE id = ? AND (
                    customer_id = ? OR 
                    assigned_inspector_id = ? OR 
                    assigned_supervisor_id = ? OR
                    ? IN (SELECT id FROM users WHERE role = 'admin')
                )
            ");
            $stmt->execute([$requestId, $this->currentUser['id'], $this->currentUser['id'], $this->currentUser['id'], $this->currentUser['id']]);
            $request = $stmt->fetch();
            
            if (!$request) {
                return ['success' => false, 'message' => 'Access denied'];
            }
            
            // Get results with point details
            $stmt = $this->db->prepare("
                SELECT 
                    ir.*,
                    ip.point_code,
                    ip.point_name_ar,
                    ip.point_name_en,
                    ip.point_category,
                    ip.point_priority,
                    ip.is_required,
                    ip.requires_photo,
                    ip.result_options
                FROM inspection_results ir
                JOIN inspection_points ip ON ir.inspection_point_id = ip.id
                WHERE ir.inspection_request_id = ?
                ORDER BY ip.point_category, ip.point_order
            ");
            $stmt->execute([$requestId]);
            $results = $stmt->fetchAll();
            
            // Group results by category
            $groupedResults = [];
            foreach ($results as $result) {
                $groupedResults[$result['point_category']][] = $result;
            }
            
            return ['success' => true, 'data' => $groupedResults];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get workflow stages
     */
    public function getWorkflowStages() {
        if (!$this->hasPermission('view_requests')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM inspection_workflow_stages 
                WHERE is_active = 1
                ORDER BY stage_order
            ");
            $stmt->execute();
            $stages = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $stages];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get notifications for current user
     */
    public function getNotifications($unreadOnly = false) {
        if (!$this->currentUser) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $unreadCondition = $unreadOnly ? 'AND read_at IS NULL' : '';
            
            $stmt = $this->db->prepare("
                SELECT wn.*, ire.request_number, ire.current_status
                FROM workflow_notifications wn
                LEFT JOIN inspection_requests_enhanced ire ON wn.inspection_request_id = ire.id
                WHERE wn.recipient_id = ? $unreadCondition
                ORDER BY wn.created_at DESC
                LIMIT 50
            ");
            $stmt->execute([$this->currentUser['id']]);
            $notifications = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $notifications];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Mark notification as read
     */
    public function markNotificationRead($notificationId) {
        if (!$this->currentUser) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $stmt = $this->db->prepare("
                UPDATE workflow_notifications 
                SET read_at = NOW() 
                WHERE id = ? AND recipient_id = ?
            ");
            $result = $stmt->execute([$notificationId, $this->currentUser['id']]);
            
            if ($result) {
                return ['success' => true, 'message' => 'Notification marked as read'];
            } else {
                return ['success' => false, 'message' => 'Failed to mark notification as read'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Generate unique request number
     */
    private function generateRequestNumber() {
        $prefix = 'REQ';
        $date = date('Ym');
        $sequence = 1;
        
        // Get last sequence for today
        $stmt = $this->db->prepare("
            SELECT request_number FROM inspection_requests_enhanced 
            WHERE request_number LIKE ? 
            ORDER BY id DESC LIMIT 1
        ");
        $stmt->execute(["{$prefix}{$date}%"]);
        $lastRequest = $stmt->fetch();
        
        if ($lastRequest) {
            $lastSequence = intval(substr($lastRequest['request_number'], -4));
            $sequence = $lastSequence + 1;
        }
        
        return $prefix . $date . str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }
    
    /**
     * Send workflow notification
     */
    private function sendWorkflowNotification($requestId, $type, $recipientRole, $title, $message) {
        try {
            // Get recipients based on role
            $recipientCondition = '';
            switch ($recipientRole) {
                case 'supervisor':
                    $recipientCondition = "assigned_supervisor_id";
                    break;
                case 'inspector':
                    $recipientCondition = "assigned_inspector_id";
                    break;
                case 'customer':
                    $recipientCondition = "customer_id";
                    break;
                default:
                    return;
            }
            
            $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, created_at)
                SELECT ?, ?, $recipientCondition, ?, ?, ?, ?, ?, 'in_app', 'medium', NOW()
                FROM inspection_requests_enhanced 
                WHERE id = ? AND $recipientCondition IS NOT NULL
            ");
            
            $stmt->execute([
                $requestId,
                $type,
                $recipientRole,
                $title,
                $title,
                $message,
                $message,
                $requestId
            ]);
            
        } catch (Exception $e) {
            error_log("Error sending workflow notification: " . $e->getMessage());
        }
    }
    
    /**
     * Send status change notifications
     */
    private function sendStatusChangeNotifications($requestId, $newStatus, $request) {
        try {
            switch ($newStatus) {
                case 'submitted':
                    $this->sendWorkflowNotification($requestId, 'stage_change', 'supervisor', 
                        'Request submitted', 'New inspection request requires your review');
                    break;
                case 'approved':
                    $this->sendWorkflowNotification($requestId, 'stage_change', 'inspector', 
                        'Request approved', 'You have been assigned a new inspection');
                    break;
                case 'assigned':
                    $this->sendWorkflowNotification($requestId, 'assignment', 'inspector', 
                        'Inspection assigned', 'You have been assigned to an inspection');
                    break;
                case 'completed':
                    $this->sendWorkflowNotification($requestId, 'completion', 'customer', 
                        'Inspection completed', 'Your inspection has been completed');
                    break;
            }
        } catch (Exception $e) {
            error_log("Error sending status change notifications: " . $e->getMessage());
        }
    }
    
    /**
     * Calculate inspection score
     */
    private function calculateInspectionScore($requestId) {
        try {
            $stmt = $this->db->prepare("
                SELECT AVG(result_score) as avg_score,
                       COUNT(*) as total_points,
                       SUM(CASE WHEN compliance_status = 'compliant' THEN 1 ELSE 0 END) as compliant_points
                FROM inspection_results 
                WHERE inspection_request_id = ?
            ");
            $stmt->execute([$requestId]);
            $scoreData = $stmt->fetch();
            
            if ($scoreData) {
                $overallScore = $scoreData['avg_score'];
                $complianceRate = ($scoreData['compliant_points'] / $scoreData['total_points']) * 100;
                
                // Determine grade
                $grade = 'C';
                if ($overallScore >= 95) $grade = 'A+';
                elseif ($overallScore >= 90) $grade = 'A';
                elseif ($overallScore >= 85) $grade = 'B+';
                elseif ($overallScore >= 80) $grade = 'B';
                elseif ($overallScore >= 75) $grade = 'C+';
                elseif ($overallScore >= 70) $grade = 'C';
                elseif ($overallScore >= 60) $grade = 'D';
                else $grade = 'F';
                
                // Update request with score
                $stmt = $this->db->prepare("
                    UPDATE inspection_requests_enhanced 
                    SET quality_score = ?, grade = ? 
                    WHERE id = ?
                ");
                $stmt->execute([$overallScore, $grade, $requestId]);
            }
            
        } catch (Exception $e) {
            error_log("Error calculating inspection score: " . $e->getMessage());
        }
    }
    
    /**
     * Generate inspection report
     */
    private function generateInspectionReport($requestId) {
        try {
            // Generate report number
            $reportNumber = 'RPT' . date('Ym') . str_pad($requestId, 6, '0', STR_PAD_LEFT);
            
            // Create report record
            $stmt = $this->db->prepare("
                INSERT INTO inspection_reports 
                (inspection_request_id, report_number, report_type, 
                 report_title_ar, report_title_en, generated_by, generated_at)
                VALUES (?, ?, ?, ?, ?, ?, NOW())
            ");
            
            $stmt->execute([
                $requestId,
                $reportNumber,
                'standard',
                ' inspection Report',
                'Inspection Report',
                $this->currentUser['id']
            ]);
            
            // Update request with report reference
            $stmt = $this->db->prepare("
                UPDATE inspection_requests_enhanced 
                SET current_stage = 'final_delivery'
                WHERE id = ?
            ");
            $stmt->execute([$requestId]);
            
        } catch (Exception $e) {
            error_log("Error generating inspection report: " . $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);
}

$workflow = new InspectionWorkflow();
$endpoint = $_GET['endpoint'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($endpoint) {
        case 'inspection-types':
            if ($method === 'GET') {
                $includeInactive = $_GET['include_inactive'] === 'true';
                echo json_encode($workflow->getInspectionTypes($includeInactive));
            }
            break;
            
        case 'inspection-points':
            if ($method === 'GET') {
                $typeId = $_GET['type_id'];
                echo json_encode($workflow->getInspectionPoints($typeId));
            }
            break;
            
        case 'requests':
            if ($method === 'GET') {
                $status = $_GET['status'] ?? 'all';
                $role = $_GET['role'] ?? null;
                echo json_encode($workflow->getInspectionRequests($status, $role));
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($workflow->createInspectionRequest($data));
            }
            break;
            
        case 'request-status':
            if ($method === 'PUT') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($workflow->updateRequestStatus($data['request_id'], $data));
            }
            break;
            
        case 'inspection-results':
            if ($method === 'GET') {
                $requestId = $_GET['request_id'];
                echo json_encode($workflow->getInspectionResults($requestId));
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($workflow->submitInspectionResults($data['request_id'], $data['results']));
            }
            break;
            
        case 'workflow-stages':
            if ($method === 'GET') {
                echo json_encode($workflow->getWorkflowStages());
            }
            break;
            
        case 'notifications':
            if ($method === 'GET') {
                $unreadOnly = $_GET['unread_only'] === 'true';
                echo json_encode($workflow->getNotifications($unreadOnly));
            } elseif ($method === 'PUT') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($workflow->markNotificationRead($data['notification_id']));
            }
            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()]);
}
?>
