<?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);

// Get selected period from URL parameter
$selected_period = $_GET['period'] ?? '30 days';

// Get all analytics data
$recruitmentMetrics = $hrAnalytics->getRecruitmentMetrics($selected_period);
$hiringFunnel = $hrAnalytics->getHiringFunnel($selected_period);
$timeToHireStats = $hrAnalytics->getTimeToHireStats('90 days');
$sourceEffectiveness = $hrAnalytics->getSourceEffectiveness($selected_period);
$monthlyTrends = $hrAnalytics->getMonthlyTrends(6);
$jobsStats = $hrAnalytics->getJobsStatistics();
$conversionRates = $hrAnalytics->getConversionRates($selected_period);
$detailedStats = $hrAnalytics->getDetailedStats($selected_period);

// Handle export request
if (isset($_POST['export'])) {
    $filename = 'hr_metrics_' . date('Y-m-d') . '.csv';
    $filepath = $hrAnalytics->exportMetricsToCSV($recruitmentMetrics, $filename);
    
    if (file_exists($filepath)) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        readfile($filepath);
        unlink($filepath); // Clean up
        exit;
    }
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HR Analytics Dashboard - <?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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            --warning-gradient: linear-gradient(135deg, #ffeaa7 0%, #fab1a0 100%);
            --danger-gradient: linear-gradient(135deg, #fd79a8 0%, #fdcb6e 100%);
            --glass-bg: rgba(255, 255, 255, 0.25);
            --glass-border: rgba(255, 255, 255, 0.18);
            --shadow-light: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
            --shadow-card: 0 4px 30px rgba(0, 0, 0, 0.1);
            --border-radius: 20px;
            --text-primary: #2d3748;
            --text-secondary: #718096;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
        }

        /* Modern Glassmorphism Cards */
        .metric-card {
            backdrop-filter: blur(16px) saturate(180%);
            -webkit-backdrop-filter: blur(16px) saturate(180%);
            background: var(--glass-bg);
            border: 1px solid var(--glass-border);
            border-radius: var(--border-radius);
            padding: 2rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: var(--shadow-light);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .metric-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
            border-radius: var(--border-radius) var(--border-radius) 0 0;
        }

        .metric-card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
        }

        .metric-card.success::before {
            background: var(--success-gradient);
        }

        .metric-card.warning::before {
            background: var(--warning-gradient);
        }

        .metric-card.danger::before {
            background: var(--danger-gradient);
        }

        .metric-number {
            font-size: 3rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: var(--text-primary);
            line-height: 1;
        }

        .metric-label {
            font-size: 0.875rem;
            font-weight: 500;
            color: var(--text-secondary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
        }

        .metric-label i {
            margin-right: 0.5rem;
            font-size: 1.1rem;
            opacity: 0.7;
        }

        /* Modern Chart Containers */
        .chart-container {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: var(--border-radius);
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: var(--shadow-card);
            transition: all 0.3s ease;
        }

        .chart-container:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 40px rgba(0, 0, 0, 0.12);
        }

        .chart-container h5 {
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 1.5rem;
            font-size: 1.25rem;
        }

        /* Modern Funnel Visualization */
        .funnel-container {
            background: white;
            border-radius: var(--border-radius);
            padding: 1.5rem;
            margin-bottom: 1rem;
            box-shadow: var(--shadow-card);
            transition: all 0.3s ease;
        }

        .funnel-container:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 40px rgba(0, 0, 0, 0.12);
        }

        .funnel-job-title {
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 1rem;
            font-size: 1.1rem;
        }

        .funnel-stage {
            display: flex;
            align-items: center;
            margin-bottom: 0.75rem;
            padding: 0.75rem;
            border-radius: 12px;
            background: linear-gradient(90deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.05) 100%);
            transition: all 0.3s ease;
        }

        .funnel-stage:hover {
            background: linear-gradient(90deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.1) 100%);
            transform: translateX(5px);
        }

        .funnel-bar {
            height: 8px;
            border-radius: 6px;
            background: var(--primary-gradient);
            margin-right: 1rem;
            flex: 1;
            max-width: 200px;
            position: relative;
            overflow: hidden;
        }

        .funnel-bar::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.6), transparent);
            animation: shimmer 2s infinite;
        }

        @keyframes shimmer {
            0% { left: -100%; }
            100% { left: 100%; }
        }

        .funnel-label {
            font-weight: 500;
            color: var(--text-primary);
            min-width: 120px;
        }

        .funnel-count {
            font-weight: 600;
            color: var(--text-primary);
            background: rgba(102, 126, 234, 0.1);
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.875rem;
        }

        /* Modern Period Selector */
        .period-selector {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 15px;
            padding: 0.5rem;
            box-shadow: var(--shadow-card);
        }

        .period-selector select {
            background: transparent;
            border: none;
            font-weight: 500;
            color: var(--text-primary);
        }

        /* Modern Conversion Badges */
        .conversion-badge {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: var(--text-primary);
            padding: 0.75rem 1.25rem;
            border-radius: 25px;
            font-weight: 600;
            font-size: 0.875rem;
            box-shadow: var(--shadow-card);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .conversion-badge::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: var(--success-gradient);
        }

        .conversion-badge:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }

        /* Modern Summary Section */
        .summary-section {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: var(--border-radius);
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: var(--shadow-card);
        }

        .summary-badge {
            background: var(--primary-gradient);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 500;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        /* Enhanced Navigation */
        .navbar {
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
        }

        .navbar-brand, .nav-link {
            color: var(--text-primary) !important;
            font-weight: 500;
        }

        /* Button Enhancements */
        .btn {
            border-radius: 12px;
            font-weight: 500;
            padding: 0.75rem 1.5rem;
            transition: all 0.3s ease;
            border: none;
        }

        .btn-success {
            background: var(--success-gradient);
            box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4);
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(17, 153, 142, 0.4);
        }

        .btn-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-info:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .metric-card {
                padding: 1.5rem 1rem;
                margin-bottom: 1rem;
            }
            
            .metric-number {
                font-size: 2.5rem;
            }
            
            .chart-container {
                padding: 1.5rem 1rem;
            }
            
            .conversion-badge {
                margin-bottom: 0.5rem;
                width: calc(50% - 0.5rem);
                text-align: center;
            }
        }

        /* Loading Animation */
        .loading-shimmer {
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: loading 2s infinite;
        }

        @keyframes loading {
            0% { background-position: 200% 0; }
            100% { background-position: -200% 0; }
        }
    </style>
</head>
<body class="bg-light">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="dashboard.php">
                <i class="fas fa-chart-line me-2"></i>HR Analytics
            </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="dashboard.php">
                    <i class="fas fa-arrow-left me-1"></i>Back to Dashboard
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid py-4">
        <!-- Header -->
        <div class="row mb-4">
            <div class="col-md-6">
                <h1 class="h3 mb-0" style="color: var(--text-primary); font-weight: 700;">
                    <i class="fas fa-chart-line me-3" style="color: #667eea;"></i>
                    HR Analytics Dashboard
                </h1>
                <p style="color: var(--text-secondary); font-size: 1rem; margin-top: 0.5rem;">Comprehensive recruitment and HR metrics with real-time insights</p>
            </div>
            <div class="col-md-6 text-end">
                <!-- Period Selector -->
                <div class="period-selector d-inline-block">
                    <select class="form-select" id="periodSelector" onchange="changePeriod()">
                        <option value="7 days" <?php echo $selected_period === '7 days' ? 'selected' : ''; ?>>Last 7 Days</option>
                        <option value="30 days" <?php echo $selected_period === '30 days' ? 'selected' : ''; ?>>Last 30 Days</option>
                        <option value="90 days" <?php echo $selected_period === '90 days' ? 'selected' : ''; ?>>Last 90 Days</option>
                        <option value="6 months" <?php echo $selected_period === '6 months' ? 'selected' : ''; ?>>Last 6 Months</option>
                    </select>
                </div>
                <form method="POST" class="d-inline-block ms-2">
                    <button type="submit" name="export" class="btn btn-success">
                        <i class="fas fa-file-excel me-1"></i>Export Excel
                    </button>
                </form>
                <a href="hr-reports.php?period=<?php echo urlencode($selected_period); ?>" class="btn btn-info ms-2">
                    <i class="fas fa-file-alt me-1"></i>Generate Report
                </a>
            </div>
        </div>

        <!-- Summary Section -->
        <?php if ($detailedStats['total_applications'] > 0): ?>
        <div class="row mb-4">
            <div class="col-12">
                <div class="summary-section">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h6 class="mb-2" style="color: var(--text-primary); font-weight: 600;">
                                <i class="fas fa-info-circle me-2" style="color: #667eea;"></i>
                                Analytics Summary for <?php echo ucfirst($selected_period); ?>
                            </h6>
                            <p class="mb-0" style="color: var(--text-secondary);">
                                Showing data from <strong style="color: var(--text-primary);"><?php echo $detailedStats['total_applications']; ?> applications</strong> 
                                from <strong style="color: var(--text-primary);"><?php echo $detailedStats['unique_candidates']; ?> unique candidates</strong> 
                                across <strong style="color: var(--text-primary);"><?php echo $detailedStats['jobs_with_applications']; ?> job positions</strong>.
                                <?php if ($detailedStats['first_application'] && $detailedStats['latest_application']): ?>
                                    <br><small style="color: var(--text-secondary); font-size: 0.8rem;">
                                        Date range: <?php echo date('M d, Y', strtotime($detailedStats['first_application'])); ?> - 
                                        <?php echo date('M d, Y', strtotime($detailedStats['latest_application'])); ?>
                                    </small>
                                <?php endif; ?>
                            </p>
                        </div>
                        <div class="col-md-4 text-end">
                            <div class="summary-badge">
                                Real-time data from your applications
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Key Metrics Row -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="metric-card">
                    <div class="metric-number"><?php echo $recruitmentMetrics['application_received']['total'] ?? 0; ?></div>
                    <div class="metric-label">
                        <i class="fas fa-file-alt me-1"></i>Applications Received
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="metric-card success">
                    <div class="metric-number"><?php echo $recruitmentMetrics['shortlisted']['total'] ?? 0; ?></div>
                    <div class="metric-label">
                        <i class="fas fa-star me-1"></i>Shortlisted
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="metric-card warning">
                    <div class="metric-number"><?php echo $recruitmentMetrics['interviewed']['total'] ?? 0; ?></div>
                    <div class="metric-label">
                        <i class="fas fa-users me-1"></i>Interviewed
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="metric-card danger">
                    <div class="metric-number"><?php echo round($timeToHireStats['avg_time_to_hire'] ?? 0); ?> days</div>
                    <div class="metric-label">
                        <i class="fas fa-clock me-1"></i>Avg Days Since Applied
                    </div>
                </div>
            </div>
        </div>

        <!-- Jobs Statistics -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="metric-card success">
                    <div class="metric-number"><?php echo $jobsStats['active_jobs']; ?></div>
                    <div class="metric-label">
                        <i class="fas fa-briefcase me-1"></i>Active Jobs
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="metric-card">
                    <div class="metric-number"><?php echo $jobsStats['total_jobs']; ?></div>
                    <div class="metric-label">
                        <i class="fas fa-list me-1"></i>Total Jobs Posted
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <h5 class="mb-3">
                        <i class="fas fa-percentage me-2 text-primary"></i>Conversion Rates
                    </h5>
                    <div class="d-flex flex-wrap justify-content-between">
                        <span class="conversion-badge mb-2">
                            App → Shortlist: <?php echo $conversionRates['application_to_shortlist']; ?>%
                        </span>
                        <span class="conversion-badge mb-2">
                            Shortlist → Interview: <?php echo $conversionRates['shortlist_to_interview']; ?>%
                        </span>
                        <span class="conversion-badge mb-2">
                            Interview → Hire: <?php echo $conversionRates['interview_to_hire']; ?>%
                        </span>
                        <span class="conversion-badge mb-2">
                            Overall → Hire: <?php echo $conversionRates['application_to_hire']; ?>%
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts Row -->
        <div class="row mb-4">
            <!-- Hiring Funnel -->
            <div class="col-md-8">
                <div class="chart-container">
                    <h5 class="mb-3">
                        <i class="fas fa-funnel-dollar me-2 text-primary"></i>Hiring Funnel by Job
                    </h5>
                    <?php if (!empty($hiringFunnel)): ?>
                        <?php foreach ($hiringFunnel as $job): ?>
                            <div class="funnel-container">
                                <div class="funnel-job-title"><?php echo htmlspecialchars($job['job_title']); ?></div>
                                
                                <div class="funnel-stage">
                                    <div class="funnel-label">Applications</div>
                                    <div class="funnel-bar" style="width: 100%;"></div>
                                    <div class="funnel-count"><?php echo $job['applications']; ?></div>
                                </div>
                                
                                <div class="funnel-stage">
                                    <div class="funnel-label">Shortlisted</div>
                                    <div class="funnel-bar" style="width: <?php echo $job['applications'] > 0 ? ($job['shortlisted'] / $job['applications']) * 100 : 0; ?>%; background: var(--success-gradient);"></div>
                                    <div class="funnel-count"><?php echo $job['shortlisted']; ?></div>
                                </div>
                                
                                <div class="funnel-stage">
                                    <div class="funnel-label">Interviewed</div>
                                    <div class="funnel-bar" style="width: <?php echo $job['applications'] > 0 ? ($job['interviewed'] / $job['applications']) * 100 : 0; ?>%; background: var(--warning-gradient);"></div>
                                    <div class="funnel-count"><?php echo $job['interviewed']; ?></div>
                                </div>
                                
                                <div class="funnel-stage">
                                    <div class="funnel-label">Hired</div>
                                    <div class="funnel-bar" style="width: <?php echo $job['applications'] > 0 ? ($job['hired'] / $job['applications']) * 100 : 0; ?>%; background: var(--success-gradient);"></div>
                                    <div class="funnel-count"><?php echo $job['hired']; ?></div>
                                </div>
                                
                                <div class="funnel-stage">
                                    <div class="funnel-label">Rejected</div>
                                    <div class="funnel-bar" style="width: <?php echo $job['applications'] > 0 ? ($job['rejected'] / $job['applications']) * 100 : 0; ?>%; background: var(--danger-gradient);"></div>
                                    <div class="funnel-count"><?php echo $job['rejected']; ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-chart-bar fa-3x mb-3"></i>
                            <p>No hiring funnel data available for the selected period.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Monthly Trends Chart -->
            <div class="col-md-4">
                <div class="chart-container">
                    <h5 class="mb-3">
                        <i class="fas fa-chart-line me-2 text-primary"></i>Monthly Trends
                    </h5>
                    <canvas id="monthlyTrendsChart" width="400" height="300"></canvas>
                </div>
            </div>
        </div>

        <!-- Source Effectiveness -->
        <?php if (!empty($sourceEffectiveness)): ?>
        <div class="row mb-4">
            <div class="col-12">
                <div class="chart-container">
                    <h5 class="mb-3">
                        <i class="fas fa-bullseye me-2 text-primary"></i>Source Effectiveness
                    </h5>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Source</th>
                                    <th>Applications</th>
                                    <th>Hires</th>
                                    <th>Conversion Rate</th>
                                    <th>Effectiveness</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($sourceEffectiveness 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>
                                        <div class="progress" style="height: 20px;">
                                            <div class="progress-bar bg-success" role="progressbar" 
                                                 style="width: <?php echo $source['conversion_rate']; ?>%">
                                                <?php echo $source['conversion_rate']; ?>%
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Monthly trends chart
        const monthlyTrendsData = <?php echo json_encode($monthlyTrends); ?>;
        
        if (Object.keys(monthlyTrendsData).length > 0) {
            const ctx = document.getElementById('monthlyTrendsChart').getContext('2d');
            
            const months = Object.keys(monthlyTrendsData);
            const applicationsData = months.map(month => monthlyTrendsData[month]['application_received'] || 0);
            const hiresData = months.map(month => monthlyTrendsData[month]['candidate_hired'] || 0);
            
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: months,
                    datasets: [{
                        label: 'Applications',
                        data: applicationsData,
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        tension: 0.4
                    }, {
                        label: 'Hires',
                        data: hiresData,
                        borderColor: 'rgb(255, 99, 132)',
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'top',
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
        
        // Period selector function
        function changePeriod() {
            const period = document.getElementById('periodSelector').value;
            window.location.href = '?period=' + encodeURIComponent(period);
        }
        
        // Auto-refresh every 5 minutes
        setTimeout(function() {
            location.reload();
        }, 300000);
    </script>
</body>
</html>