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

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

// Handle report generation
$report_type = $_GET['type'] ?? 'overview';
$period = $_GET['period'] ?? '30 days';

// Get company info
$stmt = $db->prepare("SELECT name FROM companies WHERE id = ?");
$stmt->execute([$company_id]);
$company = $stmt->fetch();

$reportData = [];
$reportTitle = '';

switch ($report_type) {
    case 'recruitment':
        $reportTitle = 'Recruitment Performance Report';
        $reportData = [
            'metrics' => $hrAnalytics->getRecruitmentMetrics($period),
            'funnel' => $hrAnalytics->getHiringFunnel($period),
            'timeToHire' => $hrAnalytics->getTimeToHireStats('90 days'),
            'conversion' => $hrAnalytics->getConversionRates($period)
        ];
        break;
        
    case 'performance':
        $reportTitle = 'Performance Metrics Report';
        $reportData = [
            'jobs' => $hrAnalytics->getJobsStatistics(),
            'trends' => $hrAnalytics->getMonthlyTrends(6),
            'sources' => $hrAnalytics->getSourceEffectiveness($period)
        ];
        break;
        
    case 'overview':
    default:
        $reportTitle = 'HR Overview Report';
        $reportData = [
            'metrics' => $hrAnalytics->getRecruitmentMetrics($period),
            'jobs' => $hrAnalytics->getJobsStatistics(),
            'timeToHire' => $hrAnalytics->getTimeToHireStats('90 days'),
            'conversion' => $hrAnalytics->getConversionRates($period)
        ];
        break;
}

// Handle PDF export
if (isset($_GET['export']) && $_GET['export'] === 'pdf') {
    require_once '../includes/fpdf_report_generator.php';
    
    try {
        $pdfGenerator = new FPDFReportGenerator($reportData, $reportTitle, $period, $company['name']);
        $pdfContent = $pdfGenerator->generateReport();
        
        // Set PDF headers
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . sanitizeFilename($reportTitle) . '_' . date('Y-m-d') . '.pdf"');
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Content-Length: ' . strlen($pdfContent));
        
        echo $pdfContent;
        exit;
        
    } catch (Exception $e) {
        // Fallback to HTML download with PDF instructions
        $html_content = generatePDFContent($reportData, $reportTitle, $period, $company['name']);
        
        header('Content-Type: text/html');
        header('Content-Disposition: attachment; filename="' . sanitizeFilename($reportTitle) . '_' . date('Y-m-d') . '.html"');
        header('Cache-Control: no-cache, no-store, must-revalidate');
        
        echo $html_content;
        exit;
    }
}

function sanitizeFilename($filename) {
    return preg_replace('/[^a-zA-Z0-9_-]/', '_', $filename);
}

function generatePDFContent($reportData, $reportTitle, $period, $companyName) {
    ob_start();
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title><?php echo htmlspecialchars($reportTitle); ?></title>
        <style>
            @media print { @page { margin: 1in; } }
            body { font-family: Arial, sans-serif; margin: 0; padding: 20px; color: #333; }
            .header { text-align: center; border-bottom: 3px solid #667eea; padding-bottom: 20px; margin-bottom: 30px; }
            .header h1 { color: #667eea; margin: 0; font-size: 28px; }
            .header p { margin: 5px 0; color: #666; }
            .section { margin-bottom: 30px; page-break-inside: avoid; }
            .section h2 { color: #667eea; border-bottom: 2px solid #f0f0f0; padding-bottom: 10px; }
            .metrics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0; }
            .metric-box { border: 2px solid #e9ecef; border-radius: 8px; padding: 15px; text-align: center; }
            .metric-number { font-size: 24px; font-weight: bold; color: #667eea; margin-bottom: 5px; }
            .metric-label { font-size: 14px; color: #666; }
            table { width: 100%; border-collapse: collapse; margin: 15px 0; }
            th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
            th { background-color: #f8f9fa; font-weight: bold; color: #495057; }
            .conversion-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; }
            .conversion-box { border: 2px solid #28a745; border-radius: 8px; padding: 15px; text-align: center; }
            .conversion-rate { font-size: 18px; font-weight: bold; color: #28a745; }
            .footer { text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #666; font-size: 12px; }
        </style>
    </head>
    <body>
        <div class="header">
            <h1><?php echo htmlspecialchars($reportTitle); ?></h1>
            <p><strong><?php echo htmlspecialchars($companyName); ?></strong></p>
            <p>Generated on <?php echo date('F j, Y \\a\\t g:i A'); ?></p>
            <p>Period: <?php echo htmlspecialchars(ucfirst($period)); ?></p>
        </div>

        <?php if (isset($reportData['metrics'])): ?>
        <div class="section">
            <h2>Recruitment Summary</h2>
            <div class="metrics-grid">
                <div class="metric-box">
                    <div class="metric-number"><?php echo $reportData['metrics']['application_received']['total'] ?? 0; ?></div>
                    <div class="metric-label">Applications Received</div>
                </div>
                <div class="metric-box">
                    <div class="metric-number"><?php echo $reportData['metrics']['shortlisted']['total'] ?? 0; ?></div>
                    <div class="metric-label">Shortlisted</div>
                </div>
                <div class="metric-box">
                    <div class="metric-number"><?php echo $reportData['metrics']['interviewed']['total'] ?? 0; ?></div>
                    <div class="metric-label">Interviewed</div>
                </div>
                <div class="metric-box">
                    <div class="metric-number"><?php echo $reportData['metrics']['hired']['total'] ?? 0; ?></div>
                    <div class="metric-label">Hired</div>
                </div>
            </div>
            
            <?php if (isset($reportData['conversion'])): ?>
            <h3>Conversion Rates</h3>
            <div class="conversion-grid">
                <div class="conversion-box">
                    <div class="conversion-rate"><?php echo $reportData['conversion']['application_to_shortlist'] ?? 0; ?>%</div>
                    <div class="metric-label">App → Shortlist</div>
                </div>
                <div class="conversion-box">
                    <div class="conversion-rate"><?php echo $reportData['conversion']['shortlist_to_interview'] ?? 0; ?>%</div>
                    <div class="metric-label">Shortlist → Interview</div>
                </div>
                <div class="conversion-box">
                    <div class="conversion-rate"><?php echo $reportData['conversion']['interview_to_hire'] ?? 0; ?>%</div>
                    <div class="metric-label">Interview → Hire</div>
                </div>
                <div class="conversion-box">
                    <div class="conversion-rate"><?php echo $reportData['conversion']['application_to_hire'] ?? 0; ?>%</div>
                    <div class="metric-label">Overall Conversion</div>
                </div>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php if (isset($reportData['funnel']) && !empty($reportData['funnel'])): ?>
        <div class="section">
            <h2>Hiring Funnel Analysis</h2>
            <table>
                <thead>
                    <tr>
                        <th>Job Position</th>
                        <th>Applications</th>
                        <th>Shortlisted</th>
                        <th>Interviewed</th>
                        <th>Hired</th>
                        <th>Success Rate</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($reportData['funnel'] as $job): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($job['job_title']); ?></td>
                        <td><?php echo $job['applications']; ?></td>
                        <td><?php echo $job['shortlisted'] ?? 0; ?></td>
                        <td><?php echo $job['interviewed'] ?? 0; ?></td>
                        <td><?php echo $job['hired']; ?></td>
                        <td><?php echo $job['applications'] > 0 ? round(($job['hired'] / $job['applications']) * 100, 1) : 0; ?>%</td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

        <?php if (isset($reportData['sources']) && !empty($reportData['sources'])): ?>
        <div class="section">
            <h2>Source Effectiveness Analysis</h2>
            <table>
                <thead>
                    <tr>
                        <th>Source</th>
                        <th>Applications</th>
                        <th>Hires</th>
                        <th>Conversion Rate</th>
                        <th>ROI Rating</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($reportData['sources'] as $source): ?>
                    <tr>
                        <td><?php echo htmlspecialchars(ucfirst($source['source_name'])); ?></td>
                        <td><?php echo $source['applications_count']; ?></td>
                        <td><?php echo $source['hires_count']; ?></td>
                        <td><?php echo $source['conversion_rate']; ?>%</td>
                        <td>
                            <?php 
                            $rating = $source['conversion_rate'] > 15 ? 'Excellent' : 
                                     ($source['conversion_rate'] > 10 ? 'Good' : 
                                     ($source['conversion_rate'] > 5 ? 'Average' : 'Poor'));
                            echo $rating;
                            ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

        <?php if (isset($reportData['timeToHire'])): ?>
        <div class="section">
            <h2>Time to Hire Statistics</h2>
            <div class="metrics-grid">
                <div class="metric-box">
                    <div class="metric-number"><?php echo round($reportData['timeToHire']['avg_time_to_hire'] ?? 0); ?> days</div>
                    <div class="metric-label">Average Time to Hire</div>
                </div>
                <div class="metric-box">
                    <div class="metric-number"><?php echo $reportData['timeToHire']['min_time_to_hire'] ?? 0; ?> days</div>
                    <div class="metric-label">Fastest Hire</div>
                </div>
                <div class="metric-box">
                    <div class="metric-number"><?php echo $reportData['timeToHire']['max_time_to_hire'] ?? 0; ?> days</div>
                    <div class="metric-label">Longest Process</div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="footer">
            <p>Report generated by <?php echo SITE_NAME; ?> HR Analytics System</p>
            <p>This document can be printed as PDF using your browser's print function</p>
        </div>
    </body>
    </html>
    <?php
    return ob_get_clean();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $reportTitle; ?> - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .report-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .metric-summary {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .performance-indicator {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #333;
            padding: 1rem;
            border-radius: 10px;
            text-align: center;
            margin-bottom: 1rem;
        }
        
        .report-section {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .trend-positive {
            color: #28a745;
        }
        
        .trend-negative {
            color: #dc3545;
        }
        
        .trend-neutral {
            color: #6c757d;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body class="bg-light">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <div class="container-fluid">
            <a class="navbar-brand" href="hr-analytics.php">
                <i class="fas fa-chart-bar me-2"></i>HR Reports
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    <i class="fas fa-building me-1"></i>
                    <?php echo htmlspecialchars($company['name']); ?>
                </span>
                <a class="nav-link" href="hr-analytics.php">
                    <i class="fas fa-arrow-left me-1"></i>Back to Analytics
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid py-4">
        <!-- Report Header -->
        <div class="report-header">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="h2 mb-2">
                        <i class="fas fa-file-alt me-2"></i>
                        <?php echo $reportTitle; ?>
                    </h1>
                    <p class="mb-0">
                        Generated on <?php echo date('F j, Y \a\t g:i A'); ?> for 
                        <strong><?php echo htmlspecialchars($company['name']); ?></strong>
                    </p>
                    <small class="opacity-75">Period: <?php echo ucfirst($period); ?></small>
                </div>
                <div class="col-md-4 text-end no-print">
                    <div class="btn-group">
                        <button class="btn btn-light" onclick="window.print()">
                            <i class="fas fa-print me-1"></i>Print
                        </button>
                        <a href="?<?php echo http_build_query(array_merge($_GET, ['export' => 'pdf'])); ?>" class="btn btn-light">
                            <i class="fas fa-file-pdf me-1"></i>Export PDF
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Report Type Selector -->
        <div class="row mb-4 no-print">
            <div class="col-12">
                <div class="btn-group w-100">
                    <a href="?type=overview&period=<?php echo $period; ?>" 
                       class="btn <?php echo $report_type === 'overview' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                        <i class="fas fa-eye me-1"></i>Overview
                    </a>
                    <a href="?type=recruitment&period=<?php echo $period; ?>" 
                       class="btn <?php echo $report_type === 'recruitment' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                        <i class="fas fa-users me-1"></i>Recruitment
                    </a>
                    <a href="?type=performance&period=<?php echo $period; ?>" 
                       class="btn <?php echo $report_type === 'performance' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                        <i class="fas fa-chart-line me-1"></i>Performance
                    </a>
                </div>
            </div>
        </div>

        <?php if ($report_type === 'overview' || $report_type === 'recruitment'): ?>
        <!-- Recruitment Metrics -->
        <div class="report-section">
            <h3 class="mb-4">
                <i class="fas fa-user-plus me-2 text-primary"></i>
                Recruitment Summary
            </h3>
            
            <div class="row">
                <div class="col-md-3">
                    <div class="performance-indicator">
                        <h4><?php echo $reportData['metrics']['application_received']['total'] ?? 0; ?></h4>
                        <p class="mb-0">Applications Received</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="performance-indicator">
                        <h4><?php echo $reportData['metrics']['interview_scheduled']['total'] ?? 0; ?></h4>
                        <p class="mb-0">Interviews Scheduled</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="performance-indicator">
                        <h4><?php echo $reportData['metrics']['candidate_hired']['total'] ?? 0; ?></h4>
                        <p class="mb-0">Candidates Hired</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="performance-indicator">
                        <h4><?php echo round($reportData['timeToHire']['avg_time_to_hire'] ?? 0); ?> days</h4>
                        <p class="mb-0">Avg. Time to Hire</p>
                    </div>
                </div>
            </div>

            <?php if (isset($reportData['conversion'])): ?>
            <h5 class="mt-4 mb-3">Conversion Rates</h5>
            <div class="row">
                <div class="col-md-4">
                    <div class="metric-summary text-center">
                        <h4 class="text-primary"><?php echo $reportData['conversion']['application_to_shortlist'] ?? 0; ?>%</h4>
                        <p class="mb-0">Application → Shortlist</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="metric-summary text-center">
                        <h4 class="text-warning"><?php echo $reportData['conversion']['shortlist_to_interview'] ?? 0; ?>%</h4>
                        <p class="mb-0">Shortlist → Interview</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="metric-summary text-center">
                        <h4 class="text-success"><?php echo $reportData['conversion']['interview_to_hire'] ?? 0; ?>%</h4>
                        <p class="mb-0">Interview → Hire</p>
                    </div>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-md-6 offset-md-3">
                    <div class="metric-summary text-center">
                        <h4 class="text-info"><?php echo $reportData['conversion']['application_to_hire'] ?? 0; ?>%</h4>
                        <p class="mb-0">Overall Application → Hire</p>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php if (($report_type === 'recruitment' || $report_type === 'overview') && !empty($reportData['funnel'])): ?>
        <!-- Hiring Funnel -->
        <div class="report-section">
            <h3 class="mb-4">
                <i class="fas fa-funnel-dollar me-2 text-primary"></i>
                Hiring Funnel Analysis
            </h3>
            
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Job Position</th>
                            <th>Applications</th>
                            <th>Shortlisted</th>
                            <th>Interviewed</th>
                            <th>Hired</th>
                            <th>Rejected</th>
                            <th>Success Rate</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($reportData['funnel'] as $job): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($job['job_title']); ?></td>
                            <td><?php echo $job['applications']; ?></td>
                            <td><?php echo $job['shortlisted'] ?? 0; ?></td>
                            <td><?php echo $job['interviewed'] ?? 0; ?></td>
                            <td class="text-success"><?php echo $job['hired']; ?></td>
                            <td class="text-danger"><?php echo $job['rejected']; ?></td>
                            <td>
                                <?php 
                                $successRate = $job['applications'] > 0 ? round(($job['hired'] / $job['applications']) * 100, 1) : 0;
                                $class = $successRate > 10 ? 'trend-positive' : ($successRate > 5 ? 'trend-neutral' : 'trend-negative');
                                ?>
                                <span class="<?php echo $class; ?>">
                                    <i class="fas fa-<?php echo $successRate > 10 ? 'arrow-up' : ($successRate > 5 ? 'minus' : 'arrow-down'); ?> me-1"></i>
                                    <?php echo $successRate; ?>%
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($report_type === 'performance' && !empty($reportData['sources'])): ?>
        <!-- Source Effectiveness -->
        <div class="report-section">
            <h3 class="mb-4">
                <i class="fas fa-bullseye me-2 text-primary"></i>
                Source Effectiveness Analysis
            </h3>
            
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Source</th>
                            <th>Applications</th>
                            <th>Hires</th>
                            <th>Conversion Rate</th>
                            <th>ROI Rating</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($reportData['sources'] as $source): ?>
                        <tr>
                            <td>
                                <i class="fas fa-globe me-2"></i>
                                <?php echo htmlspecialchars(ucfirst($source['source_name'])); ?>
                            </td>
                            <td><?php echo $source['applications_count']; ?></td>
                            <td><?php echo $source['hires_count']; ?></td>
                            <td><?php echo $source['conversion_rate']; ?>%</td>
                            <td>
                                <?php 
                                $rating = $source['conversion_rate'] > 15 ? 'Excellent' : ($source['conversion_rate'] > 10 ? 'Good' : ($source['conversion_rate'] > 5 ? 'Average' : 'Poor'));
                                $class = $source['conversion_rate'] > 15 ? 'trend-positive' : ($source['conversion_rate'] > 5 ? 'trend-neutral' : 'trend-negative');
                                ?>
                                <span class="<?php echo $class; ?>">
                                    <?php echo $rating; ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <!-- Recommendations -->
        <div class="report-section">
            <h3 class="mb-4">
                <i class="fas fa-lightbulb me-2 text-warning"></i>
                AI-Powered Recommendations
            </h3>
            
            <div class="row">
                <?php
                $applications = $reportData['metrics']['application_received']['total'] ?? 0;
                $hires = $reportData['metrics']['candidate_hired']['total'] ?? 0;
                $avgTimeToHire = $reportData['timeToHire']['avg_time_to_hire'] ?? 0;
                
                $recommendations = [];
                
                if ($applications < 10) {
                    $recommendations[] = [
                        'type' => 'warning',
                        'title' => 'Low Application Volume',
                        'text' => 'Consider expanding job posting reach or reviewing job descriptions to attract more candidates.'
                    ];
                }
                
                if ($avgTimeToHire > 30) {
                    $recommendations[] = [
                        'type' => 'danger',
                        'title' => 'Slow Hiring Process',
                        'text' => 'Average time to hire is above industry standard. Streamline interview process to reduce candidate drop-off.'
                    ];
                }
                
                if (($hires / max($applications, 1)) < 0.05) {
                    $recommendations[] = [
                        'type' => 'info',
                        'title' => 'Low Conversion Rate',
                        'text' => 'Consider reviewing candidate screening criteria or improving interview process effectiveness.'
                    ];
                }
                
                if (empty($recommendations)) {
                    $recommendations[] = [
                        'type' => 'success',
                        'title' => 'Strong Performance',
                        'text' => 'Your recruitment metrics are performing well. Continue current strategies while monitoring for improvements.'
                    ];
                }
                ?>
                
                <?php foreach ($recommendations as $rec): ?>
                <div class="col-md-6 mb-3">
                    <div class="alert alert-<?php echo $rec['type']; ?> h-100">
                        <h6><i class="fas fa-info-circle me-2"></i><?php echo $rec['title']; ?></h6>
                        <p class="mb-0"><?php echo $rec['text']; ?></p>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Footer -->
        <div class="text-center text-muted small">
            <p>Report generated by <?php echo SITE_NAME; ?> HR Analytics System</p>
            <p>For questions about this report, contact your system administrator.</p>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>