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

$userRole = strtolower($_SESSION['role'] ?? '');
$username = $_SESSION['username'] ?? 'Reviewing Manager';

if(!in_array($userRole, ['manager','admin','superadmin'])){
    die("Access Denied");
}

/*
|--------------------------------------------------------------------------
| SAVE MANAGER REVIEW
|--------------------------------------------------------------------------
*/
if(isset($_POST['submit_review'])){
    $appraisalId = intval($_POST['appraisal_id']);
    $managerComment = trim($_POST['manager_comment']);

    foreach($_POST['manager_score'] as $scoreId => $score){
        $score = intval($score);

        $stmt = $conn->prepare("
        UPDATE appraisal_scores
        SET manager_score=?
        WHERE id=?
        ");

        $stmt->bind_param("ii", $score, $scoreId);
        $stmt->execute();
    }

    $update = $conn->prepare("
    UPDATE employee_appraisals
    SET
        manager_comment=?,
        manager_reviewed_at=NOW(),
        status='Pending HR Review'
    WHERE id=?
    ");

    $update->bind_param("si", $managerComment, $appraisalId);
    $update->execute();

    header("Location: manager_review.php?saved=1");
    exit;
}

/*
|--------------------------------------------------------------------------
| APPRAISALS
|--------------------------------------------------------------------------
*/
$appraisals = $conn->query("
SELECT
ea.*,
e.name employee_name,
d.name department,
ap.title period_name
FROM employee_appraisals ea
LEFT JOIN employees e ON e.id=ea.employee_id
LEFT JOIN departments d ON d.id=e.department_id
LEFT JOIN appraisal_periods ap ON ap.id=ea.period_id
WHERE ea.status='Pending Manager Review'
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>Manager Performance Review - Leadership Desktop</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">Manager Evaluation</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">Manager Assessment Workspace</h1>
            <p class="text-xs sm:text-sm text-gray-500 mt-1">
                Evaluate direct report submissions &bull; Authenticated as <span class="font-extrabold text-blue-600"><?= htmlspecialchars($username); ?></span>
            </p>
        </div>
        <div class="bg-slate-950 text-white px-4 py-2 rounded-xl font-bold text-xs sm:text-sm shadow-sm text-center">
            Review Tier: <span class="font-black text-amber-400 uppercase"><?= htmlspecialchars($userRole); ?></span>
        </div>
    </div>

    <!-- Toast Feedback Alerts -->
    <?php if(isset($_GET['saved'])): ?>
    <div class="bg-emerald-50 border border-emerald-200 text-emerald-800 p-4 rounded-2xl shadow-sm flex items-center gap-3 text-sm font-semibold animate-fade-in">
        <span class="text-lg">📥</span> Managerial score matrix certified and successfully forwarded to HR oversight benches.
    </div>
    <?php endif; ?>

    <!-- Pending Workspace Queue Block -->
    <div class="space-y-4">
        <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">Awaiting Team Assessments</h2>

        <?php if($appraisals->num_rows == 0): ?>
        <div class="bg-white rounded-3xl p-8 text-center border border-white/60 shadow-sm">
            <p class="text-gray-400 font-medium text-sm">No pending self-appraisals require immediate operational action from your desk.</p>
        </div>
        <?php endif; ?>

        <?php while($appraisal = $appraisals->fetch_assoc()): ?>
        <div class="bg-white rounded-3xl p-5 sm:p-8 shadow-md border border-white/60 space-y-6">
            
            <!-- Header Identity Badge Layer -->
            <div class="flex flex-col sm:flex-row sm:items-center justify-between border-b border-slate-100 pb-5 gap-4">
                <div>
                    <h3 class="text-xl font-black text-gray-800"><?= htmlspecialchars($appraisal['employee_name']) ?></h3>
                    <p class="text-xs font-bold text-blue-600 uppercase tracking-wide mt-0.5"><?= htmlspecialchars($appraisal['department']) ?></p>
                </div>
                <div>
                    <span class="bg-blue-50 text-blue-700 border border-blue-100 px-4 py-1.5 rounded-xl font-bold text-xs uppercase tracking-wide">
                        <?= htmlspecialchars($appraisal['period_name']) ?>
                    </span>
                </div>
            </div>

            <!-- Qualitative Employee Statement -->
            <div class="space-y-2">
                <h4 class="text-xs font-bold text-slate-400 uppercase tracking-wider">Employee Self Evaluation Commentary</h4>
                <div class="bg-slate-50 p-4 rounded-2xl text-sm text-gray-700 border border-slate-100 leading-relaxed max-h-40 overflow-y-auto">
                    <?= nl2br(htmlspecialchars($appraisal['self_comment'])) ?>
                </div>
            </div>

            <!-- Evaluation Audit Form -->
            <form method="POST" class="space-y-6 pt-2">
                <input type="hidden" name="appraisal_id" value="<?= $appraisal['id'] ?>">

                <!-- Metrics Entry Table Matrix -->
                <div class="border border-slate-100 rounded-2xl overflow-hidden shadow-inner bg-slate-50/50">
                    <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-[10px] font-bold uppercase tracking-wider">
                                    <th class="p-4">Tracked KPI Assessment Criteria</th>
                                    <th class="p-4 text-center w-28">Self Score</th>
                                    <th class="p-4 text-center w-36">Supervisor Merit Selection</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 text-sm bg-white text-gray-700">
                                <?php
                                $scores = $conn->query("
                                SELECT s.*, k.kpi_name, k.max_score
                                FROM appraisal_scores s
                                LEFT JOIN performance_kpis k ON k.id=s.kpi_id
                                WHERE s.appraisal_id={$appraisal['id']}
                                ");
                                while($score = $scores->fetch_assoc()):
                                ?>
                                <tr class="hover:bg-slate-50/30 transition-colors">
                                    <td class="p-4 font-semibold text-gray-800 whitespace-normal max-w-lg">
                                        <?= htmlspecialchars($score['kpi_name']) ?>
                                    </td>
                                    <td class="p-4 text-center">
                                        <span class="inline-block bg-slate-100 text-slate-600 font-mono text-xs font-bold px-3 py-1 rounded-lg">
                                            <?= $score['self_score'] ?>
                                        </span>
                                    </td>
                                    <td class="p-4 text-center">
                                        <select name="manager_score[<?= $score['id'] ?>]" required 
                                                class="w-full bg-slate-50 border border-slate-200 p-2.5 rounded-xl text-xs font-black text-center text-blue-600 focus:outline-none focus:border-blue-500 focus:bg-white cursor-pointer transition-all">
                                            <option value="">Rate</option>
                                            <?php for($i = 1; $i <= $score['max_score']; $i++): ?>
                                            <option value="<?= $i ?>"><?= $i ?> / <?= $score['max_score'] ?></option>
                                            <?php endfor; ?>
                                        </select>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Descriptive Supervisor Commentary Box -->
                <div class="space-y-2">
                    <label class="block text-xs font-bold text-gray-500 uppercase tracking-wider">Managerial Performance Evaluation Summary</label>
                    <textarea name="manager_comment" rows="4" required 
                              placeholder="Provide data-driven supervisor validation summaries, observed workplace benchmarks, and targeted operational adjustments..." 
                              class="w-full bg-slate-50 border border-slate-200 p-4 rounded-2xl text-sm focus:outline-none focus:border-blue-500 focus:bg-white shadow-inner leading-relaxed transition-all"></textarea>
                </div>

                <!-- Action Controls Footer Pane -->
                <div class="pt-2 flex flex-col sm:flex-row items-center justify-between gap-4 border-t border-slate-50">
                    <p class="text-xs text-gray-400 leading-normal max-w-md">
                        Review all parameters carefully. Direct lock and submission transfers processing capabilities exclusively over to the HR audit panel.
                    </p>
                    <button type="submit" name="submit_review" 
                            class="w-full sm:w-auto bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-bold text-sm px-8 py-3.5 rounded-xl shadow-md hover:shadow-xl transition-all duration-300 transform hover:-translate-y-0.5 active:translate-y-0 text-center whitespace-nowrap">
                        Sign & Forward To HR
                    </button>
                </div>
            </form>

        </div>
        <?php endwhile; ?>
    </div>

</div>

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