<?php
/**
 * AUTO TESTER - Team Inspection API
 * Multi-inspector collaborative inspection system
 */

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

class TeamInspections {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create team inspection request
     */
    public function createTeamInspection($data) {
        try {
            // Validate required fields
            $required = ['team_id', 'inspection_type_id', 'customer_id', 'requested_by'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Generate unique request number
            $requestNumber = $this->generateTeamRequestNumber();
            
            // Create team inspection request
            $stmt = $this->db->prepare("
                INSERT INTO team_inspection_requests 
                (request_number, team_id, primary_vehicle_id, inspection_type_id, customer_id,
                 requested_by, priority_level, inspection_mode, estimated_duration_minutes,
                 scheduled_start_time, scheduled_end_time, location_type, location_address,
                 special_instructions, equipment_needed, safety_requirements, status, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'assigned', NOW())
            ");
            
            $result = $stmt->execute([
                $requestNumber,
                $data['team_id'],
                $data['primary_vehicle_id'] ?? null,
                $data['inspection_type_id'],
                $data['customer_id'],
                $data['requested_by'],
                $data['priority_level'] ?? 'medium',
                $data['inspection_mode'] ?? 'single_vehicle',
                $data['estimated_duration_minutes'] ?? 60,
                $data['scheduled_start_time'] ?? null,
                $data['scheduled_end_time'] ?? null,
                $data['location_type'] ?? 'center',
                $data['location_address'] ?? null,
                $data['special_instructions'] ?? null,
                json_encode($data['equipment_needed'] ?? []),
                json_encode($data['safety_requirements'] ?? [])
            ]);
            
            if ($result) {
                $requestId = $this->db->lastInsertId();
                
                // Add vehicles if provided
                if (isset($data['vehicles']) && is_array($data['vehicles'])) {
                    $this->addVehiclesToInspection($requestId, $data['vehicles']);
                }
                
                // Create default tasks based on inspection type
                $this->createDefaultTasks($requestId, $data['inspection_type_id'], $data['team_id']);
                
                // Notify team members
                $this->notifyTeamMembers($data['team_id'], $requestId);
                
                return [
                    'success' => true,
                    'message' => 'Team inspection created successfully',
                    'request_id' => $requestId,
                    'request_number' => $requestNumber
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to create team inspection'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Add vehicles to team inspection
     */
    private function addVehiclesToInspection($requestId, $vehicles) {
        foreach ($vehicles as $index => $vehicle) {
            $stmt = $this->db->prepare("
                INSERT INTO team_inspection_vehicles 
                (team_request_id, vehicle_id, vehicle_sequence, inspection_priority, assigned_inspectors)
                VALUES (?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $requestId,
                $vehicle['vehicle_id'],
                $vehicle['sequence'] ?? $index + 1,
                $vehicle['priority'] ?? 'secondary',
                json_encode($vehicle['assigned_inspectors'] ?? [])
            ]);
        }
    }
    
    /**
     * Create default tasks for team inspection
     */
    private function createDefaultTasks($requestId, $inspectionTypeId, $teamId) {
        // Get inspection points for the type
        $stmt = $this->db->prepare("
            SELECT ip.* FROM inspection_points ip
            JOIN inspection_type_points itp ON ip.id = itp.point_id
            WHERE itp.inspection_type_id = ?
            ORDER BY ip.point_order
        ");
        $stmt->execute([$inspectionTypeId]);
        $points = $stmt->fetchAll();
        
        // Get team members for assignment
        $stmt = $this->db->prepare("
            SELECT tm.inspector_id, tm.role_in_team, tm.specialization_area
            FROM team_members tm
            WHERE tm.team_id = ? AND tm.is_active = TRUE
            ORDER BY tm.role_in_team DESC
        ");
        $stmt->execute([$teamId]);
        $teamMembers = $stmt->fetchAll();
        
        // Assign tasks to team members
        $taskOrder = 1;
        foreach ($points as $point) {
            $assignedInspector = $this->assignTaskToInspector($point, $teamMembers);
            
            $stmt = $this->db->prepare("
                INSERT INTO team_inspection_tasks 
                (team_request_id, task_name, task_description, task_category,
                 assigned_inspector_id, support_inspectors, inspection_point_id,
                 task_order, estimated_duration_minutes, task_dependencies,
                 required_tools, safety_precautions)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $requestId,
                $point['point_name_ar'],
                $point['description_ar'],
                $point['category'],
                $assignedInspector['inspector_id'],
                json_encode($this->getSupportInspectors($assignedInspector, $teamMembers)),
                $point['id'],
                $taskOrder++,
                $point['estimated_duration_minutes'] ?? 30,
                json_encode($point['dependencies'] ?? []),
                json_encode($point['required_tools'] ?? []),
                json_encode($point['safety_precautions'] ?? [])
            ]);
        }
    }
    
    /**
     * Assign task to appropriate inspector
     */
    private function assignTaskToInspector($point, $teamMembers) {
        // Find inspector with matching specialization
        foreach ($teamMembers as $member) {
            if ($member['specialization_area'] && 
                stripos($member['specialization_area'], $point['category']) !== false) {
                return $member;
            }
        }
        
        // Assign to senior inspector if no specialization match
        foreach ($teamMembers as $member) {
            if ($member['role_in_team'] === 'senior_inspector') {
                return $member;
            }
        }
        
        // Default to first available inspector
        return $teamMembers[0] ?? ['inspector_id' => 1];
    }
    
    /**
     * Get support inspectors for task
     */
    private function getSupportInspectors($assignedInspector, $teamMembers) {
        $support = [];
        foreach ($teamMembers as $member) {
            if ($member['inspector_id'] !== $assignedInspector['inspector_id']) {
                $support[] = $member['inspector_id'];
                if (count($support) >= 2) break; // Max 2 support inspectors
            }
        }
        return $support;
    }
    
    /**
     * Get team inspection details
     */
    public function getTeamInspection($requestId) {
        try {
            $stmt = $this->db->prepare("
                SELECT tir.*, it.team_name, it.team_code, itype.type_name_ar,
                       u.full_name as customer_name, req.full_name as requested_by_name
                FROM team_inspection_requests tir
                JOIN inspection_teams it ON tir.team_id = it.id
                JOIN inspection_types itype ON tir.inspection_type_id = itype.id
                JOIN users u ON tir.customer_id = u.id
                JOIN users req ON tir.requested_by = req.id
                WHERE tir.id = ?
            ");
            $stmt->execute([$requestId]);
            $request = $stmt->fetch();
            
            if (!$request) {
                return ['success' => false, 'message' => 'Team inspection not found'];
            }
            
            // Get vehicles
            $stmt = $this->db->prepare("
                SELECT tiv.*, v.make, v.model, v.year, v.plate_number
                FROM team_inspection_vehicles tiv
                JOIN vehicles v ON tiv.vehicle_id = v.id
                WHERE tiv.team_request_id = ?
                ORDER BY tiv.vehicle_sequence
            ");
            $stmt->execute([$requestId]);
            $request['vehicles'] = $stmt->fetchAll();
            
            // Get tasks
            $stmt = $this->db->prepare("
                SELECT tit.*, u.full_name as assigned_inspector_name
                FROM team_inspection_tasks tit
                JOIN users u ON tit.assigned_inspector_id = u.id
                WHERE tit.team_request_id = ?
                ORDER BY tit.task_order
            ");
            $stmt->execute([$requestId]);
            $request['tasks'] = $stmt->fetchAll();
            
            // Get team members
            $stmt = $this->db->prepare("
                SELECT tm.*, u.full_name, u.phone
                FROM team_members tm
                JOIN users u ON tm.inspector_id = u.id
                WHERE tm.team_id = ? AND tm.is_active = TRUE
            ");
            $stmt->execute([$request['team_id']]);
            $request['team_members'] = $stmt->fetchAll();
            
            // Get communication log
            $stmt = $this->db->prepare("
                SELECT tcl.*, u.full_name as sender_name
                FROM team_communication_log tcl
                JOIN users u ON tcl.sender_id = u.id
                WHERE tcl.team_request_id = ?
                ORDER BY tcl.created_at DESC
                LIMIT 50
            ");
            $stmt->execute([$requestId]);
            $request['communications'] = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $request];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update task status
     */
    public function updateTaskStatus($taskId, $data) {
        try {
            $stmt = $this->db->prepare("
                UPDATE team_inspection_tasks 
                SET task_status = ?, completion_percentage = ?, task_notes = ?, 
                    task_result_data = ?, updated_at = NOW()
                WHERE id = ?
            ");
            
            $result = $stmt->execute([
                $data['task_status'],
                $data['completion_percentage'] ?? 0,
                $data['task_notes'] ?? null,
                json_encode($data['task_result_data'] ?? []),
                $taskId
            ]);
            
            if ($result) {
                // Update timestamps based on status
                if ($data['task_status'] === 'in_progress') {
                    $stmt = $this->db->prepare("UPDATE team_inspection_tasks SET started_at = NOW() WHERE id = ?");
                    $stmt->execute([$taskId]);
                } elseif ($data['task_status'] === 'completed') {
                    $stmt = $this->db->prepare("UPDATE team_inspection_tasks SET completed_at = NOW() WHERE id = ?");
                    $stmt->execute([$taskId]);
                }
                
                // Log activity
                $this->logTaskActivity($taskId, $data['task_status'], $data['inspector_id']);
                
                return ['success' => true, 'message' => 'Task updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update task'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Send team message
     */
    public function sendTeamMessage($data) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO team_communication_log 
                (team_request_id, sender_id, message_type, message_content, 
                 message_data, recipients, is_urgent, message_priority)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $result = $stmt->execute([
                $data['team_request_id'],
                $data['sender_id'],
                $data['message_type'] ?? 'text',
                $data['message_content'],
                json_encode($data['message_data'] ?? []),
                json_encode($data['recipients'] ?? []),
                $data['is_urgent'] ?? false,
                $data['message_priority'] ?? 'medium'
            ]);
            
            if ($result) {
                // Notify recipients if urgent
                if ($data['is_urgent'] ?? false) {
                    $this->notifyRecipients($data['team_request_id'], $data['sender_id'], $data['recipients'] ?? []);
                }
                
                return ['success' => true, 'message' => 'Message sent successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to send message'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get team performance metrics
     */
    public function getTeamPerformance($teamId, $dateRange = '30') {
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM team_performance_metrics 
                WHERE team_id = ? AND metric_date >= DATE_SUB(CURRENT_DATE, INTERVAL ? DAY)
                ORDER BY metric_date DESC
            ");
            $stmt->execute([$teamId, $dateRange]);
            $metrics = $stmt->fetchAll();
            
            // Calculate averages
            $averages = [
                'avg_quality_score' => 0,
                'avg_efficiency_score' => 0,
                'avg_satisfaction_score' => 0,
                'total_inspections' => 0,
                'completion_rate' => 0
            ];
            
            if (!empty($metrics)) {
                $totalQuality = 0;
                $totalEfficiency = 0;
                $totalSatisfaction = 0;
                $totalInspections = 0;
                $completedInspections = 0;
                
                foreach ($metrics as $metric) {
                    if ($metric['quality_score_average']) $totalQuality += $metric['quality_score_average'];
                    if ($metric['team_efficiency_score']) $totalEfficiency += $metric['team_efficiency_score'];
                    if ($metric['customer_satisfaction_score']) $totalSatisfaction += $metric['customer_satisfaction_score'];
                    $totalInspections += $metric['total_inspections'];
                    $completedInspections += $metric['completed_inspections'];
                }
                
                $count = count($metrics);
                $averages['avg_quality_score'] = round($totalQuality / $count, 2);
                $averages['avg_efficiency_score'] = round($totalEfficiency / $count, 2);
                $averages['avg_satisfaction_score'] = round($totalSatisfaction / $count, 2);
                $averages['total_inspections'] = $totalInspections;
                $averages['completion_rate'] = $totalInspections > 0 ? round(($completedInspections / $totalInspections) * 100, 2) : 0;
            }
            
            return [
                'success' => true,
                'data' => [
                    'daily_metrics' => $metrics,
                    'averages' => $averages
                ]
            ];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get available teams for assignment
     */
    public function getAvailableTeams($centerId = null, $specialization = null) {
        try {
            $sql = "
                SELECT it.*, u.full_name as team_leader_name,
                       COUNT(tir.id) as active_inspections
                FROM inspection_teams it
                JOIN users u ON it.team_leader_id = u.id
                LEFT JOIN team_inspection_requests tir ON it.id = tir.team_id 
                    AND tir.status IN ('assigned', 'in_progress')
                WHERE it.is_active = TRUE
            ";
            
            $params = [];
            
            if ($centerId) {
                $sql .= " AND it.center_id = ?";
                $params[] = $centerId;
            }
            
            if ($specialization) {
                $sql .= " AND it.specialization = ?";
                $params[] = $specialization;
            }
            
            $sql .= " GROUP BY it.id ORDER BY it.team_name";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            $teams = $stmt->fetchAll();
            
            // Get team members for each team
            foreach ($teams as &$team) {
                $stmt = $this->db->prepare("
                    SELECT tm.*, u.full_name, u.phone
                    FROM team_members tm
                    JOIN users u ON tm.inspector_id = u.id
                    WHERE tm.team_id = ? AND tm.is_active = TRUE
                    ORDER BY tm.role_in_team DESC
                ");
                $stmt->execute([$team['id']]);
                $team['members'] = $stmt->fetchAll();
            }
            
            return ['success' => true, 'data' => $teams];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Generate unique team request number
     */
    private function generateTeamRequestNumber() {
        $prefix = 'TEAM';
        $date = date('Ym');
        $sequence = 1;
        
        $stmt = $this->db->prepare("
            SELECT request_number FROM team_inspection_requests 
            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);
    }
    
    /**
     * Notify team members of new assignment
     */
    private function notifyTeamMembers($teamId, $requestId) {
        $stmt = $this->db->prepare("
            SELECT inspector_id FROM team_members 
            WHERE team_id = ? AND is_active = TRUE
        ");
        $stmt->execute([$teamId]);
        $members = $stmt->fetchAll();
        
        foreach ($members as $member) {
            $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 (?, 'team_assignment', ?, 'inspector', ?, ?, ?, ?, 'in_app', 'high', 1, NOW())
            ");
            
            $stmt->execute([
                $requestId,
                $member['inspector_id'],
                'Team Inspection Assignment',
                'Team Inspection Assignment',
                'You have been assigned to a team inspection. Please check your dashboard for details.',
                'You have been assigned to a team inspection. Please check your dashboard for details.'
            ]);
        }
    }
    
    /**
     * Log task activity
     */
    private function logTaskActivity($taskId, $status, $inspectorId) {
        $stmt = $this->db->prepare("
            SELECT team_request_id, task_name FROM team_inspection_tasks WHERE id = ?
        ");
        $stmt->execute([$taskId]);
        $task = $stmt->fetch();
        
        if ($task) {
            $activityType = $status === 'completed' ? 'task_completed' : 'task_started';
            $description = $status === 'completed' ? 
                "Task \"{$task['task_name']}\" completed" : 
                "Task \"{$task['task_name']}\" started";
            
            $stmt = $this->db->prepare("
                INSERT INTO team_activity_stream 
                (team_request_id, actor_id, activity_type, activity_description, activity_data)
                VALUES (?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $task['team_request_id'],
                $inspectorId,
                $activityType,
                $description,
                json_encode(['task_id' => $taskId, 'task_name' => $task['task_name'], 'status' => $status])
            ]);
        }
    }
    
    /**
     * Notify recipients of urgent messages
     */
    private function notifyRecipients($teamRequestId, $senderId, $recipients) {
        if (empty($recipients)) {
            // Get all team members
            $stmt = $this->db->prepare("
                SELECT tm.inspector_id FROM team_members tm
                JOIN team_inspection_requests tir ON tm.team_id = tir.team_id
                WHERE tir.id = ? AND tm.is_active = TRUE AND tm.inspector_id != ?
            ");
            $stmt->execute([$teamRequestId, $senderId]);
            $members = $stmt->fetchAll();
            $recipients = array_column($members, 'inspector_id');
        }
        
        foreach ($recipients as $recipientId) {
            $stmt = $this->db->prepare("
                INSERT INTO workflow_notifications 
                (notification_type, recipient_id, recipient_role,
                 title_ar, title_en, message_ar, message_en, channels, priority, created_at)
                VALUES ('urgent_message', ?, 'inspector', ?, ?, ?, ?, 'in_app', 'critical', NOW())
            ");
            
            $stmt->execute([
                $recipientId,
                'Urgent Team Message',
                'Urgent Team Message',
                'You have received an urgent message from your team. Please check immediately.',
                'You have received an urgent message from your team. Please check immediately.'
            ]);
        }
    }
}

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

$teamInspections = new TeamInspections();
$endpoint = $_GET['endpoint'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($endpoint) {
        case 'requests':
            if ($method === 'GET') {
                $requestId = $_GET['id'] ?? null;
                if ($requestId) {
                    echo json_encode($teamInspections->getTeamInspection($requestId));
                } else {
                    echo json_encode(['success' => false, 'message' => 'Request ID required']);
                }
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($teamInspections->createTeamInspection($data));
            }
            break;
            
        case 'tasks':
            if ($method === 'PUT') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($teamInspections->updateTaskStatus($data['task_id'], $data));
            }
            break;
            
        case 'messages':
            if ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($teamInspections->sendTeamMessage($data));
            }
            break;
            
        case 'teams':
            if ($method === 'GET') {
                $centerId = $_GET['center_id'] ?? null;
                $specialization = $_GET['specialization'] ?? null;
                echo json_encode($teamInspections->getAvailableTeams($centerId, $specialization));
            }
            break;
            
        case 'performance':
            if ($method === 'GET') {
                $teamId = $_GET['team_id'] ?? null;
                $dateRange = $_GET['date_range'] ?? '30';
                if ($teamId) {
                    echo json_encode($teamInspections->getTeamPerformance($teamId, $dateRange));
                } else {
                    echo json_encode(['success' => false, 'message' => 'Team 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()]);
}
?>
