<?php 
session_start();
include 'config.php';
include 'header.php';

// Ensure only Admins and Super Admins access this page
if (!isset($_SESSION['username']) || ($_SESSION['role'] != 'Super Admin' && $_SESSION['role'] != 'Admin')) {
    header("Location: index.php");
    exit();
}

// Fetch user details
$user_details_sql = "SELECT id, username, department, email, role FROM users";
$user_details_result = $conn->query($user_details_sql);

// Fetch employee performance data
$performance_sql = "SELECT ep.id, u.username, u.department, 
                    pm.kpa, pm.kra, pm.kpi, pm.weight, pm.periodicity, pm.measuring, pm.comments 
                    FROM employee_performance ep
                    JOIN users u ON ep.employee_id = u.id
                    JOIN performance_metrics pm ON ep.metric_id = pm.id";
$performance_result = $conn->query($performance_sql);
?>
<style>
    body {
        display: flex;
        margin: 0;
        font-family: Arial, sans-serif;
    }
    .sidebar {
        width: 250px;
        height: 100vh;
        background-color: rgb(234, 242, 250);
        padding: 20px;
        position: fixed;
        top: 0;
        left: 0;
        overflow-y: auto;
        box-shadow: 2px 0 5px rgba(23, 135, 226, 0.89);
    }
    .content {
        margin-left: 260px;
        width: calc(100% - 260px);
        padding: 20px;
    }
    .table {
        width: 100%;
    }
    .add-btn {
        background-color: #28a745;
        color: white;
        border: none;
        padding: 5px 10px;
        cursor: pointer;
        border-radius: 5px;
    }
    @media (max-width: 768px) {
        .sidebar {
            width: 100%;
            height: auto;
            position: relative;
        }
        .content {
            margin-left: 0;
            width: 100%;
        }
    }
</style>

<div class="sidebar">
    <h4>Dashboard</h4>
    <ul class="nav flex-column nav-pills">
        <li class="nav-item"><a class="nav-link" href="dashboard.php">Dashboard</a></li>
        <li class="nav-item"><a class="nav-link" href="manage_users.php">Manage Users</a></li>
        <li class="nav-item"><a class="nav-link" href="manage_documents.php">Manage Documents</a></li>
        <li class="nav-item"><a class="nav-link" href="attendance.php">Attendance</a></li>
        <li class="nav-item"><a class="nav-link" href="grievance_dashboard.php">Grievance Portal</a></li>
        <li class="nav-item"><a class="nav-link" href="leave_dashboard.php">Leave Portal</a></li>
        <li class="nav-item"><a class="nav-link" href="payroll.php">Payroll</a></li>
        <li class="nav-item"><a class="nav-link" href="performance_management.php">PMS</a></li>
        <li class="nav-item"><a class="nav-link" href="dashboard_training.php">Training Portal</a></li>
        <li class="nav-item"><a class="nav-link text-danger" href="logout.php">Logout</a></li>
    </ul>
</div>

<div class="content"> 
    <h1 class="text-primary text-center">Performance Management</h1>

    <div class="card mt-5 mx-auto">
        <div class="card-header bg-success text-white d-flex justify-content-between">
            <h2>Employee Performance Metrics</h2>
            <button class="add-btn" onclick="addPerformanceRow()">+</button>
        </div>
        <div class="card-body table-responsive">
            <table class="table table-bordered table-hover" id="performanceTable">
                <thead class="thead-dark">
                    <tr>
                        <th>Username</th>
                        <th>Department</th>
                        <th>KPA</th>
                        <th>KRA</th>
                        <th>KPI</th>
                        <th>Weight</th>
                        <th>Periodicity</th>
                        <th>Measuring</th>
                        <th>Comments</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $performance_result->fetch_assoc()) { ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['username']); ?></td>
                            <td><?php echo htmlspecialchars($row['department']); ?></td>
                            <td><?php echo htmlspecialchars($row['kpa']); ?></td>
                            <td><?php echo htmlspecialchars($row['kra']); ?></td>
                            <td><?php echo htmlspecialchars($row['kpi']); ?></td>
                            <td><?php echo htmlspecialchars($row['weight']); ?></td>
                            <td><?php echo htmlspecialchars($row['periodicity']); ?></td>
                            <td><?php echo htmlspecialchars($row['measuring']); ?></td>
                            <td><?php echo htmlspecialchars($row['comments']); ?></td>
                            <td>
                                <button class="btn btn-warning btn-sm">Edit</button>
                                <button class="btn btn-danger btn-sm">Delete</button>
                            </td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    function addPerformanceRow() {
        let table = document.getElementById("performanceTable").getElementsByTagName('tbody')[0];
        let newRow = table.insertRow();
        
        for (let i = 0; i < 9; i++) {
            let cell = newRow.insertCell(i);
            let input = document.createElement("input");
            input.type = "text";
            input.className = "form-control";
            cell.appendChild(input);
        }
        let actionCell = newRow.insertCell(9);
        actionCell.innerHTML = '<button class="btn btn-success btn-sm" onclick="savePerformance(this)">Save</button>';
    }

    function savePerformance(button) {
        let row = button.parentElement.parentElement;
        let inputs = row.getElementsByTagName("input");
        let data = [];
        for (let input of inputs) {
            data.push(input.value);
        }
        
        fetch('save_performance.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ performance: data })
        }).then(response => response.json()).then(data => {
            if (data.success) {
                alert("Performance saved successfully!");
                location.reload();
            } else {
                alert("Error saving performance");
            }
        });
    }
</script>

<?php include 'footer.php'; ?>
