<?php
/**
 * AUTO TESTER - Quality Metrics API
 * Provides quality control metrics for supervisor dashboard
 * Created: 2026-04-22
 */

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

require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../includes/Database.php';

class QualityMetrics {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    /**
     * Get quality metrics overview
     */
    public function getQualityMetrics($period = 'today') {
        try {
            $periodCondition = $this->getPeriodCondition($period);
            
            // Get inspector performance metrics
            $inspectorPerformance = $this->getInspectorPerformance($periodCondition);
            
            // Get QC review metrics
            $qcReviews = $this->getQCReviewMetrics($periodCondition);
            
            // Get customer complaints metrics
            $customerComplaints = $this->getCustomerComplaintsMetrics($periodCondition);
            
            // Get system health metrics
            $systemHealth = $this->getSystemHealthMetrics();
            
            // Calculate overall quality score
            $overallScore = $this->calculateOverallQualityScore([
                $inspectorPerformance,
                $qcReviews,
                $customerComplaints,
                $systemHealth
            ]);
            
            return [
                'success' => true,
                'data' => [
                    'period' => $period,
                    'overall_score' => $overallScore,
                    'inspector_performance' => $inspectorPerformance,
                    'qc_reviews' => $qcReviews,
                    'customer_complaints' => $customerComplaints,
                    'system_health' => $systemHealth,
                    'last_updated' => date('Y-m-d H:i:s')
                ]
            ];
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Database error: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Get inspector performance metrics
     */
    private function getInspectorPerformance($periodCondition) {
        $stmt = $this->db->prepare("
            SELECT 
                AVG(ip.score) as avg_score,
                COUNT(ip.id) as total_inspections,
                AVG(ip.efficiency_score) as avg_efficiency,
                COUNT(DISTINCT ip.inspector_id) as active_inspectors,
                SUM(CASE WHEN ip.score >= 90 THEN 1 ELSE 0 END) as excellent_inspections,
                SUM(CASE WHEN ip.score >= 80 AND ip.score < 90 THEN 1 ELSE 0 END) as good_inspections,
                SUM(CASE WHEN ip.score < 80 THEN 1 ELSE 0 END) as needs_improvement
            FROM inspector_performance ip
            WHERE $periodCondition
        ");
        
        $stmt->execute();
        $result = $stmt->fetch();
        
        if ($result) {
            return [
                'avg_score' => round($result['avg_score'], 1),
                'total_inspections' => intval($result['total_inspections']),
                'avg_efficiency' => round($result['avg_efficiency'], 1),
                'active_inspectors' => intval($result['active_inspectors']),
                'excellent_inspections' => intval($result['excellent_inspections']),
                'good_inspections' => intval($result['good_inspections']),
                'needs_improvement' => intval($result['needs_improvement']),
                'performance_rating' => $this->calculatePerformanceRating($result['avg_score'])
            ];
        }
        
        return $this->getDefaultPerformanceMetrics();
    }
    
    /**
     * Get QC review metrics
     */
    private function getQCReviewMetrics($periodCondition) {
        $stmt = $this->db->prepare("
            SELECT 
                COUNT(qcr.id) as total_reviews,
                SUM(CASE WHEN qcr.status = 'approved' THEN 1 ELSE 0 END) as approved,
                SUM(CASE WHEN qcr.status = 'rejected' THEN 1 ELSE 0 END) as rejected,
                SUM(CASE WHEN qcr.status = 'needs_review' THEN 1 ELSE 0 END) as needs_review,
                AVG(qcr.quality_score) as avg_quality_score,
                AVG(qcr.accuracy_score) as avg_accuracy_score
            FROM qc_reviews qcr
            WHERE $periodCondition
        ");
        
        $stmt->execute();
        $result = $stmt->fetch();
        
        if ($result) {
            $totalReviews = intval($result['total_reviews']);
            $approvalRate = $totalReviews > 0 ? round(($result['approved'] / $totalReviews) * 100, 1) : 0;
            
            return [
                'total_reviews' => $totalReviews,
                'approved' => intval($result['approved']),
                'rejected' => intval($result['rejected']),
                'needs_review' => intval($result['needs_review']),
                'approval_rate' => $approvalRate,
                'avg_quality_score' => round($result['avg_quality_score'], 1),
                'avg_accuracy_score' => round($result['avg_accuracy_score'], 1)
            ];
        }
        
        return $this->getDefaultQCMetrics();
    }
    
    /**
     * Get customer complaints metrics
     */
    private function getCustomerComplaintsMetrics($periodCondition) {
        $stmt = $this->db->prepare("
            SELECT 
                COUNT(cc.id) as total_complaints,
                SUM(CASE WHEN cc.status = 'resolved' THEN 1 ELSE 0 END) as resolved,
                SUM(CASE WHEN cc.status = 'pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN cc.status = 'investigating' THEN 1 ELSE 0 END) as investigating,
                AVG(cc.severity_score) as avg_severity,
                AVG(DATEDIFF(cc.resolved_date, cc.created_date)) as avg_resolution_days
            FROM customer_complaints cc
            WHERE $periodCondition
        ");
        
        $stmt->execute();
        $result = $stmt->fetch();
        
        if ($result) {
            $totalComplaints = intval($result['total_complaints']);
            $resolutionRate = $totalComplaints > 0 ? round(($result['resolved'] / $totalComplaints) * 100, 1) : 0;
            
            return [
                'total_complaints' => $totalComplaints,
                'resolved' => intval($result['resolved']),
                'pending' => intval($result['pending']),
                'investigating' => intval($result['investigating']),
                'resolution_rate' => $resolutionRate,
                'avg_severity' => round($result['avg_severity'], 1),
                'avg_resolution_days' => round($result['avg_resolution_days'], 1)
            ];
        }
        
        return $this->getDefaultComplaintsMetrics();
    }
    
    /**
     * Get system health metrics
     */
    private function getSystemHealthMetrics() {
        // Get system logs for uptime and error tracking
        $stmt = $this->db->prepare("
            SELECT 
                COUNT(*) as total_requests,
                SUM(CASE WHEN status_code >= 400 THEN 1 ELSE 0 END) as error_requests,
                AVG(response_time) as avg_response_time,
                MAX(created_at) as last_request
            FROM system_logs
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
        ");
        
        $stmt->execute();
        $logsResult = $stmt->fetch();
        
        // Get database performance
        $dbPerformance = $this->getDatabasePerformance();
        
        // Calculate uptime (simplified - in production, use proper monitoring)
        $uptime = 99.9; // Placeholder
        
        if ($logsResult) {
            $totalRequests = intval($logsResult['total_requests']);
            $errorRate = $totalRequests > 0 ? round(($logsResult['error_requests'] / $totalRequests) * 100, 2) : 0;
            
            return [
                'uptime' => $uptime,
                'total_requests' => $totalRequests,
                'error_rate' => $errorRate,
                'avg_response_time' => round($logsResult['avg_response_time'], 2),
                'database_performance' => $dbPerformance,
                'last_request' => $logsResult['last_request'],
                'health_score' => $this->calculateHealthScore($uptime, $errorRate, $logsResult['avg_response_time'])
            ];
        }
        
        return $this->getDefaultSystemHealthMetrics();
    }
    
    /**
     * Get database performance metrics
     */
    private function getDatabasePerformance() {
        try {
            // Test query performance
            $start = microtime(true);
            $stmt = $this->db->prepare("SELECT 1");
            $stmt->execute();
            $queryTime = (microtime(true) - $start) * 1000;
            
            // Get connection info
            $connections = $this->db->getConnectionCount();
            
            return [
                'query_time' => round($queryTime, 2),
                'active_connections' => $connections,
                'status' => 'healthy'
            ];
        } catch (Exception $e) {
            return [
                'query_time' => 0,
                'active_connections' => 0,
                'status' => 'error',
                'error' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Get period condition for SQL queries
     */
    private function getPeriodCondition($period) {
        switch ($period) {
            case 'today':
                return "DATE(created_at) = CURDATE()";
            case 'week':
                return "created_at >= DATE_SUB(NOW(), INTERVAL 1 WEEK)";
            case 'month':
                return "created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
            default:
                return "DATE(created_at) = CURDATE()";
        }
    }
    
    /**
     * Calculate overall quality score
     */
    private function calculateOverallQualityScore($metrics) {
        $weights = [
            'inspector_performance' => 0.3,
            'qc_reviews' => 0.3,
            'customer_complaints' => 0.2,
            'system_health' => 0.2
        ];
        
        $scores = [
            $metrics[0]['avg_score'] ?? 0,
            $metrics[1]['approval_rate'] ?? 0,
            ($metrics[2]['resolution_rate'] ?? 100) - ($metrics[2]['total_complaints'] ?? 0), // Lower complaints = higher score
            $metrics[3]['health_score'] ?? 0
        ];
        
        $weightedScore = 0;
        foreach ($scores as $index => $score) {
            $metricType = array_keys($weights)[$index];
            $weightedScore += $score * $weights[$metricType];
        }
        
        return round($weightedScore, 1);
    }
    
    /**
     * Calculate performance rating
     */
    private function calculatePerformanceRating($score) {
        if ($score >= 95) return 'excellent';
        if ($score >= 85) return 'good';
        if ($score >= 75) return 'average';
        return 'needs_improvement';
    }
    
    /**
     * Calculate health score
     */
    private function calculateHealthScore($uptime, $errorRate, $responseTime) {
        $uptimeScore = $uptime;
        $errorScore = max(0, 100 - ($errorRate * 10)); // 1% error = 10 points deduction
        $responseScore = max(0, 100 - ($responseTime / 10)); // 1000ms = 10 points deduction
        
        return round(($uptimeScore + $errorScore + $responseScore) / 3, 1);
    }
    
    /**
     * Default metrics for empty results
     */
    private function getDefaultPerformanceMetrics() {
        return [
            'avg_score' => 0,
            'total_inspections' => 0,
            'avg_efficiency' => 0,
            'active_inspectors' => 0,
            'excellent_inspections' => 0,
            'good_inspections' => 0,
            'needs_improvement' => 0,
            'performance_rating' => 'no_data'
        ];
    }
    
    private function getDefaultQCMetrics() {
        return [
            'total_reviews' => 0,
            'approved' => 0,
            'rejected' => 0,
            'needs_review' => 0,
            'approval_rate' => 0,
            'avg_quality_score' => 0,
            'avg_accuracy_score' => 0
        ];
    }
    
    private function getDefaultComplaintsMetrics() {
        return [
            'total_complaints' => 0,
            'resolved' => 0,
            'pending' => 0,
            'investigating' => 0,
            'resolution_rate' => 0,
            'avg_severity' => 0,
            'avg_resolution_days' => 0
        ];
    }
    
    private function getDefaultSystemHealthMetrics() {
        return [
            'uptime' => 0,
            'total_requests' => 0,
            'error_rate' => 0,
            'avg_response_time' => 0,
            'database_performance' => [
                'query_time' => 0,
                'active_connections' => 0,
                'status' => 'unknown'
            ],
            'last_request' => null,
            'health_score' => 0
        ];
    }
}

// Handle API requests
try {
    $qualityMetrics = new QualityMetrics();
    
    $endpoint = $_GET['endpoint'] ?? 'metrics';
    $period = $_GET['period'] ?? 'today';
    
    switch ($endpoint) {
        case 'metrics':
            echo json_encode($qualityMetrics->getQualityMetrics($period));
            break;
            
        case 'performance':
            echo json_encode([
                'success' => true,
                'data' => $qualityMetrics->getInspectorPerformance($qualityMetrics->getPeriodCondition($period))
            ]);
            break;
            
        case 'qc':
            echo json_encode([
                'success' => true,
                'data' => $qualityMetrics->getQCReviewMetrics($qualityMetrics->getPeriodCondition($period))
            ]);
            break;
            
        case 'complaints':
            echo json_encode([
                'success' => true,
                'data' => $qualityMetrics->getCustomerComplaintsMetrics($qualityMetrics->getPeriodCondition($period))
            ]);
            break;
            
        case 'health':
            echo json_encode([
                'success' => true,
                'data' => $qualityMetrics->getSystemHealthMetrics()
            ]);
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'message' => 'Invalid endpoint'
            ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Server error: ' . $e->getMessage()
    ]);
}
?>
