<?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 Admin';

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

/*
|--------------------------------------------------------------------------
| CREATE KPI
|--------------------------------------------------------------------------
*/
if(isset($_POST['save'])){
    $departmentId = intval($_POST['department_id']);
    $kpiName = trim($_POST['kpi_name']);
    $maxScore = intval($_POST['max_score']);

    $stmt = $conn->prepare("
    INSERT INTO performance_kpis
    (
        department_id,
        kpi_name,
        max_score
    )
    VALUES
    (
        ?,?,?
    )
    ");

    $stmt->bind_param(
        "isi",
        $departmentId,
        $kpiName,
        $maxScore
    );

    $stmt->execute();

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

/*
|--------------------------------------------------------------------------
| DELETE KPI
|--------------------------------------------------------------------------
*/
if(isset($_GET['delete'])){
    $id = intval($_GET['delete']);

    $conn->query("
    DELETE FROM performance_kpis
    WHERE id=$id
    ");

    header("Location: kpi_setup.php");
    exit;
}

$departments = $conn->query("
SELECT *
FROM departments
ORDER BY name
");

$kpis = $conn->query("
SELECT
k.*,
d.name department
FROM performance_kpis k
LEFT JOIN departments d ON d.id=k.department_id
ORDER BY d.name, k.kpi_name
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KPI Target Management - Executive Controls</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">KPI Allocation</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">Department KPI Provisioning</h1>
            <p class="text-xs sm:text-sm text-gray-500 mt-1">
                Establish analytical criteria metric fields &bull; Logged in 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">
            Security Clearance: <span class="font-black text-blue-400 uppercase"><?= htmlspecialchars($role); ?></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> Performance evaluation key benchmark metric map integrated successfully.
    </div>
    <?php endif; ?>

    <!-- Interactive Creation Workspace Panel -->
    <div class="space-y-3">
        <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">Configure New Indicator Map</h2>
        <div class="bg-white rounded-3xl p-5 sm:p-8 shadow-md border border-white/60">
            <form method="POST" class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
                    <div>
                        <label class="block mb-2 text-xs font-bold text-gray-500 uppercase tracking-wider">Target Org Division</label>
                        <select name="department_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 Department</option>
                            <?php while($d = $departments->fetch_assoc()): ?>
                            <option value="<?= $d['id'] ?>">
                                <?= htmlspecialchars($d['name']) ?>
                            </option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div>
                        <label class="block mb-2 text-xs font-bold text-gray-500 uppercase tracking-wider">KPI Assessment Matrix Title</label>
                        <input type="text" name="kpi_name" required placeholder="e.g., Guest Satisfaction Index" 
                               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 shadow-inner transition-all">
                    </div>

                    <div>
                        <label class="block mb-2 text-xs font-bold text-gray-500 uppercase tracking-wider">Scale Limit Ceiling (Max Value)</label>
                        <input type="number" name="max_score" value="5" required min="1" 
                               class="w-full bg-slate-50 border border-slate-200 p-3.5 rounded-xl text-sm font-bold text-gray-700 focus:outline-none focus:border-blue-500 focus:bg-white shadow-inner transition-all">
                    </div>
                </div>

                <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-xl">
                        Adding this tracking indicator updates the self-appraisal matrix and managerial evaluation score sheets for all assigned personnel records immediately.
                    </p>
                    <button type="submit" name="save" 
                            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">
                        Deploy KPI Metric
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Active Structural Records Configuration Matrix -->
    <div class="space-y-3">
        <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">Active Divisional Benchmarks Registry</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">Strategic KPI Matrix Criteria</th>
                            <th class="p-4 sm:p-5 text-center w-32">Metric Scale Limit</th>
                            <th class="p-4 sm:p-5 text-center w-28">Management Control</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-sm text-gray-700">
                        <?php if($kpis->num_rows == 0): ?>
                        <tr>
                            <td colspan="4" class="p-8 text-center text-gray-400 font-medium">
                                No Key Performance Indicators configured in system registries yet.
                            </td>
                        </tr>
                        <?php else: ?>
                            <?php while($row = $kpis->fetch_assoc()): ?>
                            <tr class="hover:bg-slate-50/50 transition-colors">
                                <td class="p-4 sm:p-5">
                                    <span class="inline-block bg-slate-100 text-slate-700 text-xs px-2.5 py-1 rounded-md font-bold uppercase tracking-wide">
                                        <?= htmlspecialchars($row['department'] ?? 'Unassigned Division') ?>
                                    </span>
                                </td>
                                <td class="p-4 sm:p-5 font-bold text-gray-800 whitespace-normal max-w-md">
                                    <?= htmlspecialchars($row['kpi_name']) ?>
                                </td>
                                <td class="p-4 sm:p-5 text-center">
                                    <span class="inline-block bg-blue-50 text-blue-700 font-mono text-xs font-black px-3 py-1 rounded-lg">
                                        1 &rarr; <?= intval($row['max_score']) ?> Points Max
                                    </span>
                                </td>
                                <td class="p-4 sm:p-5 text-center">
                                    <a href="?delete=<?= $row['id'] ?>" 
                                       onclick="return confirm('Confirm permanent removal of this key tracking metric benchmark? Historical calculations mapping to this record field may become decoupled.')" 
                                       class="inline-block bg-red-50 text-red-600 hover:bg-red-100 text-xs font-bold px-3 py-1.5 rounded-xl border border-red-100 transition-colors">
                                        Purge
                                    </a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

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