<?php
// Start the session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Check if employee is logged in and the session ID is set
if (!isset($_SESSION['id']) || $_SESSION['role'] != 'Employee') {
    header('Location: login.php'); // Redirect to login page if not logged in or role is not Employee
    exit();
}

// Connect to the database
include('config.php');

// Get the employee ID from session
$employee_id = $_SESSION['id'];

// Fetch grievances from the database for this employee
$sql = "SELECT * FROM grievances WHERE employee_id = '$employee_id' ORDER BY created_at DESC";
$result = mysqli_query($conn, $sql);

// Debug: Check if the query is successful
if (!$result) {
    die("Error fetching grievances: " . mysqli_error($conn));
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Grievances</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .container {
            margin-top: 50px;
        }
        .grievance-card {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>View Grievances</h2>

        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-success">
                <?= $_SESSION['message']; ?>
            </div>
            <?php unset($_SESSION['message']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger">
                <?= $_SESSION['error']; ?>
            </div>
            <?php unset($_SESSION['error']); ?>
        <?php endif; ?>

        <?php if (mysqli_num_rows($result) > 0): ?>
            <?php while ($row = mysqli_fetch_assoc($result)): ?>
                <div class="card grievance-card">
                    <div class="card-body">
                        <h5 class="card-title"><?= htmlspecialchars($row['title']); ?></h5>
                        <p class="card-text"><?= nl2br(htmlspecialchars($row['description'])); ?></p>
                        <p class="card-text"><strong>Status:</strong> <?= htmlspecialchars($row['status']); ?></p>
                        <p class="card-text"><small class="text-muted">Created on <?= $row['created_at']; ?></small></p>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <p>No grievances submitted yet.</p>
        <?php endif; ?>
    </div>
</body>
</html>
