<?php
/**
 * AUTO TESTER - Quality Control API
 * Handles all quality control operations including reviews, performance tracking, and complaints
 */

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

class QualityControlSystem {
    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 quality control action
     */
    private function hasPermission($permission) {
        if (!$this->currentUser) {
            return false;
        }
        
        $permissions = json_decode($this->currentUser['permissions'] ?? '{}', true);
        $qcPermissions = $permissions['quality_control'] ?? [];
        
        // Check role-based permissions
        $role = $this->currentUser['role'];
        
        switch ($permission) {
            case 'view_dashboard':
                return in_array($role, ['supervisor', 'admin']);
            case 'review_inspections':
                return in_array($role, ['supervisor', 'admin']);
            case 'manage_complaints':
                return in_array($role, ['supervisor', 'admin']);
            case 'view_reports':
                return in_array($role, ['supervisor', 'admin']);
            case 'peer_review':
                return $role === 'inspector';
            case 'view_own_performance':
                return $role === 'inspector';
            default:
                return false;
        }
    }
    
    /**
     * Get quality control statistics
     */
    public function getQualityStats() {
        if (!$this->hasPermission('view_dashboard')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Get dashboard stats from view
            $stmt = $this->db->prepare("SELECT * FROM quality_control_dashboard LIMIT 1");
            $stmt->execute();
            $dashboardStats = $stmt->fetch();
            
            // Get recent performance trends
            $stmt = $this->db->prepare("
                SELECT 
                    DATE_FORMAT(period_end, '%Y-%m') as month,
                    AVG(avg_accuracy) as avg_accuracy,
                    AVG(avg_customer_rating) as avg_rating,
                    AVG(error_rate) as avg_error_rate,
                    COUNT(*) as inspector_count
                FROM inspector_performance 
                WHERE period_type = 'monthly'
                AND period_end >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH)
                GROUP BY DATE_FORMAT(period_end, '%Y-%m')
                ORDER BY month DESC
            ");
            $stmt->execute();
            $trends = $stmt->fetchAll();
            
            // Get top performers
            $stmt = $this->db->prepare("
                SELECT 
                    inspector_id,
                    full_name,
                    performance_grade,
                    performance_score,
                    avg_accuracy,
                    total_inspections,
                    rank_in_period
                FROM inspector_performance_summary 
                WHERE period_end >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
                ORDER BY performance_score DESC
                LIMIT 10
            ");
            $stmt->execute();
            $topPerformers = $stmt->fetchAll();
            
            return [
                'success' => true,
                'data' => [
                    'dashboard_stats' => $dashboardStats,
                    'performance_trends' => $trends,
                    'top_performers' => $topPerformers
                ]
            ];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get pending reviews for current user
     */
    public function getPendingReviews() {
        if (!$this->hasPermission('review_inspections')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $stmt = $this->db->prepare("
                SELECT 
                    ir.id,
                    ir.inspection_id,
                    ir.review_type,
                    ir.priority,
                    ir.assigned_at,
                    ir.review_type,
                    i.customer_name,
                    i.car_make,
                    i.car_model,
                    i.inspection_date,
                    insp.full_name as inspector_name,
                    i.inspector_id
                FROM inspection_reviews ir
                JOIN inspection_requests i ON ir.inspection_id = i.id
                JOIN users insp ON i.inspector_id = insp.id
                WHERE ir.reviewer_id = ?
                AND ir.status = 'pending'
                ORDER BY ir.priority DESC, ir.assigned_at ASC
            ");
            $stmt->execute([$this->currentUser['id']]);
            $reviews = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $reviews];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Submit inspection review
     */
    public function submitReview($data) {
        if (!$this->hasPermission('review_inspections')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Validate required fields
            $required = ['review_id', 'accuracy_score', 'completeness_score', 'professionalism_score'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Calculate overall score
            $overallScore = ($data['accuracy_score'] + $data['completeness_score'] + $data['professionalism_score']) / 3;
            
            // Update review
            $stmt = $this->db->prepare("
                UPDATE inspection_reviews 
                SET 
                    accuracy_score = ?,
                    completeness_score = ?,
                    professionalism_score = ?,
                    documentation_score = ?,
                    overall_score = ?,
                    notes = ?,
                    corrections = ?,
                    strengths = ?,
                    weaknesses = ?,
                    status = 'approved',
                    started_at = COALESCE(started_at, NOW()),
                    completed_at = NOW(),
                    review_duration = TIMESTAMPDIFF(MINUTE, COALESCE(started_at, assigned_at), NOW()),
                    reviewer_confidence = ?,
                    would_recommend = ?,
                    additional_training_needed = ?
                WHERE id = ? AND reviewer_id = ?
            ");
            
            $result = $stmt->execute([
                $data['accuracy_score'],
                $data['completeness_score'],
                $data['professionalism_score'],
                $data['documentation_score'] ?? 0,
                $overallScore,
                $data['notes'] ?? '',
                json_encode($data['corrections'] ?? []),
                $data['strengths'] ?? '',
                $data['weaknesses'] ?? '',
                $data['reviewer_confidence'] ?? 'medium',
                $data['would_recommend'] ?? true,
                $data['additional_training_needed'] ?? false,
                $data['review_id'],
                $this->currentUser['id']
            ]);
            
            if (!$result) {
                return ['success' => false, 'message' => 'Failed to update review'];
            }
            
            // Get inspection details for performance update
            $stmt = $this->db->prepare("
                SELECT inspector_id 
                FROM inspection_requests 
                WHERE id = (SELECT inspection_id FROM inspection_reviews WHERE id = ?)
            ");
            $stmt->execute([$data['review_id']]);
            $inspection = $stmt->fetch();
            
            // Update inspector performance
            if ($inspection) {
                $this->updateInspectorPerformance($inspection['inspector_id']);
            }
            
            // Create quality alert if needed
            if ($overallScore < 70) {
                $this->createQualityAlert('performance_drop', 'warning', 
                    'Low inspection quality detected', 
                    "Review score: {$overallScore}%", 
                    $inspection['inspector_id'], 
                    $data['review_id']);
            }
            
            return ['success' => true, 'message' => 'Review submitted successfully'];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update inspector performance metrics
     */
    private function updateInspectorPerformance($inspectorId) {
        try {
            // Get current month period
            $periodStart = date('Y-m-01');
            $periodEnd = date('Y-m-t');
            
            // Calculate performance metrics
            $stmt = $this->db->prepare("
                SELECT 
                    COUNT(*) as total_inspections,
                    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_inspections,
                    AVG(CASE WHEN status = 'completed' THEN completion_time ELSE NULL END) as avg_completion_time,
                    AVG(CASE WHEN status = 'completed' THEN customer_rating ELSE NULL END) as avg_customer_rating
                FROM inspection_requests 
                WHERE inspector_id = ?
                AND DATE(created_at) BETWEEN ? AND ?
            ");
            $stmt->execute([$inspectorId, $periodStart, $periodEnd]);
            $inspectionStats = $stmt->fetch();
            
            // Get review scores
            $stmt = $this->db->prepare("
                SELECT 
                    AVG(accuracy_score) as avg_accuracy,
                    AVG(completeness_score) as avg_completeness,
                    AVG(professionalism_score) as avg_professionalism,
                    AVG(documentation_score) as avg_documentation,
                    COUNT(*) as review_count
                FROM inspection_reviews ir
                JOIN inspection_requests i ON ir.inspection_id = i.id
                WHERE i.inspector_id = ?
                AND ir.status = 'approved'
                AND DATE(ir.completed_at) BETWEEN ? AND ?
            ");
            $stmt->execute([$inspectorId, $periodStart, $periodEnd]);
            $reviewStats = $stmt->fetch();
            
            // Get complaint rate
            $stmt = $this->db->prepare("
                SELECT 
                    COUNT(*) as complaint_count
                FROM customer_complaints cc
                JOIN inspection_requests i ON cc.inspection_id = i.id
                WHERE i.inspector_id = ?
                AND DATE(cc.created_at) BETWEEN ? AND ?
            ");
            $stmt->execute([$inspectorId, $periodStart, $periodEnd]);
            $complaintStats = $stmt->fetch();
            
            // Calculate error rate (mismatches in reviews)
            $stmt = $this->db->prepare("
                SELECT 
                    COUNT(*) as total_reviews,
                    SUM(CASE WHEN is_match = 0 THEN 1 ELSE 0 END) as mismatches
                FROM inspection_reviews ir
                JOIN inspection_requests i ON ir.inspection_id = i.id
                WHERE i.inspector_id = ?
                AND ir.status = 'approved'
                AND DATE(ir.completed_at) BETWEEN ? AND ?
            ");
            $stmt->execute([$inspectorId, $periodStart, $periodEnd]);
            $errorStats = $stmt->fetch();
            
            // Calculate rates
            $totalInspections = $inspectionStats['total_inspections'] ?: 1;
            $complaintRate = ($complaintStats['complaint_count'] / $totalInspections) * 100;
            $errorRate = $errorStats['total_reviews'] > 0 ? 
                ($errorStats['mismatches'] / $errorStats['total_reviews']) * 100 : 0;
            
            // Calculate overall performance score
            $accuracyWeight = 40;
            $completenessWeight = 30;
            $professionalismWeight = 30;
            
            $performanceScore = (
                ($reviewStats['avg_accuracy'] * $accuracyWeight) +
                ($reviewStats['avg_completeness'] * $completenessWeight) +
                ($reviewStats['avg_professionalism'] * $professionalismWeight)
            ) / 100;
            
            // Determine grade
            $grade = $this->getPerformanceGrade($performanceScore);
            $needsTraining = $performanceScore < 70;
            
            // Update or insert performance record
            $stmt = $this->db->prepare("
                INSERT INTO inspector_performance 
                (inspector_id, period_start, period_end, period_type,
                 total_inspections, completed_inspections, avg_completion_time,
                 avg_accuracy, avg_completeness, avg_professionalism, avg_documentation,
                 avg_customer_rating, error_rate, complaint_rate,
                 performance_score, performance_grade, needs_training,
                 calculated_at)
                VALUES (?, ?, ?, 'monthly', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                ON DUPLICATE KEY UPDATE
                total_inspections = VALUES(total_inspections),
                completed_inspections = VALUES(completed_inspections),
                avg_completion_time = VALUES(avg_completion_time),
                avg_accuracy = VALUES(avg_accuracy),
                avg_completeness = VALUES(avg_completeness),
                avg_professionalism = VALUES(avg_professionalism),
                avg_documentation = VALUES(avg_documentation),
                avg_customer_rating = VALUES(avg_customer_rating),
                error_rate = VALUES(error_rate),
                complaint_rate = VALUES(complaint_rate),
                performance_score = VALUES(performance_score),
                performance_grade = VALUES(performance_grade),
                needs_training = VALUES(needs_training),
                calculated_at = VALUES(calculated_at)
            ");
            
            $result = $stmt->execute([
                $inspectorId, $periodStart, $periodEnd,
                $inspectionStats['total_inspections'],
                $inspectionStats['completed_inspections'],
                $inspectionStats['avg_completion_time'],
                $reviewStats['avg_accuracy'],
                $reviewStats['avg_completeness'],
                $reviewStats['avg_professionalism'],
                $reviewStats['avg_documentation'],
                $inspectionStats['avg_customer_rating'],
                $errorRate,
                $complaintRate,
                $performanceScore,
                $grade,
                $needsTraining
            ]);
            
            return $result;
            
        } catch (Exception $e) {
            error_log("Performance update error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get performance grade based on score
     */
    private function getPerformanceGrade($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';
    }
    
    /**
     * Assign random reviews
     */
    public function assignRandomReviews() {
        if (!$this->hasPermission('review_inspections')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Get review percentage setting
            $stmt = $this->db->prepare("
                SELECT JSON_EXTRACT(setting_value, '$') as percentage 
                FROM quality_control_settings 
                WHERE setting_key = 'random_review_percentage'
            ");
            $stmt->execute();
            $setting = $stmt->fetch();
            $reviewPercentage = json_decode($setting['percentage']) ?: 10;
            
            // Find inspections for random review
            $stmt = $this->db->prepare("
                SELECT i.id, i.inspector_id
                FROM inspection_requests i
                LEFT JOIN inspection_reviews ir ON i.id = ir.inspection_id
                WHERE i.status = 'completed'
                AND i.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
                AND ir.id IS NULL
                AND (i.inspector_id != ? OR ? IS NULL)
                ORDER BY RAND()
                LIMIT 50
            ");
            $stmt->execute([$this->currentUser['id'], $this->currentUser['id']]);
            $inspections = $stmt->fetchAll();
            
            $assignedCount = 0;
            
            foreach ($inspections as $inspection) {
                // Randomly select based on percentage
                if (rand(1, 100) <= $reviewPercentage) {
                    // Assign to reviewer
                    $stmt = $this->db->prepare("
                        INSERT INTO inspection_reviews 
                        (inspection_id, reviewer_id, reviewer_type, review_type, status, priority)
                        VALUES (?, ?, 'supervisor', 'random', 'pending', 
                        CASE WHEN RAND() > 0.8 THEN 'high' ELSE 'medium' END)
                    ");
                    $result = $stmt->execute([$inspection['id'], $this->currentUser['id']]);
                    
                    if ($result) {
                        $assignedCount++;
                    }
                }
            }
            
            return [
                'success' => true, 
                'message' => "Assigned {$assignedCount} random reviews for review"
            ];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get inspector ranking
     */
    public function getInspectorRanking($period = 'current_month') {
        if (!$this->hasPermission('view_dashboard')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $dateCondition = '';
            switch ($period) {
                case 'current_month':
                    $dateCondition = "AND period_end >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-01')";
                    break;
                case 'last_month':
                    $dateCondition = "AND period_end >= DATE_SUB(DATE_FORMAT(CURRENT_DATE, '%Y-%m-01'), INTERVAL 1 MONTH)
                                   AND period_end < DATE_FORMAT(CURRENT_DATE, '%Y-%m-01')";
                    break;
                case 'current_quarter':
                    $dateCondition = "AND period_end >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-01')
                                   AND MONTH(period_end) BETWEEN 1 AND 3";
                    break;
                default:
                    $dateCondition = "AND period_end >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-01')";
            }
            
            $stmt = $this->db->prepare("
                SELECT 
                    inspector_id,
                    full_name,
                    performance_grade,
                    performance_score,
                    avg_accuracy,
                    avg_customer_rating,
                    total_inspections,
                    error_rate,
                    complaint_rate,
                    rank_in_period
                FROM inspector_performance_summary 
                WHERE 1=1 $dateCondition
                ORDER BY performance_score DESC
            ");
            $stmt->execute();
            $ranking = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $ranking];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get customer complaints
     */
    public function getComplaints($status = 'all') {
        if (!$this->hasPermission('manage_complaints')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $statusCondition = '';
            if ($status !== 'all') {
                $statusCondition = "AND cc.status = ?";
            }
            
            $stmt = $this->db->prepare("
                SELECT 
                    cc.*,
                    i.customer_name,
                    i.car_make,
                    i.car_model,
                    i.inspection_date,
                    insp.full_name as inspector_name,
                    inv.full_name as investigator_name
                FROM customer_complaints cc
                JOIN inspection_requests i ON cc.inspection_id = i.id
                JOIN users insp ON i.inspector_id = insp.id
                LEFT JOIN users inv ON cc.investigator_id = inv.id
                WHERE 1=1 $statusCondition
                ORDER BY cc.created_at DESC
            ");
            
            if ($status !== 'all') {
                $stmt->execute([$status]);
            } else {
                $stmt->execute();
            }
            
            $complaints = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $complaints];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Create quality alert
     */
    private function createQualityAlert($alertType, $severity, $title, $message, $targetId = null, $inspectionId = null) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO quality_alerts 
                (alert_type, severity, title, message, target_type, target_id, inspection_id, status)
                VALUES (?, ?, ?, ?, 'inspector', ?, ?, 'active')
            ");
            return $stmt->execute([$alertType, $severity, $title, $message, $targetId, $inspectionId]);
        } catch (Exception $e) {
            error_log("Alert creation error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get peer reviews for inspector
     */
    public function getPeerReviews($inspectorId = null) {
        if (!$this->hasPermission('peer_review') && !$this->hasPermission('view_dashboard')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // If no inspector ID provided, get current user's peer reviews
            if (!$inspectorId) {
                $inspectorId = $this->currentUser['id'];
            }
            
            $stmt = $this->db->prepare("
                SELECT 
                    pr.*,
                    reviewer.full_name as reviewer_name,
                    i.customer_name,
                    i.car_make,
                    i.car_model,
                    i.created_at as inspection_date
                FROM peer_reviews pr
                JOIN users reviewer ON pr.reviewer_inspector_id = reviewer.id
                JOIN inspection_requests i ON pr.inspection_id = i.id
                WHERE pr.reviewee_inspector_id = ?
                ORDER BY pr.created_at DESC
            ");
            $stmt->execute([$inspectorId]);
            $reviews = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $reviews];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Submit peer review
     */
    public function submitPeerReview($data) {
        if (!$this->hasPermission('peer_review')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Validate required fields
            $required = ['inspection_id', 'reviewee_inspector_id', 'overall_score'];
            foreach ($required as $field) {
                if (!isset($data[$field])) {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Check if review already exists
            $stmt = $this->db->prepare("
                SELECT id FROM peer_reviews 
                WHERE inspection_id = ? AND reviewer_inspector_id = ? AND reviewee_inspector_id = ?
            ");
            $stmt->execute([$data['inspection_id'], $this->currentUser['id'], $data['reviewee_inspector_id']]);
            
            if ($stmt->fetch()) {
                return ['success' => false, 'message' => 'Review already submitted for this inspection'];
            }
            
            // Insert peer review
            $stmt = $this->db->prepare("
                INSERT INTO peer_reviews 
                (inspection_id, reviewer_inspector_id, reviewee_inspector_id,
                 technical_accuracy_score, thoroughness_score, documentation_score,
                 professionalism_score, communication_score, overall_score,
                 feedback, strengths, areas_for_improvement, specific_examples,
                 recommendations, is_anonymous, confidence_level, status, submitted_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'completed', NOW())
            ");
            
            $result = $stmt->execute([
                $data['inspection_id'],
                $this->currentUser['id'],
                $data['reviewee_inspector_id'],
                $data['technical_accuracy_score'] ?? null,
                $data['thoroughness_score'] ?? null,
                $data['documentation_score'] ?? null,
                $data['professionalism_score'] ?? null,
                $data['communication_score'] ?? null,
                $data['overall_score'],
                $data['feedback'] ?? '',
                $data['strengths'] ?? '',
                $data['areas_for_improvement'] ?? '',
                json_encode($data['specific_examples'] ?? []),
                $data['recommendations'] ?? '',
                $data['is_anonymous'] ?? true,
                $data['confidence_level'] ?? 'medium'
            ]);
            
            if ($result) {
                return ['success' => true, 'message' => 'Peer review submitted successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to submit peer review'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get quality reports
     */
    public function getQualityReports($reportType = 'monthly') {
        if (!$this->hasPermission('view_reports')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM quality_reports 
                WHERE report_type = ? 
                ORDER BY created_at DESC 
                LIMIT 12
            ");
            $stmt->execute([$reportType]);
            $reports = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $reports];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Generate quality report
     */
    public function generateQualityReport($reportType, $periodStart, $periodEnd) {
        if (!$this->hasPermission('view_reports')) {
            return ['success' => false, 'message' => 'Unauthorized access'];
        }
        
        try {
            // Generate report data
            $reportData = $this->generateReportData($reportType, $periodStart, $periodEnd);
            
            // Save report
            $stmt = $this->db->prepare("
                INSERT INTO quality_reports 
                (report_type, report_period_start, report_period_end, report_title, 
                 report_description, report_data, summary_statistics, trend_analysis,
                 recommendations, overall_quality_score, total_inspections_reviewed,
                 accuracy_rate, complaint_rate, average_response_time,
                 generated_by, generation_method, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'manual', 'generating')
            ");
            
            $result = $stmt->execute([
                $reportType,
                $periodStart,
                $periodEnd,
                ucfirst($reportType) . ' Quality Report ' . $periodStart,
                'Quality control performance report for the specified period',
                json_encode($reportData),
                json_encode($reportData['summary'] ?? []),
                json_encode($reportData['trends'] ?? []),
                json_encode($reportData['recommendations'] ?? []),
                $reportData['overall_quality_score'] ?? 0,
                $reportData['total_inspections_reviewed'] ?? 0,
                $reportData['accuracy_rate'] ?? 0,
                $reportData['complaint_rate'] ?? 0,
                $reportData['average_response_time'] ?? 0,
                $this->currentUser['id']
            ]);
            
            if ($result) {
                $reportId = $this->db->lastInsertId();
                
                // Update status to completed
                $stmt = $this->db->prepare("
                    UPDATE quality_reports 
                    SET status = 'completed', completed_at = NOW() 
                    WHERE id = ?
                ");
                $stmt->execute([$reportId]);
                
                return [
                    'success' => true, 
                    'message' => 'Quality report generated successfully',
                    'report_id' => $reportId
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to generate report'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Generate report data
     */
    private function generateReportData($reportType, $periodStart, $periodEnd) {
        // This would contain complex logic to generate comprehensive report data
        // For now, return placeholder data
        return [
            'overall_quality_score' => 92.5,
            'total_inspections_reviewed' => 1250,
            'accuracy_rate' => 96.8,
            'complaint_rate' => 2.3,
            'average_response_time' => 18,
            'summary' => [
                'top_performers' => [],
                'areas_for_improvement' => [],
                'key_achievements' => []
            ],
            'trends' => [
                'quality_trend' => 'improving',
                'customer_satisfaction_trend' => 'stable',
                'error_rate_trend' => 'decreasing'
            ],
            'recommendations' => [
                'Continue training programs',
                'Implement additional quality checks',
                'Enhance customer communication'
            ]
        ];
    }
}

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

$qualityControl = new QualityControlSystem();
$endpoint = $_GET['endpoint'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($endpoint) {
        case 'stats':
            if ($method === 'GET') {
                echo json_encode($qualityControl->getQualityStats());
            }
            break;
            
        case 'pending-reviews':
            if ($method === 'GET') {
                echo json_encode($qualityControl->getPendingReviews());
            }
            break;
            
        case 'review':
            if ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($qualityControl->submitReview($data));
            }
            break;
            
        case 'assign-random-reviews':
            if ($method === 'POST') {
                echo json_encode($qualityControl->assignRandomReviews());
            }
            break;
            
        case 'inspector-ranking':
            if ($method === 'GET') {
                $period = $_GET['period'] ?? 'current_month';
                echo json_encode($qualityControl->getInspectorRanking($period));
            }
            break;
            
        case 'complaints':
            if ($method === 'GET') {
                $status = $_GET['status'] ?? 'all';
                echo json_encode($qualityControl->getComplaints($status));
            }
            break;
            
        case 'peer-reviews':
            if ($method === 'GET') {
                $inspectorId = $_GET['inspector_id'] ?? null;
                echo json_encode($qualityControl->getPeerReviews($inspectorId));
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($qualityControl->submitPeerReview($data));
            }
            break;
            
        case 'reports':
            if ($method === 'GET') {
                $reportType = $_GET['type'] ?? 'monthly';
                echo json_encode($qualityControl->getQualityReports($reportType));
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($qualityControl->generateQualityReport(
                    $data['report_type'],
                    $data['period_start'],
                    $data['period_end']
                ));
            }
            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()]);
}
?>
