<?php
class HRAnalytics {
    private $db;
    private $company_id;
    
    public function __construct($database, $company_id) {
        $this->db = $database;
        $this->company_id = $company_id;
    }
    
    // Track HR metrics
    public function trackMetric($metric_type, $job_id = null, $candidate_id = null, $value = 1) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO hr_analytics (company_id, metric_type, metric_value, job_id, candidate_id) 
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([$this->company_id, $metric_type, $value, $job_id, $candidate_id]);
            return true;
        } catch (PDOException $e) {
            error_log("HR Analytics tracking error: " . $e->getMessage());
            return false;
        }
    }
    
    // Get recruitment metrics for dashboard
    public function getRecruitmentMetrics($period = '30 days') {
        try {
            $stmt = $this->db->prepare("
                SELECT 
                    metric_type,
                    COUNT(*) as count,
                    SUM(metric_value) as total_value
                FROM hr_analytics 
                WHERE company_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
                GROUP BY metric_type
            ");
            
            $days = $this->parsePeriodToDays($period);
            $stmt->execute([$this->company_id, $days]);
            
            $metrics = [];
            while ($row = $stmt->fetch()) {
                $metrics[$row['metric_type']] = [
                    'count' => $row['count'],
                    'total' => $row['total_value']
                ];
            }
            
            return $metrics;
        } catch (PDOException $e) {
            error_log("Error getting recruitment metrics: " . $e->getMessage());
            return [];
        }
    }
    
    // Get hiring funnel data
    public function getHiringFunnel($period = '30 days') {
        try {
            $days = $this->parsePeriodToDays($period);
            
            $stmt = $this->db->prepare("
                SELECT 
                    j.title as job_title,
                    COUNT(CASE WHEN ha.metric_type = 'application_received' THEN 1 END) as applications,
                    COUNT(CASE WHEN ha.metric_type = 'interview_scheduled' THEN 1 END) as interviews,
                    COUNT(CASE WHEN ha.metric_type = 'candidate_hired' THEN 1 END) as hired,
                    COUNT(CASE WHEN ha.metric_type = 'candidate_rejected' THEN 1 END) as rejected
                FROM jobs j
                LEFT JOIN hr_analytics ha ON j.id = ha.job_id 
                    AND ha.company_id = ? 
                    AND ha.created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
                WHERE j.company_id = ?
                GROUP BY j.id, j.title
                HAVING applications > 0
                ORDER BY applications DESC
                LIMIT 10
            ");
            
            $stmt->execute([$this->company_id, $days, $this->company_id]);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            error_log("Error getting hiring funnel: " . $e->getMessage());
            return [];
        }
    }
    
    // Get time to hire statistics
    public function getTimeToHireStats($period = '90 days') {
        try {
            $days = $this->parsePeriodToDays($period);
            
            $stmt = $this->db->prepare("
                SELECT 
                    AVG(days_to_hire) as avg_time_to_hire,
                    MIN(days_to_hire) as min_time_to_hire,
                    MAX(days_to_hire) as max_time_to_hire,
                    COUNT(*) as total_hires
                FROM time_to_hire 
                WHERE company_id = ? AND hire_date >= DATE_SUB(NOW(), INTERVAL ? DAY)
            ");
            
            $stmt->execute([$this->company_id, $days]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            error_log("Error getting time to hire stats: " . $e->getMessage());
            return ['avg_time_to_hire' => 0, 'min_time_to_hire' => 0, 'max_time_to_hire' => 0, 'total_hires' => 0];
        }
    }
    
    // Get source effectiveness
    public function getSourceEffectiveness($period = '30 days') {
        try {
            $days = $this->parsePeriodToDays($period);
            
            $stmt = $this->db->prepare("
                SELECT 
                    source_name,
                    applications_count,
                    hires_count,
                    CASE 
                        WHEN applications_count > 0 THEN ROUND((hires_count / applications_count) * 100, 2)
                        ELSE 0 
                    END as conversion_rate
                FROM source_effectiveness 
                WHERE company_id = ? AND period_start >= DATE_SUB(NOW(), INTERVAL ? DAY)
                ORDER BY conversion_rate DESC, applications_count DESC
            ");
            
            $stmt->execute([$this->company_id, $days]);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            error_log("Error getting source effectiveness: " . $e->getMessage());
            return [];
        }
    }
    
    // Get monthly trends
    public function getMonthlyTrends($months = 6) {
        try {
            $stmt = $this->db->prepare("
                SELECT 
                    DATE_FORMAT(created_at, '%Y-%m') as month,
                    metric_type,
                    COUNT(*) as count
                FROM hr_analytics 
                WHERE company_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL ? MONTH)
                GROUP BY DATE_FORMAT(created_at, '%Y-%m'), metric_type
                ORDER BY month ASC
            ");
            
            $stmt->execute([$this->company_id, $months]);
            
            $trends = [];
            while ($row = $stmt->fetch()) {
                $trends[$row['month']][$row['metric_type']] = $row['count'];
            }
            
            return $trends;
        } catch (PDOException $e) {
            error_log("Error getting monthly trends: " . $e->getMessage());
            return [];
        }
    }
    
    // Get active jobs statistics
    public function getJobsStatistics() {
        try {
            $stmt = $this->db->prepare("
                SELECT 
                    COUNT(CASE WHEN status = 'active' THEN 1 END) as active_jobs,
                    COUNT(CASE WHEN status = 'closed' THEN 1 END) as closed_jobs,
                    COUNT(CASE WHEN status = 'draft' THEN 1 END) as draft_jobs,
                    COUNT(*) as total_jobs,
                    AVG(DATEDIFF(NOW(), created_at)) as avg_job_age_days
                FROM jobs 
                WHERE company_id = ?
            ");
            
            $stmt->execute([$this->company_id]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            error_log("Error getting jobs statistics: " . $e->getMessage());
            return ['active_jobs' => 0, 'closed_jobs' => 0, 'draft_jobs' => 0, 'total_jobs' => 0, 'avg_job_age_days' => 0];
        }
    }
    
    // Calculate conversion rates
    public function getConversionRates($period = '30 days') {
        $metrics = $this->getRecruitmentMetrics($period);
        
        $applications = $metrics['application_received']['total'] ?? 0;
        $interviews = $metrics['interview_scheduled']['total'] ?? 0;
        $hires = $metrics['candidate_hired']['total'] ?? 0;
        
        return [
            'application_to_interview' => $applications > 0 ? round(($interviews / $applications) * 100, 2) : 0,
            'interview_to_hire' => $interviews > 0 ? round(($hires / $interviews) * 100, 2) : 0,
            'application_to_hire' => $applications > 0 ? round(($hires / $applications) * 100, 2) : 0,
        ];
    }
    
    private function parsePeriodToDays($period) {
        $periods = [
            '7 days' => 7,
            '30 days' => 30,
            '90 days' => 90,
            '6 months' => 180,
            '1 year' => 365
        ];
        
        return $periods[$period] ?? 30;
    }
    
    // Export data for reports
    public function exportMetricsToCSV($metrics, $filename) {
        $filepath = UPLOAD_PATH . 'reports/' . $filename;
        
        // Create reports directory if it doesn't exist
        if (!is_dir(UPLOAD_PATH . 'reports/')) {
            mkdir(UPLOAD_PATH . 'reports/', 0755, true);
        }
        
        $file = fopen($filepath, 'w');
        
        // Add CSV headers
        fputcsv($file, ['Metric', 'Count', 'Value', 'Date']);
        
        // Add data rows
        foreach ($metrics as $metric => $data) {
            fputcsv($file, [$metric, $data['count'], $data['total'], date('Y-m-d')]);
        }
        
        fclose($file);
        return $filepath;
    }
}
?>