<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

require '../config.php';
session_start();
session_write_close();

if(!isset($_SESSION['user_id'])){
    header("Location: ../login.php");
    exit;
}

$role = strtolower($_SESSION['role'] ?? '');
$username = $_SESSION['username'] ?? 'Executive';

if(
    !in_array(
        $role,
        ['hr','gm','admin','superadmin']
    )
){
    die("Access Denied");
}

/*
|--------------------------------------------------------------------------
| SUMMARY
|--------------------------------------------------------------------------
*/
$summary = $conn->query("
SELECT
COUNT(*) total,
SUM(
CASE
WHEN status='Completed'
THEN 1
ELSE 0
END
) completed
FROM employee_appraisals
")->fetch_assoc();

/*
|--------------------------------------------------------------------------
| OVERALL AVERAGE
|--------------------------------------------------------------------------
*/
$avgScore = $conn->query("
SELECT
AVG(hr_score) average_score
FROM appraisal_scores
WHERE hr_score IS NOT NULL
")->fetch_assoc();

/*
|--------------------------------------------------------------------------
| TOP PERFORMERS
|--------------------------------------------------------------------------
*/
$topPerformers = $conn->query("
SELECT
e.name,
d.name department,
AVG(s.hr_score) avg_score
FROM appraisal_scores s
LEFT JOIN employee_appraisals ea
ON ea.id=s.appraisal_id
LEFT JOIN employees e
ON e.id=ea.employee_id
LEFT JOIN departments d
ON d.id=e.department_id
WHERE ea.status='Completed'
GROUP BY ea.employee_id
ORDER BY avg_score DESC
LIMIT 10
");

/*
|--------------------------------------------------------------------------
| LOWEST PERFORMERS
|--------------------------------------------------------------------------
*/
$lowPerformers = $conn->query("
SELECT
e.name,
d.name department,
AVG(s.hr_score) avg_score
FROM appraisal_scores s
LEFT JOIN employee_appraisals ea
ON ea.id=s.appraisal_id
LEFT JOIN employees e
ON e.id=ea.employee_id
LEFT JOIN departments d
ON d.id=e.department_id
WHERE ea.status='Completed'
GROUP BY ea.employee_id
ORDER BY avg_score ASC
LIMIT 10
");

/*
|--------------------------------------------------------------------------
| DEPARTMENT RANKING
|--------------------------------------------------------------------------
*/
$departments = $conn->query("
SELECT
d.name department,
AVG(s.hr_score) avg_score
FROM appraisal_scores s
LEFT JOIN employee_appraisals ea
ON ea.id=s.appraisal_id
LEFT JOIN employees e
ON e.id=ea.employee_id
LEFT JOIN departments d
ON d.id=e.department_id
WHERE ea.status='Completed'
GROUP BY d.id
ORDER BY avg_score DESC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Performance Reports - Executive HR Boardroom</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-gradient-to-br from-slate-100 via-blue-50 to-indigo-100 min-h-screen flex flex-col md:flex-row overflow-x-hidden font-sans">

<?php include '../components/sidebar.php'; ?>

<div id="sidebar-overlay" class="fixed inset-0 bg-black/50 hidden z-40" onclick="toggleSidebar()"></div>

<!-- Responsive Mobile Navigation Bar -->
<div class="mobile-trigger-bar w-full bg-slate-900 text-white flex items-center justify-between p-4 md:hidden sticky top-0 z-30 shadow-md">
    <span class="font-bold tracking-wide">HR Analytics</span>
    <button onclick="toggleSidebar()" class="bg-white/10 hover:bg-white/20 px-3 py-2 rounded-lg text-xl transition">
        ☰
    </button>
</div>

<!-- Main Content Area Wrapper -->
<div id="main-content" class="flex-1 content-expanded transition-all duration-300 w-full p-4 sm:p-6 lg:p-8 space-y-6 sm:space-y-8">

    <!-- Top Profile Header Frame -->
    <div class="bg-white/70 backdrop-blur-xl border border-white/40 p-5 rounded-3xl shadow-sm flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <h1 class="text-2xl sm:text-3xl font-black text-gray-800">Performance Reports</h1>
            <p class="text-xs sm:text-sm text-gray-500 mt-1">
                Corporate Evaluation Analytics &bull; Signed in as <span class="font-extrabold text-blue-600"><?= htmlspecialchars($username); ?></span>
            </p>
        </div>
        <div class="bg-blue-100 text-blue-700 px-4 py-2 rounded-xl font-bold text-xs sm:text-sm shadow-sm text-center">
            Security Access: <span class="font-black uppercase"><?= htmlspecialchars($role); ?></span>
        </div>
    </div>

    <!-- Analytics Key Metrics Grid -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
        
        <div class="bg-white border border-slate-100 p-6 rounded-3xl shadow-md relative overflow-hidden group hover:shadow-lg transition-all">
            <div class="flex items-center justify-between mb-4">
                <span class="text-xs font-bold text-slate-400 uppercase tracking-wider">Total Appraisals</span>
                <span class="w-8 h-8 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center font-bold text-sm">🗂️</span>
            </div>
            <h2 class="text-3xl sm:text-4xl font-black text-slate-800 tracking-tight">
                <?= number_format($summary['total'] ?? 0) ?>
            </h2>
        </div>

        <div class="bg-white border border-slate-100 p-6 rounded-3xl shadow-md relative overflow-hidden group hover:shadow-lg transition-all">
            <div class="flex items-center justify-between mb-4">
                <span class="text-xs font-bold text-slate-400 uppercase tracking-wider">Completed Matrix</span>
                <span class="w-8 h-8 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center font-bold text-sm">✅</span>
            </div>
            <h2 class="text-3xl sm:text-4xl font-black text-emerald-600 tracking-tight">
                <?= number_format($summary['completed'] ?? 0) ?>
            </h2>
        </div>

        <div class="bg-white border border-slate-100 p-6 rounded-3xl shadow-md relative overflow-hidden group hover:shadow-lg transition-all sm:col-span-2 lg:col-span-1">
            <div class="flex items-center justify-between mb-4">
                <span class="text-xs font-bold text-slate-400 uppercase tracking-wider">Company Average Score</span>
                <span class="w-8 h-8 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center font-bold text-sm">📈</span>
            </div>
            <h2 class="text-3xl sm:text-4xl font-black text-indigo-600 tracking-tight">
                <?= number_format($avgScore['average_score'] ?? 0.00, 2) ?>
            </h2>
        </div>

    </div>

    <!-- Data Layout Matrix Groupings -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 sm:gap-8">
        
        <!-- TOP PERFORMERS -->
        <div class="space-y-3">
            <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">1. Highest Evaluated Talent</h2>
            <div class="bg-white rounded-3xl shadow-md border border-white/60 overflow-hidden">
                <div class="overflow-x-auto w-full">
                    <table class="w-full text-left border-collapse whitespace-nowrap">
                        <thead>
                            <tr class="bg-slate-50 border-b border-slate-100 text-slate-400 text-[11px] font-bold uppercase tracking-wider">
                                <th class="p-4 sm:p-5">Employee</th>
                                <th class="p-4 sm:p-5">Department</th>
                                <th class="p-4 sm:p-5 text-center">Score</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 text-sm text-gray-700">
                            <?php while($row = $topPerformers->fetch_assoc()): ?>
                            <tr class="hover:bg-slate-50/50 transition-colors">
                                <td class="p-4 sm:p-5 font-bold text-gray-800"><?= htmlspecialchars($row['name']) ?></td>
                                <td class="p-4 sm:p-5 text-gray-500 font-medium"><?= htmlspecialchars($row['department']) ?></td>
                                <td class="p-4 sm:p-5 text-center">
                                    <span class="inline-block bg-emerald-50 text-emerald-700 font-black px-3 py-1 rounded-lg text-xs font-mono">
                                        <?= number_format($row['avg_score'] ?? 0.00, 2) ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- LOWEST PERFORMERS -->
        <div class="space-y-3">
            <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">2. Needs Support / Performance Gap</h2>
            <div class="bg-white rounded-3xl shadow-md border border-white/60 overflow-hidden">
                <div class="overflow-x-auto w-full">
                    <table class="w-full text-left border-collapse whitespace-nowrap">
                        <thead>
                            <tr class="bg-slate-50 border-b border-slate-100 text-slate-400 text-[11px] font-bold uppercase tracking-wider">
                                <th class="p-4 sm:p-5">Employee</th>
                                <th class="p-4 sm:p-5">Department</th>
                                <th class="p-4 sm:p-5 text-center">Score</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 text-sm text-gray-700">
                            <?php while($row = $lowPerformers->fetch_assoc()): ?>
                            <tr class="hover:bg-slate-50/50 transition-colors">
                                <td class="p-4 sm:p-5 font-bold text-gray-800"><?= htmlspecialchars($row['name']) ?></td>
                                <td class="p-4 sm:p-5 text-gray-500 font-medium"><?= htmlspecialchars($row['department']) ?></td>
                                <td class="p-4 sm:p-5 text-center">
                                    <span class="inline-block bg-rose-50 text-rose-700 font-black px-3 py-1 rounded-lg text-xs font-mono">
                                        <?= number_format($row['avg_score'] ?? 0.00, 2) ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>

    <!-- DEPARTMENT RANKINGS -->
    <div class="space-y-3">
        <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">3. Divisional Performance Index</h2>
        <div class="bg-white rounded-3xl shadow-md border border-white/60 overflow-hidden">
            <div class="overflow-x-auto w-full">
                <table class="w-full text-left border-collapse whitespace-nowrap">
                    <thead>
                        <tr class="bg-slate-50 border-b border-slate-100 text-slate-400 text-[11px] font-bold uppercase tracking-wider">
                            <th class="p-4 sm:p-5">Department Division</th>
                            <th class="p-4 sm:p-5 text-center">Aggregate Benchmark Rating</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-sm text-gray-700">
                        <?php while($row = $departments->fetch_assoc()): ?>
                        <tr class="hover:bg-slate-50/50 transition-colors">
                            <td class="p-4 sm:p-5 font-bold text-slate-800">
                                <?= htmlspecialchars($row['department'] ?? 'Unassigned Division') ?>
                            </td>
                            <td class="p-4 sm:p-5 text-center">
                                <span class="inline-block bg-blue-50 text-blue-700 font-black px-4 py-1.5 rounded-xl text-xs font-mono border border-blue-100">
                                    <?= number_format($row['avg_score'] ?? 0.00, 2) ?>
                                </span>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<script src="../components/sidebar.js"></script>
</body>
</html>