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

$database = new Database();
$db = $database->getConnection();

$company_id = $_SESSION['company_id'];

// Get company statistics
$stats = [];

// Total jobs posted
$stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs WHERE company_id = ?");
$stmt->execute([$company_id]);
$stats['total_jobs'] = $stmt->fetch()['count'];

// Active jobs
$stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs WHERE company_id = ? AND status = 'active'");
$stmt->execute([$company_id]);
$stats['active_jobs'] = $stmt->fetch()['count'];

// Total applications received
$stmt = $db->prepare("
    SELECT COUNT(*) as count 
    FROM job_applications ja 
    JOIN jobs j ON ja.job_id = j.id 
    WHERE j.company_id = ?
");
$stmt->execute([$company_id]);
$stats['total_applications'] = $stmt->fetch()['count'];

// Application status breakdown
$stmt = $db->prepare("
    SELECT ja.status, COUNT(*) as count 
    FROM job_applications ja 
    JOIN jobs j ON ja.job_id = j.id 
    WHERE j.company_id = ? 
    GROUP BY ja.status
");
$stmt->execute([$company_id]);
$status_counts = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$stats['pending_applications'] = $status_counts['applied'] ?? 0;
$stats['longlisted_applications'] = $status_counts['longlisted'] ?? 0;
$stats['shortlisted_applications'] = $status_counts['shortlisted'] ?? 0;
$stats['interviewed_applications'] = $status_counts['interviewed'] ?? 0;
$stats['hired_applications'] = $status_counts['hired'] ?? 0;
$stats['rejected_applications'] = $status_counts['rejected'] ?? 0;

// Recent jobs
$stmt = $db->prepare("
    SELECT j.*, cat.name as category_name,
           COUNT(ja.id) as application_count
    FROM jobs j 
    LEFT JOIN job_categories cat ON j.category_id = cat.id 
    LEFT JOIN job_applications ja ON j.id = ja.job_id
    WHERE j.company_id = ? 
    GROUP BY j.id
    ORDER BY j.created_at DESC 
    LIMIT 5
");
$stmt->execute([$company_id]);
$recent_jobs = $stmt->fetchAll();

// Recent applications
$stmt = $db->prepare("
    SELECT ja.*, j.title as job_title, 
           c.first_name, c.last_name, c.email
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN candidates c ON ja.candidate_id = c.id
    WHERE j.company_id = ?
    ORDER BY ja.applied_at DESC
    LIMIT 5
");
$stmt->execute([$company_id]);
$recent_applications = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Company 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">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['company_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-building me-2"></i>Company Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="post-job.php">
                                <i class="fas fa-plus-circle me-2"></i>Post New Job
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                                <?php if ($stats['pending_applications'] > 0): ?>
                                    <span class="badge bg-warning ms-2"><?php echo $stats['pending_applications']; ?></span>
                                <?php endif; ?>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="internal-candidates.php">
                                <i class="fas fa-user-tie me-2"></i>Internal Candidates
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="interviews.php">
                                <i class="fas fa-calendar-alt me-2"></i>Interviews
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="hr-analytics.php">
                                <i class="fas fa-chart-line me-2"></i>HR Analytics
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="change-password.php">
                                <i class="fas fa-lock me-2"></i>Change Password
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <h1 class="h2 mb-4">
                        <i class="fas fa-tachometer-alt me-2"></i>Company Dashboard
                    </h1>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-primary mb-2">
                                        <i class="fas fa-briefcase fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['total_jobs']; ?></h3>
                                    <p class="text-muted mb-0">Total Jobs</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-success mb-2">
                                        <i class="fas fa-check-circle fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['active_jobs']; ?></h3>
                                    <p class="text-muted mb-0">Active Jobs</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-info mb-2">
                                        <i class="fas fa-file-alt fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['total_applications']; ?></h3>
                                    <p class="text-muted mb-0">Total Applications</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-warning mb-2">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['pending_applications']; ?></h3>
                                    <p class="text-muted mb-0">Pending</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Application Status Bar Chart -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-chart-bar me-2"></i>Application Status Overview
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-lg-8">
                                    <canvas id="statusChart" height="100"></canvas>
                                </div>
                                <div class="col-lg-4">
                                    <h6 class="text-muted mb-3">Status Summary</h6>
                                    <div class="status-legend">
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="legend-color" style="background-color: #0dcaf0; width: 16px; height: 16px; border-radius: 2px; margin-right: 8px;"></div>
                                            <span class="small">Applied: <strong><?php echo $stats['pending_applications']; ?></strong></span>
                                        </div>
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="legend-color" style="background-color: #6f42c1; width: 16px; height: 16px; border-radius: 2px; margin-right: 8px;"></div>
                                            <span class="small">Longlisted: <strong><?php echo $stats['longlisted_applications']; ?></strong></span>
                                        </div>
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="legend-color" style="background-color: #ffc107; width: 16px; height: 16px; border-radius: 2px; margin-right: 8px;"></div>
                                            <span class="small">Shortlisted: <strong><?php echo $stats['shortlisted_applications']; ?></strong></span>
                                        </div>
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="legend-color" style="background-color: #fd7e14; width: 16px; height: 16px; border-radius: 2px; margin-right: 8px;"></div>
                                            <span class="small">Interviewed: <strong><?php echo $stats['interviewed_applications']; ?></strong></span>
                                        </div>
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="legend-color" style="background-color: #198754; width: 16px; height: 16px; border-radius: 2px; margin-right: 8px;"></div>
                                            <span class="small">Hired: <strong><?php echo $stats['hired_applications']; ?></strong></span>
                                        </div>
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="legend-color" style="background-color: #dc3545; width: 16px; height: 16px; border-radius: 2px; margin-right: 8px;"></div>
                                            <span class="small">Rejected: <strong><?php echo $stats['rejected_applications']; ?></strong></span>
                                        </div>
                                        <hr>
                                        <div class="d-flex align-items-center">
                                            <span class="small text-primary">Total Applications: <strong><?php echo $stats['total_applications']; ?></strong></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-bolt me-2"></i>Quick Actions
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3 mb-2">
                                    <a href="post-job.php" class="btn btn-primary w-100">
                                        <i class="fas fa-plus-circle me-2"></i>Post New Job
                                    </a>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <a href="applications.php" class="btn btn-outline-warning w-100">
                                        <i class="fas fa-file-alt me-2"></i>View Applications
                                    </a>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <a href="jobs.php" class="btn btn-outline-success w-100">
                                        <i class="fas fa-briefcase me-2"></i>Manage Jobs
                                    </a>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <a href="profile.php" class="btn btn-outline-info w-100">
                                        <i class="fas fa-building me-2"></i>Edit Profile
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Recent Jobs -->
                        <div class="col-lg-6 mb-4">
                            <div class="card h-100">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-briefcase me-2"></i>Recent Jobs
                                    </h5>
                                    <a href="jobs.php" class="btn btn-sm btn-outline-primary">View All</a>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($recent_jobs)): ?>
                                        <div class="text-center py-3">
                                            <i class="fas fa-briefcase fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">No jobs posted yet.</p>
                                            <a href="post-job.php" class="btn btn-primary">Post Your First Job</a>
                                        </div>
                                    <?php else: ?>
                                        <div class="list-group list-group-flush">
                                            <?php foreach ($recent_jobs as $job): ?>
                                                <div class="list-group-item d-flex justify-content-between align-items-center px-0">
                                                    <div>
                                                        <h6 class="mb-1"><?php echo htmlspecialchars($job['title']); ?></h6>
                                                        <small class="text-muted">
                                                            <?php echo htmlspecialchars($job['category_name']); ?> • 
                                                            <?php echo $job['application_count']; ?> applications
                                                        </small>
                                                    </div>
                                                    <span class="badge status-<?php echo $job['status']; ?>">
                                                        <?php echo ucfirst($job['status']); ?>
                                                    </span>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Recent Applications -->
                        <div class="col-lg-6 mb-4">
                            <div class="card h-100">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-file-alt me-2"></i>Recent Applications
                                    </h5>
                                    <a href="applications.php" class="btn btn-sm btn-outline-primary">View All</a>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($recent_applications)): ?>
                                        <div class="text-center py-3">
                                            <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">No applications received yet.</p>
                                        </div>
                                    <?php else: ?>
                                        <div class="list-group list-group-flush">
                                            <?php foreach ($recent_applications as $application): ?>
                                                <div class="list-group-item d-flex justify-content-between align-items-center px-0">
                                                    <div>
                                                        <h6 class="mb-1"><?php echo htmlspecialchars($application['first_name'] . ' ' . $application['last_name']); ?></h6>
                                                        <small class="text-muted">
                                                            Applied for: <?php echo htmlspecialchars($application['job_title']); ?>
                                                        </small>
                                                    </div>
                                                    <div class="text-end">
                                                        <span class="badge status-<?php echo $application['status']; ?> d-block mb-1">
                                                            <?php echo ucfirst($application['status']); ?>
                                                        </span>
                                                        <small class="text-muted"><?php echo formatDate($application['applied_at']); ?></small>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // Application Status Bar Chart
        const ctx = document.getElementById('statusChart').getContext('2d');
        const statusChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Applied', 'Longlisted', 'Shortlisted', 'Interviewed', 'Hired', 'Rejected'],
                datasets: [{
                    label: 'Applications',
                    data: [
                        <?php echo $stats['pending_applications']; ?>,
                        <?php echo $stats['longlisted_applications']; ?>,
                        <?php echo $stats['shortlisted_applications']; ?>,
                        <?php echo $stats['interviewed_applications']; ?>,
                        <?php echo $stats['hired_applications']; ?>,
                        <?php echo $stats['rejected_applications']; ?>
                    ],
                    backgroundColor: [
                        '#0dcaf0', // Applied - Info Blue
                        '#6f42c1', // Longlisted - Purple  
                        '#ffc107', // Shortlisted - Warning Yellow
                        '#fd7e14', // Interviewed - Orange
                        '#198754', // Hired - Success Green
                        '#dc3545'  // Rejected - Danger Red
                    ],
                    borderColor: [
                        '#0aa2c0',
                        '#5a359a',
                        '#d39e00',
                        '#d63310',
                        '#146c43',
                        '#b02a37'
                    ],
                    borderWidth: 1,
                    borderRadius: 4,
                    borderSkipped: false,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const total = <?php echo $stats['total_applications']; ?>;
                                const value = context.parsed.y;
                                const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                return `${context.label}: ${value} (${percentage}%)`;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1,
                            callback: function(value) {
                                if (Number.isInteger(value)) {
                                    return value;
                                }
                            }
                        },
                        grid: {
                            color: '#f8f9fa'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            maxRotation: 0,
                            font: {
                                size: 11
                            }
                        }
                    }
                },
                animation: {
                    duration: 1000,
                    easing: 'easeInOutQuart'
                },
                interaction: {
                    intersect: false,
                    mode: 'index'
                }
            }
        });

        // Add click event to navigate to applications page with filter
        statusChart.canvas.onclick = function(evt) {
            const points = statusChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
            if (points.length) {
                const firstPoint = points[0];
                const label = statusChart.data.labels[firstPoint.index];
                // Navigate to applications page with status filter
                let status = label.toLowerCase();
                if (status === 'applied') status = 'applied';
                window.location.href = `applications.php?status=${status}`;
            }
        };

        // Change cursor on hover
        statusChart.canvas.style.cursor = 'pointer';
    </script>
</body>
</html>