<?php
require_once '../config/config.php';
require_once '../includes/excel_generator.php';
require_once '../includes/real_hr_analytics.php';
requireLogin('company');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('hr-analytics.php');
}

$database = new Database();
$db = $database->getConnection();
$company_id = $_SESSION['company_id'];
$hrAnalytics = new RealHRAnalytics($db, $company_id);

$export_type = $_POST['export_type'] ?? 'metrics';
$period = $_POST['period'] ?? '30 days';

try {
    switch ($export_type) {
        case 'metrics':
            $metrics = $hrAnalytics->getRecruitmentMetrics($period);
            $conversion = $hrAnalytics->getConversionRates($period);
            $timeToHire = $hrAnalytics->getTimeToHireStats('90 days');
            
            $data = [
                ['Metric', 'Value', 'Period'],
                ['Applications Received', $metrics['application_received']['total'] ?? 0, $period],
                ['Interviews Scheduled', $metrics['interview_scheduled']['total'] ?? 0, $period],
                ['Candidates Hired', $metrics['candidate_hired']['total'] ?? 0, $period],
                ['Candidates Rejected', $metrics['candidate_rejected']['total'] ?? 0, $period],
                ['Average Time to Hire (days)', round($timeToHire['avg_time_to_hire'] ?? 0), '90 days'],
                ['Application to Interview Rate (%)', $conversion['application_to_interview'], $period],
                ['Interview to Hire Rate (%)', $conversion['interview_to_hire'], $period],
                ['Overall Conversion Rate (%)', $conversion['application_to_hire'], $period]
            ];
            
            $headers = ['Metric', 'Value', 'Period'];
            $filename = 'hr_metrics_' . date('Y-m-d_H-i-s');
            break;
            
        case 'funnel':
            $funnel = $hrAnalytics->getHiringFunnel($period);
            
            $data = [];
            $headers = ['Job Title', 'Applications', 'Interviews', 'Hired', 'Rejected', 'Success Rate (%)'];
            
            foreach ($funnel as $job) {
                $successRate = $job['applications'] > 0 ? round(($job['hired'] / $job['applications']) * 100, 2) : 0;
                $data[] = [
                    $job['job_title'],
                    $job['applications'],
                    $job['interviews'],
                    $job['hired'],
                    $job['rejected'],
                    $successRate
                ];
            }
            
            $filename = 'hiring_funnel_' . date('Y-m-d_H-i-s');
            break;
            
        case 'sources':
            $sources = $hrAnalytics->getSourceEffectiveness($period);
            
            $data = [];
            $headers = ['Source', 'Applications', 'Hires', 'Conversion Rate (%)', 'Period'];
            
            foreach ($sources as $source) {
                $data[] = [
                    ucfirst($source['source_name']),
                    $source['applications_count'],
                    $source['hires_count'],
                    $source['conversion_rate'],
                    $period
                ];
            }
            
            $filename = 'source_effectiveness_' . date('Y-m-d_H-i-s');
            break;
            
        default:
            throw new Exception('Invalid export type');
    }
    
    if (empty($data)) {
        throw new Exception('No data available for export');
    }
    
    // Create and export Excel file
    $exporter = new ExcelGenerator($data, $headers, $filename);
    $exporter->export();
    
} catch (Exception $e) {
    $_SESSION['error'] = 'Export failed: ' . $e->getMessage();
    redirect('hr-analytics.php');
}
?>