<?php
include 'config.php'; // Database connection

// Fetch employees with roles, responsibilities, department, and designation
$employees = mysqli_query($conn, "SELECT id, username, role, responsibilities, department, designation FROM users WHERE role = 'Employee'");

// Fetch performance data with department and designation
$performance = mysqli_query($conn, "SELECT performance.*, users.username, users.role, users.responsibilities, users.department, users.designation FROM performance JOIN users ON performance.employee_id = users.id");

// Insert performance data
if (isset($_POST['submit'])) {
    $employee_id = $_POST['employee_id'];
    $okr_target = $_POST['okr_target'];
    $okr_actual = $_POST['okr_actual'];
    $kpi_target = $_POST['kpi_target'];
    $kpi_actual = $_POST['kpi_actual'];
    $kra_target = $_POST['kra_target'];
    $kra_actual = $_POST['kra_actual'];
    $evaluation_period = $_POST['evaluation_period'];

    function safe_division($numerator, $denominator) {
        return ($denominator == 0) ? 0 : ($numerator / $denominator) * 100;
    }

    $okr_score = safe_division($okr_actual, $okr_target);
    $kpi_score = safe_division($kpi_actual, $kpi_target);
    $kra_score = safe_division($kra_actual, $kra_target);
    $total_marks = ($okr_score + $kpi_score + $kra_score) / 3;

    $query = "INSERT INTO performance (employee_id, okr_target, okr_actual, kpi_target, kpi_actual, kra_target, kra_actual, evaluation_period, marks) VALUES ('$employee_id', '$okr_target', '$okr_actual', '$kpi_target', '$kpi_actual', '$kra_target', '$kra_actual', '$evaluation_period', '$total_marks')";
    mysqli_query($conn, $query);
    header("Location: performance_management.php");
}

// Update performance data
if (isset($_POST['update'])) {
    $id = $_POST['id'];
    $employee_id = $_POST['employee_id'];
    $okr_target = $_POST['okr_target'];
    $okr_actual = $_POST['okr_actual'];
    $kpi_target = $_POST['kpi_target'];
    $kpi_actual = $_POST['kpi_actual'];
    $kra_target = $_POST['kra_target'];
    $kra_actual = $_POST['kra_actual'];
    $evaluation_period = $_POST['evaluation_period'];

    function safe_division($numerator, $denominator) {
        return ($denominator == 0) ? 0 : ($numerator / $denominator) * 100;
    }

    $okr_score = safe_division($okr_actual, $okr_target);
    $kpi_score = safe_division($kpi_actual, $kpi_target);
    $kra_score = safe_division($kra_actual, $kra_target);
    $total_marks = ($okr_score + $kpi_score + $kra_score) / 3;

    $query = "UPDATE performance SET employee_id='$employee_id', okr_target='$okr_target', okr_actual='$okr_actual', kpi_target='$kpi_target', kpi_actual='$kpi_actual', kra_target='$kra_target', kra_actual='$kra_actual', evaluation_period='$evaluation_period', marks='$total_marks' WHERE id='$id'";
    mysqli_query($conn, $query);
    header("Location: performance_management.php");
}

// Delete performance data
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $query = "DELETE FROM performance WHERE id='$id'";
    mysqli_query($conn, $query);
    header("Location: performance_management.php");
}

if (isset($_GET['edit'])) {
    $id = $_GET['edit'];
    $record = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM performance WHERE id='$id'"));
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Performance Management</title>
    <style>
        body {
            display: flex;
            margin: 0;
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
        }
        .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: 270px;
            padding: 20px;
            width: calc(100% - 290px);
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0px 0px 10px 0px #aaa;
            margin-bottom: 20px;
        }
        h2 {
            text-align: center;
        }
        label {
            font-weight: bold;
        }
        input, select {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }
        th, td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: center;
        }
        th {
            background: #007bff;
            color: white;
        }
        .btn {
            background: #28a745;
            color: white;
            padding: 10px;
            border: none;
            cursor: pointer;
            width: 100%;
            border-radius: 5px;
        }
        .btn:hover {
            background: #218838;
        }
        .btn-edit {
            background: #ffc107;
            color: black;
            padding: 5px 10px;
            border: none;
            cursor: pointer;
            border-radius: 5px;
        }
        .btn-edit:hover {
            background: #e0a800;
        }
        .btn-delete {
            background: #dc3545;
            color: white;
            padding: 5px 10px;
            border: none;
            cursor: pointer;
            border-radius: 5px;
        }
        .btn-delete:hover {
            background: #c82333;
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <h2>Mypeopleconnect</h2>
        <a class="dropdown-toggle active" href="dashboard_admin.php" aria-expanded="false">
            <i class="fas fa-home"></i> Organisation Chart
        </a>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-home"></i> DAP
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="manage_users.php">Employee Details</a></li>
                <li><a class="dropdown-item" href="manage_documents.php">Policies Rolled Out</a></li>
                <li><a class="dropdown-item" href="digital.php">Acceptance Confirmed</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-users"></i> CAB
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="attendanceexcel.php">Attendance Excel</a></li>
                <li><a class="dropdown-item" href="attendance.php">Attendance</a></li>
                <li><a class="dropdown-item" href="manage_mappings.php">managemappings</a></li>
                <li><a class="dropdown-item" href="attendance_sync.php">manageatt</a></li>
                <li><a class="dropdown-item" href="payroll_excel.php">Payroll Excel</a></li>
                <li><a class="dropdown-item" href="payroll_dashboard.php">Payroll</a></li>
                <li><a class="dropdown-item" href="leave_dashboard.php">Leave</a></li>
                <li><a class="dropdown-item" href="grievance_dashboard.php">Grievance Portal</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-user"></i> PEP
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="individual_rr.php">Individual R & R</a></li>
                <li><a class="dropdown-item" href="individual_kpi.php">Individual KPI</a></li>
                <li><a class="dropdown-item" href="login_credentials.php">Login Credentials</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-book"></i> L&D
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="incident_employee.php">Incident Portal</a></li>
                <li><a class="dropdown-item" href="training_dashboard.php">Training Portal</a></li>
                <li><a class="dropdown-item" href="rr.php">Rewards and Recognition</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-star"></i> AAA
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="employee_tiy.php">Employee TIY</a></li>
                <li><a class="dropdown-item" href="login_credentials.php">Login Credentials</a></li>
            </ul>
        </div>
        <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
    <div class="content">
        <div class="container">
            <h2>Employee Performance</h2>
            <form method="POST">
                <input type="hidden" name="id" value="<?php echo isset($record['id']) ? $record['id'] : ''; ?>">
                <label>Employee:</label>
                <select name="employee_id" required>
                    <?php while ($row = mysqli_fetch_assoc($employees)) { ?>
                        <option value="<?php echo $row['id']; ?>" <?php echo (isset($record['employee_id']) && $record['employee_id'] == $row['id']) ? 'selected' : ''; ?>>
                            <?php echo $row['username']; ?>
                        </option>
                    <?php } ?>
                </select>
                <label>Evaluation Period:</label>
                <select name="evaluation_period" required>
                    <option value="Quarterly" <?php echo (isset($record['evaluation_period']) && $record['evaluation_period'] == 'Quarterly') ? 'selected' : ''; ?>>Quarterly</option>
                    <option value="Half-Yearly" <?php echo (isset($record['evaluation_period']) && $record['evaluation_period'] == 'Half-Yearly') ? 'selected' : ''; ?>>Half-Yearly</option>
                    <option value="Yearly" <?php echo (isset($record['evaluation_period']) && $record['evaluation_period'] == 'Yearly') ? 'selected' : ''; ?>>Yearly</option>
                </select>
                <label>OKR Target:</label>
                <input type="number" name="okr_target" value="<?php echo isset($record['okr_target']) ? $record['okr_target'] : ''; ?>" required>
                <label>OKR Actual:</label>
                <input type="number" name="okr_actual" value="<?php echo isset($record['okr_actual']) ? $record['okr_actual'] : ''; ?>" required>
                <label>KPI Target:</label>
                <input type="number" name="kpi_target" value="<?php echo isset($record['kpi_target']) ? $record['kpi_target'] : ''; ?>" required>
                <label>KPI Actual:</label>
                <input type="number" name="kpi_actual" value="<?php echo isset($record['kpi_actual']) ? $record['kpi_actual'] : ''; ?>" required>
                <label>KRA Target:</label>
                <input type="number" name="kra_target" value="<?php echo isset($record['kra_target']) ? $record['kra_target'] : ''; ?>" required>
                <label>KRA Actual:</label>
                <input type="number" name="kra_actual" value="<?php echo isset($record['kra_actual']) ? $record['kra_actual'] : ''; ?>" required>
                <input type="submit" class="btn" name="<?php echo isset($record['id']) ? 'update' : 'submit'; ?>" value="<?php echo isset($record['id']) ? 'Update' : 'Submit'; ?>">
            </form>
        </div>
        <div class="container">
            <h2>Performance Records</h2>
            <table>
                <tr>
                    <th>Employee</th>
                    <th>Role</th>
                    <th>Department</th>
                    <th>Designation</th>
                    <th>Responsibilities</th>
                    <th>Evaluation Period</th>
                    <th>OKR Score</th>
                    <th>KPI Score</th>
                    <th>KRA Score</th>
                    <th>Total Marks</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
                <?php while ($row = mysqli_fetch_assoc($performance)) { ?>
                    <tr>
                        <td><?php echo htmlspecialchars($row['username']); ?></td>
                        
                        <td><?php echo htmlspecialchars($row['role']); ?></td>
                        <td><?php echo htmlspecialchars($row['department']); ?></td>
                        <td><?php echo htmlspecialchars($row['designation']); ?></td>
                        <td style="white-space: pre-wrap; word-wrap: break-word; max-width: 300px;">
    <?php echo nl2br(htmlspecialchars($row['responsibilities'])); ?>
</td>
</td>
                        <td><?php echo htmlspecialchars($row['evaluation_period']); ?></td>
                        <td><?php echo round($row['okr_target'] == 0 ? 0 : ($row['okr_actual'] / $row['okr_target']) * 100, 2); ?>%</td>
                        <td><?php echo round($row['kpi_target'] == 0 ? 0 : ($row['kpi_actual'] / $row['kpi_target']) * 100, 2); ?>%</td>
                        <td><?php echo round($row['kra_target'] == 0 ? 0 : ($row['kra_actual'] / $row['kra_target']) * 100, 2); ?>%</td>
                        <td><?php echo round($row['marks'], 2); ?>%</td>
                        <td>
                            <a href="performance_management.php?edit=<?php echo $row['id']; ?>" class="btn-edit">Edit</a>
                            </td><td><a href="performance_management.php?delete=<?php echo $row['id']; ?>" class="btn-delete" onclick="return confirm('Are you sure you want to delete this record?')">Delete</a>
                        </td>
                    </tr>
                <?php } ?>
            </table>
        </div>
    </div>
</body>
</html>