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

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

/*
|--------------------------------------------------------------------------
| EMPLOYEE DETAILS
|--------------------------------------------------------------------------
*/
$employee = $conn->query("
SELECT
e.*,
d.name department
FROM employees e
LEFT JOIN departments d
ON d.id=e.department_id
WHERE e.id=$userId
")->fetch_assoc();

if(!$employee){
    die("Employee record not found");
}

$departmentId = intval($employee['department_id']);

/*
|--------------------------------------------------------------------------
| SAVE APPRAISAL
|--------------------------------------------------------------------------
*/
if(isset($_POST['submit'])){
    $periodId = intval($_POST['period_id']);
    $comment = trim($_POST['self_comment']);

    $stmt = $conn->prepare("
    INSERT INTO employee_appraisals
    (
        period_id,
        employee_id,
        self_comment,
        status
    )
    VALUES
    (
        ?,?,?,
        'Pending Manager Review'
    )
    ");

    $stmt->bind_param(
        "iis",
        $periodId,
        $userId,
        $comment
    );

    $stmt->execute();
    $appraisalId = $stmt->insert_id;

    if(!$appraisalId){
        $appraisalId = $conn->insert_id;
    }

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

        $save = $conn->prepare("
        INSERT INTO appraisal_scores
        (
            appraisal_id,
            kpi_id,
            self_score
        )
        VALUES
        (
            ?,?,?
        )
        ");

        $save->bind_param(
            "iii",
            $appraisalId,
            $kpiId,
            $score
        );

        $save->execute();
    }

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

/*
|--------------------------------------------------------------------------
| OPEN PERIODS
|--------------------------------------------------------------------------
*/
$periods = $conn->query("
SELECT *
FROM appraisal_periods
WHERE status='Open'
ORDER BY id DESC
");

/*
|--------------------------------------------------------------------------
| DEPARTMENT KPIs
|--------------------------------------------------------------------------
*/
$kpis = $conn->query("
SELECT *
FROM performance_kpis
WHERE department_id=$departmentId
ORDER BY kpi_name
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Self Appraisal - Executive 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">Self 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">Employee Self Appraisal</h1>
            <p class="text-xs sm:text-sm text-gray-500 mt-1">
                Evaluation Statement Submission &bull; Logged 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">
            Division Assignment: <span class="font-black uppercase"><?= htmlspecialchars($employee['department'] ?? 'General Corporate'); ?></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> Your personal performance matrix appraisal has been locked and routed to leadership review.
    </div>
    <?php endif; ?>

    <!-- Form Panel Workspace Block -->
    <div class="space-y-3">
        <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">Evaluation Scope Provisioning</h2>
        <div class="bg-white rounded-3xl p-5 sm:p-8 shadow-md border border-white/60">
            
            <form method="POST" class="space-y-8">
                <!-- Parameters Allocation Group -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block mb-2 text-xs font-bold text-gray-500 uppercase tracking-wider">Appraisal Cycle Period</label>
                        <select name="period_id" required 
                                class="w-full bg-slate-50 border border-slate-200 p-3.5 rounded-xl text-sm font-semibold text-gray-700 focus:outline-none focus:border-blue-500 focus:bg-white transition-all shadow-inner cursor-pointer">
                            <option value="">Select Target Period</option>
                            <?php while($p = $periods->fetch_assoc()): ?>
                            <option value="<?= $p['id'] ?>">
                                <?= htmlspecialchars($p['title']) ?>
                            </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block mb-2 text-xs font-bold text-gray-500 uppercase tracking-wider">Assigned Department</label>
                        <input type="text" readonly value="<?= htmlspecialchars($employee['department']) ?>" 
                               class="w-full bg-slate-100/80 border border-slate-200 p-3.5 rounded-xl text-sm font-bold text-slate-500 cursor-not-allowed">
                    </div>
                </div>

                <hr class="border-slate-100">

                <!-- Performance KPIs Evaluation Block -->
                <div class="space-y-4">
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center font-bold">📊</div>
                        <h2 class="text-lg font-extrabold text-gray-800">KPI Performance Benchmarking Matrix</h2>
                    </div>

                    <div class="border border-slate-100 rounded-2xl overflow-hidden shadow-sm">
                        <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">Performance Metric Benchmark Descriptor</th>
                                        <th class="p-4 sm:p-5 text-center w-36">Self Merit Score</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-100 text-sm text-gray-700">
                                    <?php if($kpis->num_rows == 0): ?>
                                    <tr>
                                        <td colspan="2" class="p-8 text-center text-gray-400 font-medium">
                                            No tracking indicators mapped to this department division.
                                        </td>
                                    </tr>
                                    <?php else: ?>
                                        <?php while($kpi = $kpis->fetch_assoc()): ?>
                                        <tr class="hover:bg-slate-50/40 transition-colors">
                                            <td class="p-4 sm:p-5 font-bold text-gray-800 whitespace-normal max-w-xl">
                                                <?= htmlspecialchars($kpi['kpi_name']) ?>
                                            </td>
                                            <td class="p-4 sm:p-5 text-center">
                                                <select name="score[<?= $kpi['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="">Score</option>
                                                    <?php for($i = 1; $i <= $kpi['max_score']; $i++): ?>
                                                    <option value="<?= $i ?>"><?= $i ?> / <?= $kpi['max_score'] ?></option>
                                                    <?php endfor; ?>
                                                </select>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Descriptive Comments Text Area -->
                <div class="space-y-2">
                    <label class="block text-xs font-bold text-gray-500 uppercase tracking-wider">
                        Self Assessment Qualitative Statement
                    </label>
                    <textarea name="self_comment" rows="5" required 
                              placeholder="Outline your milestones, structural achievements, core workplace strengths, and projected areas for target growth across this lifecycle." 
                              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>

                <!-- Form Controls Actions Footnote -->
                <div class="pt-2 flex flex-col sm:flex-row items-center justify-between gap-4 border-t border-slate-100">
                    <p class="text-xs text-gray-400 leading-normal max-w-md">
                        Please review all score inputs carefully. Submission routes the evaluations matrix to your designated line management review tier immediately.
                    </p>
                    <button type="submit" name="submit" 
                            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">
                        Lock & Submit To Manager
                    </button>
                </div>
            </form>

        </div>
    </div>

</div>

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