<?php
// हेडर को शामिल करें
require_once 'header.php';

// सुरक्षा जांच
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: my_tasks.php"); // सामान्य यूजर को My Tasks पर भेजें
    exit();
}

// --- DASHBOARD DATA FETCHING ---
// 1. एक्टिव क्लाइंट्स की संख्या
$active_clients_result = $conn->query("SELECT COUNT(id) as total FROM clients WHERE is_active = TRUE");
$active_clients_count = $active_clients_result->fetch_assoc()['total'];

// 2. पेंडिंग टास्क की संख्या
$pending_tasks_result = $conn->query("SELECT COUNT(id) as total FROM tasks WHERE status NOT IN ('Completed', 'Skipped')");
$pending_tasks_count = $pending_tasks_result->fetch_assoc()['total'];

// 3. टॉप 3 कर्मचारी (इस महीने के आधार पर)
$start_of_month = date('Y-m-01');
$end_of_month = date('Y-m-t');
$top_employees_sql = "SELECT 
                        u.id, u.name,
                        COUNT(t.id) as total_completed,
                        (SELECT COUNT(*) FROM tasks ta WHERE ta.assigned_user_id = u.id AND ta.assigned_date BETWEEN '$start_of_month' AND '$end_of_month') as total_assigned,
                        SUM(t.rejection_count > 0) as total_rejections
                    FROM tasks t
                    JOIN users u ON t.assigned_user_id = u.id
                    WHERE t.status = 'Completed' AND t.completed_at BETWEEN '$start_of_month 00:00:00' AND '$end_of_month 23:59:59'
                    GROUP BY u.id
                    ORDER BY total_completed DESC
                    LIMIT 3";
$top_employees_result = $conn->query($top_employees_sql);
$top_employees = [];
while ($row = $top_employees_result->fetch_assoc()) {
    $production = ($row['total_assigned'] > 0) ? round(($row['total_completed'] / $row['total_assigned']) * 100) : 0;
    $quality = ($row['total_completed'] > 0) ? round((($row['total_completed'] - $row['total_rejections']) / $row['total_completed']) * 100) : 100;
    $row['production'] = $production;
    $row['quality'] = $quality;
    $top_employees[] = $row;
}

// 4. कंपनी की ओवरऑल रेटिंग (इस महीने)
$company_assigned_result = $conn->query("SELECT COUNT(id) as total FROM tasks WHERE assigned_date BETWEEN '$start_of_month' AND '$end_of_month'");
$company_total_assigned = $company_assigned_result->fetch_assoc()['total'];

$company_completed_result = $conn->query("SELECT COUNT(id) as total FROM tasks WHERE status = 'Completed' AND completed_at BETWEEN '$start_of_month 00:00:00' AND '$end_of_month 23:59:59'");
$company_total_completed = $company_completed_result->fetch_assoc()['total'];

$company_rating = ($company_total_assigned > 0) ? round(($company_total_completed / $company_total_assigned) * 5, 2) : 5;


$conn->close();
?>

<title>Admin Dashboard - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Admin Dashboard</h2>

<main class="p-6 md:p-10">
    <div class.php" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-blue-100 p-3 rounded-full"><svg class="h-6 w-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a3.002 3.002 0 013.292 0l3.5 3.5m-3.5-3.5V5a3 3 0 116 0v6.143"/></svg></div>
            <div><p class="text-sm font-medium text-gray-500">Active Clients</p><p class="text-2xl font-bold text-gray-800"><?php echo $active_clients_count; ?></p></div>
        </div>
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-red-100 p-3 rounded-full"><svg class="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg></div>
            <div><p class="text-sm font-medium text-gray-500">Pending Tasks</p><p class="text-2xl font-bold text-gray-800"><?php echo $pending_tasks_count; ?></p></div>
        </div>
        <div class="bg-white p-5 rounded-lg shadow-md flex items-center gap-4">
            <div class="bg-yellow-100 p-3 rounded-full"><svg class="h-6 w-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.539 1.118l-3.975-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.196-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118L2.05 10.1c-.783-.57-.38-1.81.588-1.81h4.914a1 1 0 00.95-.69L9.53 2.927z"/></svg></div>
            <div><p class="text-sm font-medium text-gray-500">Company Rating (Monthly)</p><p class="text-2xl font-bold text-gray-800"><?php echo $company_rating; ?> / 5</p></div>
        </div>
    </div>

    <div class="bg-white rounded-lg shadow-lg p-6">
        <h3 class="text-xl font-bold mb-4">Top Performers (This Month)</h3>
        <div class="space-y-4">
            <?php if (empty($top_employees)): ?>
                <p class="text-center text-gray-500 py-8">Not enough data to determine top performers for this month.</p>
            <?php else: ?>
                <?php foreach ($top_employees as $employee): ?>
                    <div class="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50">
                        <div>
                            <p class="font-semibold text-gray-800"><?php echo htmlspecialchars($employee['name']); ?></p>
                            <p class="text-sm text-gray-500">Completed: <?php echo $employee['total_completed']; ?> Tasks</p>
                        </div>
                        <div class="flex items-center gap-6 text-center">
                            <div>
                                <p class="font-bold text-purple-600"><?php echo $employee['production']; ?>%</p>
                                <p class="text-xs text-gray-500">Production</p>
                            </div>
                            <div>
                                <p class="font-bold text-teal-600"><?php echo $employee['quality']; ?>%</p>
                                <p class="text-xs text-gray-500">Quality</p>
                            </div>
                        </div>
                        <a href="employee-profile.php?id=<?php echo $employee['id']; ?>" class="text-indigo-600 hover:text-indigo-900 text-sm font-medium">View Profile</a>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</main>

<?php
// फुटर को शामिल करें
require_once 'footer.php';
?>