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

$employeeId = intval($_SESSION['user_id']);
$username = $_SESSION['username'] ?? 'Employee Portal';
$role = $_SESSION['role'] ?? 'Staff Member';

$appraisals = $conn->query("
SELECT
ea.*,
ap.title period_name,
(
    SELECT AVG(self_score)
    FROM appraisal_scores
    WHERE appraisal_id=ea.id
) self_avg,
(
    SELECT AVG(manager_score)
    FROM appraisal_scores
    WHERE appraisal_id=ea.id
) manager_avg,
(
    SELECT AVG(hr_score)
    FROM appraisal_scores
    WHERE appraisal_id=ea.id
) hr_avg
FROM employee_appraisals ea
LEFT JOIN appraisal_periods ap ON ap.id=ea.period_id
WHERE ea.employee_id=$employeeId
ORDER BY ea.id DESC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Appraisals - Performance History</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Mulish', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans">

    <div class="flex">

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

        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            
            <!-- Standard Setup Sticky Context Header -->
            <header class="sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95 md:hidden" aria-label="Toggle Navigation">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <div>
                        <h1 class="text-sm font-black tracking-tight text-slate-950">My Performance Appraisals</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Evaluation & Leadership Metrics</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="hidden sm:flex flex-col text-right">
                        <span class="text-[11px] font-extrabold text-slate-950 leading-tight"><?= htmlspecialchars($username); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($role); ?></span>
                    </div>
                    <div class="w-7 h-7 bg-slate-200 border border-slate-300 rounded-lg flex items-center justify-center font-black text-xs text-slate-700 select-none uppercase">
                        <?= strtoupper(substr($username, 0, 1)); ?>
                    </div>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-6">

                <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                    
                    <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex items-center justify-between">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Evaluation Cycle Registry</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Track historical corporate assessments, score breakdowns, and developmental feedback notes.</p>
                        </div>
                    </div>

                    <div class="overflow-x-auto w-full">
                        <table class="w-full text-left border-collapse whitespace-nowrap">
                            <thead>
                                <tr class="bg-stone-50 border-b border-slate-300/80 text-slate-500 text-[9px] font-black uppercase tracking-wider">
                                    <th class="p-3 pl-6">Appraisal Cycle</th>
                                    <th class="p-3 text-center w-28">Self Avg</th>
                                    <th class="p-3 text-center w-28">Manager Avg</th>
                                    <th class="p-3 text-center w-28">HR Final Avg</th>
                                    <th class="p-3 text-center w-40">Review Status</th>
                                    <th class="p-3 text-center w-24 pr-6">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">
                                <?php if($appraisals->num_rows == 0): ?>
                                <tr>
                                    <td colspan="6" class="p-8 text-center text-slate-400 font-medium tracking-tight">
                                        No historical evaluation logs found for your personnel account record.
                                    </td>
                                </tr>
                                <?php else: ?>
                                    <?php while($row = $appraisals->fetch_assoc()): ?>
                                    <tr class="hover:bg-stone-50/50 transition-colors text-slate-800">
                                        <td class="p-3 pl-6 font-black text-slate-950 tracking-tight">
                                            <?= htmlspecialchars($row['period_name']) ?>
                                        </td>
                                        <td class="p-3 text-center font-mono font-semibold text-slate-600 text-[11px]">
                                            <?= $row['self_avg'] !== null ? number_format((float)$row['self_avg'], 2) : '—' ?>
                                        </td>
                                        <td class="p-3 text-center font-mono font-extrabold text-indigo-700 text-[11px]">
                                            <?= $row['manager_avg'] !== null ? number_format((float)$row['manager_avg'], 2) : '—' ?>
                                        </td>
                                        <td class="p-3 text-center font-mono font-black text-emerald-800 text-[11px]">
                                            <?= $row['hr_avg'] !== null ? number_format((float)$row['hr_avg'], 2) : '—' ?>
                                        </td>
                                        <td class="p-3 text-center">
                                            <?php
                                            $statusClass = 'bg-amber-50 text-amber-900 border-amber-300';
                                            switch($row['status']){
                                                case 'Completed':
                                                    $statusClass = 'bg-emerald-50 text-emerald-800 border-emerald-300';
                                                    break;
                                                case 'Pending HR Review':
                                                    $statusClass = 'bg-indigo-50 text-indigo-800 border-indigo-200';
                                                    break;
                                                case 'Pending Manager Review':
                                                    $statusClass = 'bg-amber-50 text-amber-900 border-amber-300';
                                                    break;
                                            }
                                            ?>
                                            <span class="inline-block px-2 py-0.5 rounded border text-[10px] font-black uppercase tracking-wider <?= $statusClass ?>">
                                                <?= htmlspecialchars($row['status']) ?>
                                            </span>
                                        </td>
                                        <td class="p-3 text-center pr-6">
                                            <button onclick="toggleDetails('<?= $row['id'] ?>')" 
                                                    class="bg-slate-950 hover:bg-indigo-700 text-white text-[10px] font-black px-3 py-1 rounded border border-transparent shadow-xs transition-all uppercase tracking-wider">
                                                View Breakdown
                                            </button>
                                        </td>
                                    </tr>
                                    
                                    <!-- Expandable Sub-panel Drawer Framework Component -->
                                    <tr id="details<?= $row['id'] ?>" style="display:none;" class="bg-stone-50/50">
                                        <td colspan="6" class="p-4 sm:p-5 border-b border-slate-300/80">
                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                                
                                                <!-- Supervisor Comments Box Frame -->
                                                <div class="space-y-1.5">
                                                    <h4 class="text-[9px] font-black text-slate-500 uppercase tracking-wider px-1">Manager Assessment Notes</h4>
                                                    <div class="bg-white border border-slate-300 rounded-lg p-3.5 text-[11px] font-semibold leading-relaxed text-slate-800 shadow-2xs min-h-[5rem]">
                                                        <?= $row['manager_comment'] ? nl2br(htmlspecialchars($row['manager_comment'])) : '<em class="text-slate-400 font-normal">No review comments provided yet.</em>' ?>
                                                    </div>
                                                </div>

                                                <!-- HR Oversight Comments Box Frame -->
                                                <div class="space-y-1.5">
                                                    <h4 class="text-[9px] font-black text-slate-500 uppercase tracking-wider px-1">HR Generalist Executive Sign-Off</h4>
                                                    <div class="bg-white border border-slate-300 rounded-lg p-3.5 text-[11px] font-semibold leading-relaxed text-slate-800 shadow-2xs min-h-[5rem]">
                                                        <?= $row['hr_comment'] ? nl2br(htmlspecialchars($row['hr_comment'])) : '<em class="text-slate-400 font-normal">Pending final structural determination.</em>' ?>
                                                    </div>
                                                </div>

                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>

            <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
                <p class="text-[9px] text-slate-500 font-mono tracking-wider">&copy; 2026 Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
            </footer>
        </div>
    </div>

    <script>
    function toggleDetails(id){
        let row = document.getElementById('details' + id);
        if(row.style.display === 'none'){
            row.style.display = 'table-row';
        } else {
            row.style.display = 'none';
        }
    }
    
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        if(sidebar && overlay) {
            sidebar.classList.toggle('-translate-x-full');
            overlay.classList.toggle('hidden');
        }
    }
    </script>
    <script src="../components/sidebar.js"></script>
</body>
</html>